answer
stringlengths
17
10.2M
package com.github.solairerove.woodstock.domain; import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; @Data @Document public class Task implements Serializable { @Id private String id; private String question; private Boolean enable; private Boolean correct; private Collection<? extends Ticket> tickets = new ArrayList<>(); public Task() { } public Task(String question, Collection<? extends Ticket> tickets) { this.question = question; this.enable = Boolean.TRUE; this.correct = Boolean.FALSE; this.tickets = tickets; } public Task(String question, Boolean enable, Boolean correct, Collection<? extends Ticket> tickets) { this.question = question; this.enable = enable; this.correct = correct; this.tickets = tickets; } }
package com.itemis.maven.plugins.cdi; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.AfterBeanDiscovery; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.Extension; import javax.inject.Named; import org.apache.commons.lang3.StringUtils; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.settings.Settings; import org.eclipse.aether.RepositorySystemSession; import org.eclipse.aether.impl.ArtifactResolver; import org.eclipse.aether.repository.RemoteRepository; import org.jboss.weld.environment.se.Weld; import org.jboss.weld.environment.se.WeldContainer; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; import com.itemis.maven.plugins.cdi.annotations.MojoProduces; import com.itemis.maven.plugins.cdi.annotations.ProcessingStep; import com.itemis.maven.plugins.cdi.internal.beans.CdiBeanWrapper; import com.itemis.maven.plugins.cdi.internal.beans.CdiProducerBean; import com.itemis.maven.plugins.cdi.internal.util.CDIUtil; import com.itemis.maven.plugins.cdi.internal.util.MavenUtil; import com.itemis.maven.plugins.cdi.internal.util.workflow.ProcessingWorkflow; import com.itemis.maven.plugins.cdi.internal.util.workflow.WorkflowExecutor; import com.itemis.maven.plugins.cdi.internal.util.workflow.WorkflowUtil; import com.itemis.maven.plugins.cdi.logging.MavenLogWrapper; import de.vandermeer.asciitable.v2.RenderedTable; import de.vandermeer.asciitable.v2.V2_AsciiTable; import de.vandermeer.asciitable.v2.render.V2_AsciiTableRenderer; import de.vandermeer.asciitable.v2.render.WidthLongestLine; import de.vandermeer.asciitable.v2.row.ContentRow; import de.vandermeer.asciitable.v2.themes.V2_E_TableThemes; /** * An abstract Mojo that enables CDI-based dependency injection for the current maven plugin.<br> * This Mojo enables you to decouple different parts of your plugin implementation and also dynamically inject * additional funktionality into your plugin.<br> * <br> * * <b>ATTENTION:</b> Please do not use annotations such as {@code @javax.inject.Inject} or * {@code @javax.enterprise.inject.Produces} directly in your Mojo! There are special replacements for that in the * annotations package of this library. Using CDI annotations directly in the Mojo would trigger Maven's own CDI * adaption!<br> * <br> * * Using this abstract Mojo as the parent of your own Mojo, you can simply see the Mojo class as a data container whose * single responsibility is to provide parameters for your business logic implementations. Simply get the * Mojo parameters injected and use the producer annotation to provide the bean to your implementations: * * <pre> * &#64;Parameter * &#64;MojoProduces * &#64;Named("sourcePath") * private String sourcePath; * * &#64;Parameter(defaultValue = "${reactorProjects}", readonly = true, required = true) * &#64;MojoProduces * &#64;Named("reactorProjects") * private List&lt;MavenProject&gt; reactorProjects; * </pre> * * Or use a producer method for the logger: * * <pre> * &#64;MojoProduces * public MavenLogWrapper createLogWrapper() { * MavenLogWrapper log = new MavenLogWrapper(getLog()); * if (this.enableLogTimestamps) { * log.enableLogTimestamps(); * } * return log; * } * </pre> * * <b>ATTENTION:</b> Make sure to not override the {@link #execute()} method since this method is responsible for the * CDI setup and will * trigger your business logic impelementations automatically.<br> * Implement your business logic in one or more classes that are annotated with {@link ProcessingStep} and implement * {@link CDIMojoProcessingStep}. Then orchestrate your standard business workflow in a worflow descriptor file.<br> * <br> * * <h1>The Workflow Descriptor</h1> * <ul> * <li>The descriptor is located under <i>META-INF/workflows</i></li> * <li>The name of the workflow descriptor file must match the name of the goal. F.i. goal="perform" * workflow-file="META-INF/workflows/perform"</li> * <li>A simple workflow lists just all processing step ids in the respective order (each id on a new line).</li> * <li>Steps that are encapsuled in <code>parallel{}</code> are executed in parallel. All other steps will be executed * sequentially.</li> * <li>A line starting with a <code>#</code> will be treated as a comment.</li> * </ul> * * <h2>A Sample Workflow</h2> * goal=perform * workflow-file=META-INF/workflows/perform * * <pre> * init * # The following steps can be run in parallel since they do not modify the project but only perform some checks * parallel { * checkUser * checkConnection * checkAether * } * compute * upload * validate * </pre> * * @author <a href="mailto:stanley.hillner@itemis.de">Stanley Hillner</a> * @since 1.0.0 */ public class AbstractCDIMojo extends AbstractMojo implements Extension { private static final String DEFAULT_WORKFLOW_DIR = "META-INF/workflows"; private static final String SYSPROP_PRINT_WF = "printWorkflow"; private static final String SYSPROP_PRINT_STEPS = "printSteps"; @Component public ArtifactResolver _resolver; @Parameter(defaultValue = "${settings}", readonly = true, required = true) public Settings _settings; @Parameter(readonly = true, defaultValue = "${repositorySystemSession}") public RepositorySystemSession _repoSystemSession; @Parameter(readonly = true, defaultValue = "${project.remotePluginRepositories}") public List<RemoteRepository> _pluginRepos; @Parameter(property = "workflow") public File workflowDescriptor; @Parameter(defaultValue = "true", property = "enableLogTimestamps") @MojoProduces @Named("enableLogTimestamps") public boolean enableLogTimestamps; @MojoProduces public final MavenLogWrapper createLogWrapper() { MavenLogWrapper log = new MavenLogWrapper(getLog()); if (this.enableLogTimestamps) { log.enableLogTimestamps(); } return log; } @Override public final void execute() throws MojoExecutionException, MojoFailureException { if (printDefaultWorkflow()) { return; } System.setProperty("org.jboss.logging.provider", "slf4j"); String logLevel = "info"; if (getLog().isDebugEnabled()) { logLevel = "debug"; } System.setProperty("org.slf4j.simpleLogger.log.org.jboss.weld", logLevel); Weld weld = new Weld(); weld.addExtension(this); addPluginDependencies(weld); WeldContainer weldContainer = null; try { weldContainer = weld.initialize(); Map<String, CDIMojoProcessingStep> steps = getAllProcessingSteps(weldContainer); if (printAvailableSteps(steps)) { return; } ProcessingWorkflow workflow = WorkflowUtil.parseWorkflow(getWorkflowDescriptor(), getGoalName()); WorkflowUtil.addExecutionContexts(workflow); WorkflowExecutor executor = new WorkflowExecutor(workflow, steps, getProject(), getLog()); executor.validate(!this._settings.isOffline()); executor.execute(); } finally { if (weldContainer != null && weldContainer.isRunning()) { weldContainer.shutdown(); } } } private boolean printDefaultWorkflow() throws MojoExecutionException { if (System.getProperty(SYSPROP_PRINT_WF) == null) { return false; } PluginDescriptor pluginDescriptor = getPluginDescriptor(); StringBuilder sb = new StringBuilder(); if (StringUtils.isNotBlank(pluginDescriptor.getGoalPrefix())) { sb.append(pluginDescriptor.getGoalPrefix()); } else { sb.append(pluginDescriptor.getGroupId()).append(':').append(pluginDescriptor.getArtifactId()).append(':') .append(pluginDescriptor.getVersion()); } sb.append(':').append(getGoalName()); Log log = createLogWrapper(); log.info("Default workflow for '" + sb + "':"); String goalName = getGoalName(); int x = 77 - goalName.length(); int a = x / 2; int b = x % 2 == 1 ? a + 1 : a; StringBuilder separator = new StringBuilder(); separator.append(Strings.repeat("=", a)).append(' ').append(goalName).append(' ').append(Strings.repeat("=", b)); System.out.println(separator); InputStream in = null; try { in = getWorkflowDescriptor(); ByteStreams.copy(in, System.out); } catch (IOException e) { throw new MojoExecutionException("A problem occurred during the serialization of the defualt workflow.", e); } finally { Closeables.closeQuietly(in); } System.out.println(separator); return true; } private boolean printAvailableSteps(Map<String, CDIMojoProcessingStep> steps) throws MojoExecutionException { if (System.getProperty(SYSPROP_PRINT_STEPS) == null) { return false; } V2_AsciiTable table = new V2_AsciiTable(); table.addRule(); ContentRow header = table.addRow("ID", "DESCRIPTION", "REQUIRES ONLINE"); header.setAlignment(new char[] { 'c', 'c', 'c' }); table.addStrongRule(); List<String> sortedIds = Lists.newArrayList(steps.keySet()); Collections.sort(sortedIds); for (String id : sortedIds) { ProcessingStep annotation = steps.get(id).getClass().getAnnotation(ProcessingStep.class); ContentRow data = table.addRow(annotation.id(), annotation.description(), annotation.requiresOnline()); data.setAlignment(new char[] { 'l', 'l', 'c' }); table.addRule(); } V2_AsciiTableRenderer renderer = new V2_AsciiTableRenderer(); renderer.setTheme(V2_E_TableThemes.UTF_STRONG_DOUBLE.get()); renderer.setWidth(new WidthLongestLine().add(10, 20).add(20, 50).add(10, 10)); RenderedTable renderedTable = renderer.render(table); Log log = createLogWrapper(); log.info( "The following processing steps are available on classpath and can be configured as part of a custom workflow."); System.out.println(renderedTable); return true; } @SuppressWarnings("unused") // will be called automatically by the CDI container once the bean discovery has finished private void processMojoCdiProducerFields(@Observes AfterBeanDiscovery event, BeanManager beanManager) throws MojoExecutionException { Set<Field> fields = Sets.newHashSet(getClass().getFields()); fields.addAll(Sets.newHashSet(getClass().getDeclaredFields())); for (Field f : fields) { if (f.isAnnotationPresent(MojoProduces.class)) { try { f.setAccessible(true); event.addBean( new CdiBeanWrapper<Object>(f.get(this), f.getGenericType(), f.getType(), CDIUtil.getCdiQualifiers(f))); } catch (Throwable t) { throw new MojoExecutionException("Could not process CDI producer field of the Mojo.", t); } } } } @SuppressWarnings({ "unused", "unchecked", "rawtypes" }) // will be called automatically by the CDI container once the bean discovery has finished private void processMojoCdiProducerMethods(@Observes AfterBeanDiscovery event, BeanManager beanManager) throws MojoExecutionException { // no method parameter injection possible at the moment since the container is not yet initialized at this point! Set<Method> methods = Sets.newHashSet(getClass().getMethods()); methods.addAll(Sets.newHashSet(getClass().getDeclaredMethods())); for (Method m : methods) { if (m.getReturnType() != Void.class && m.isAnnotationPresent(MojoProduces.class)) { try { event.addBean(new CdiProducerBean(m, this, beanManager, m.getGenericReturnType(), m.getReturnType(), CDIUtil.getCdiQualifiers(m))); } catch (Throwable t) { throw new MojoExecutionException("Could not process CDI producer method of the Mojo.", t); } } } } private void addPluginDependencies(Weld weld) throws MojoExecutionException { PluginDescriptor pluginDescriptor = getPluginDescriptor(); List<Dependency> dependencies = pluginDescriptor.getPlugin().getDependencies(); for (Dependency d : dependencies) { Optional<File> f = MavenUtil.resolvePluginDependency(d, this._pluginRepos, this._resolver, this._repoSystemSession); if (f.isPresent()) { CDIUtil.addAllClasses(weld, getClass().getClassLoader(), f.get(), getLog()); } else { throw new MojoExecutionException("Could not resolve the following plugin dependency: " + d); } } } private Map<String, CDIMojoProcessingStep> getAllProcessingSteps(WeldContainer weldContainer) { Map<String, CDIMojoProcessingStep> steps = Maps.newHashMap(); Collection<CDIMojoProcessingStep> beans = CDIUtil.getAllBeansOfType(weldContainer, CDIMojoProcessingStep.class); for (CDIMojoProcessingStep bean : beans) { ProcessingStep annotation = bean.getClass().getAnnotation(ProcessingStep.class); if (annotation != null) { String id = annotation.id(); Preconditions.checkState(!steps.containsKey(id), "The processing step id '" + id + "' is not unique!"); steps.put(id, bean); } } return steps; } private String getGoalName() { PluginDescriptor pluginDescriptor = getPluginDescriptor(); for (MojoDescriptor mojoDescriptor : pluginDescriptor.getMojos()) { if (mojoDescriptor.getImplementation().equals(getClass().getName())) { return mojoDescriptor.getGoal(); } } return null; } private PluginDescriptor getPluginDescriptor() { return (PluginDescriptor) getPluginContext().get("pluginDescriptor"); } private MavenProject getProject() { return (MavenProject) getPluginContext().get("project"); } private InputStream getWorkflowDescriptor() throws MojoExecutionException { MavenLogWrapper log = createLogWrapper(); log.info("Constructing workflow for processing"); if (this.workflowDescriptor != null) { log.debug("Requested overriding of workflow with file: " + this.workflowDescriptor.getAbsolutePath()); if (this.workflowDescriptor.exists() && this.workflowDescriptor.isFile()) { try { log.info("Workflow of goal '" + getPluginDescriptor().getGoalPrefix() + ':' + getGoalName() + "' will be overriden by file '" + this.workflowDescriptor.getAbsolutePath() + "'."); return new FileInputStream(this.workflowDescriptor); } catch (Exception e) { throw new MojoExecutionException("Unable to load custom workflow for goal " + getGoalName(), e); } } else { throw new MojoExecutionException( "Unable to load custom workflow for goal " + getPluginDescriptor().getGoalPrefix() + ':' + getGoalName() + ". The workflow file '" + this.workflowDescriptor.getAbsolutePath() + "' does not exist!"); } } log.info("Goal '" + getPluginDescriptor().getGoalPrefix() + ':' + getGoalName() + "' will use default workflow packaged with the plugin."); return Thread.currentThread().getContextClassLoader() .getResourceAsStream(DEFAULT_WORKFLOW_DIR + "/" + getGoalName()); } }
package com.hisham.design; import android.app.ProgressDialog; import android.content.Intent; import android.content.IntentSender; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.Scope; import com.google.android.gms.plus.Plus; import com.google.android.gms.plus.model.people.Person; public class SocialLoginActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, View.OnClickListener { /* Request code used to invoke sign in user interactions. */ private static final int RC_SIGN_IN = 0; /* Client used to interact with Google APIs. */ private GoogleApiClient mGoogleApiClient; /** * True if the sign-in button was clicked. When true, we know to resolve all * issues preventing sign-in without waiting. */ private boolean mSignInClicked; /** * True if we are in the process of resolving a ConnectionResult */ private boolean mIntentInProgress; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_social_login); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API) .addScope(new Scope("profile")) .build(); findViewById(R.id.sign_in_button).setOnClickListener(this); findViewById(R.id.logout).setOnClickListener(this); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } // Sign out the user // You can add a sign out button to your app. Create a button in your app to act as your sign out button. // Attach an onClickListener to the button and configure the onClick method to disconnect the GoogleApiClient: public void onClick(View view) { if (view.getId() == R.id.sign_in_button && !mGoogleApiClient.isConnecting()) { mSignInClicked = true; mGoogleApiClient.connect(); progressDialog = ProgressDialog.show(this, "Please Wait...", "Google+ Sign In.", true); } if (view.getId() == R.id.logout) { if (mGoogleApiClient.isConnected()) { mGoogleApiClient.clearDefaultAccountAndReconnect(); } } } @Override public void onConnectionFailed(ConnectionResult result) { if (!mIntentInProgress) { if (mSignInClicked && result.hasResolution()) { // The user has already clicked 'sign-in' so we attempt to resolve all // errors until the user is signed in, or they cancel. try { result.startResolutionForResult(this, RC_SIGN_IN); mIntentInProgress = true; } catch (IntentSender.SendIntentException e) { // The intent was canceled before it was sent. Return to the default // state and attempt to connect to get an updated ConnectionResult. mIntentInProgress = false; mGoogleApiClient.connect(); } } } } @Override public void onConnected(Bundle connectionHint) { mSignInClicked = false; if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); String personName = currentPerson.getDisplayName(); //String personPhoto = currentPerson.getImage(); String personGooglePlusProfile = currentPerson.getUrl(); String email = Plus.AccountApi.getAccountName(mGoogleApiClient); Toast.makeText(this, "User is connected: " + personName + " | Email: " + email, Toast.LENGTH_LONG).show(); } } protected void onActivityResult(int requestCode, int responseCode, Intent intent) { progressDialog.dismiss(); if (requestCode == RC_SIGN_IN) { if (responseCode != RESULT_OK) { mSignInClicked = false; } mIntentInProgress = false; if (!mGoogleApiClient.isConnected()) { mGoogleApiClient.reconnect(); } } } @Override public void onConnectionSuspended(int cause) { mGoogleApiClient.connect(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_social_login, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package com.kstruct.markdown; import java.io.File; import java.nio.file.Path; import java.util.Arrays; import java.util.Map; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; @Mojo(name = "generate-static-site") public class StaticSiteGeneratorMojo extends AbstractMojo { @Parameter( property = "inputDirectory") private File inputDirectory; @Parameter( property = "outputDirectory") private File outputDirectory; @Parameter( property = "siteName") private String siteName; @Parameter( property = "extraConfig") private Map<String,Object> extraConfig; @Parameter( property = "strictLinkChecking") private Boolean strictLinkChecking; @Parameter( property = "template") private Path template; public void execute() throws MojoExecutionException { getLog().info( "Will generate static site from " + inputDirectory + " into " + outputDirectory + " based on " + template ); StaticSiteGenerator ssg = new StaticSiteGenerator(inputDirectory.toPath(), outputDirectory.toPath(), template, siteName, strictLinkChecking, extraConfig); try { ssg.run(); } catch (InterruptedException e) { throw new MojoExecutionException("Processing Interrupted", e); } getLog().info( "Finished generating doc" ); } }
package com.lsw.weather.activity; import android.Manifest; import android.app.Activity; import android.content.Context; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.support.design.widget.AppBarLayout; import android.support.design.widget.CollapsingToolbarLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.NestedScrollView; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationClient; import com.amap.api.location.AMapLocationClientOption; import com.amap.api.location.AMapLocationClientOption.AMapLocationMode; import com.amap.api.location.AMapLocationListener; import com.lsw.weather.R; import com.lsw.weather.adapter.DailyForecastAdapter; import com.lsw.weather.adapter.HourlyForecastAdapter; import com.lsw.weather.adapter.SuggestionAdapter; import com.lsw.weather.api.WeatherApi; import com.lsw.weather.model.WeatherEntity; import com.lsw.weather.model.WeatherEntity.HeWeatherBean; import com.lsw.weather.util.HttpUtil; import com.lsw.weather.util.ImageUtils; import com.lsw.weather.util.SnackbarUtils; import com.lsw.weather.view.ScrollListView; import com.yanzhenjie.permission.AndPermission; import java.util.Calendar; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observer; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { @BindView(R.id.iv_weather_image) ImageView ivWeatherImage; @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.collapsing_toolbar) CollapsingToolbarLayout collapsingToolbar; @BindView(R.id.appbar) AppBarLayout appbar; @BindView(R.id.fab_speech) FloatingActionButton fabSpeech; @BindView(R.id.nav_view) NavigationView navView; @BindView(R.id.drawer_layout) DrawerLayout drawerLayout; @BindView(R.id.swipe_refresh_layout) SwipeRefreshLayout swipeRefreshLayout; @BindView(R.id.iv_icon) ImageView ivIcon; @BindView(R.id.tv_temp) TextView tvTemp; @BindView(R.id.tv_max_temp) TextView tvMaxTemp; @BindView(R.id.tv_min_temp) TextView tvMinTemp; @BindView(R.id.tv_more_info) TextView tvMoreInfo; @BindView(R.id.ll_weather_container) LinearLayout llWeatherContainer; @BindView(R.id.nested_scroll_view) NestedScrollView nestedScrollView; @BindView(R.id.lv_hourly_forecast) ScrollListView lvHourlyForecast; @BindView(R.id.lv_daily_forecast) ScrollListView lvDailyForecast; @BindView(R.id.lv_suggestion) ScrollListView lvSuggestion; @BindView(R.id.tv_today_weather) TextView tvTodayWeather; private String cityName = ""; //AMapLocationClient public AMapLocationClient mLocationClient = null; //AMapLocationClientOption public AMapLocationClientOption mLocationOption = null; private HeWeatherBean mHeWeatherBean; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setSupportActionBar(toolbar); AndPermission.with(this) .requestCode(100) .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE) .send(); onLocationCity(); swipeRefreshLayout.setRefreshing(true); swipeRefreshLayout.setColorSchemeResources(R.color.bg_orange, R.color.bg_blue, R.color.bg_green, R.color.bg_red); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { swipeRefreshLayout.setRefreshing(true); loadWeatherData(cityName); } }); fabSpeech.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show(); if (mHeWeatherBean != null) { voiceWeather(MainActivity.this, mHeWeatherBean); } } }); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawerLayout.setDrawerListener(toggle); toggle.syncState(); navView.setNavigationItemSelectedListener(this); } /** * * @param city */ private void loadWeatherData(String city) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(HttpUtil.WEATHER_URL) .addConverterFactory(GsonConverterFactory.create())// json .addCallAdapterFactory(RxJavaCallAdapterFactory.create())// RxJava .build(); WeatherApi weatherApi = retrofit.create(WeatherApi.class); weatherApi.getWeather(city, HttpUtil.HE_WEATHER_KEY) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<WeatherEntity>() { @Override public void onCompleted() { Log.d("sweeney---", "onCompleted: "); } @Override public void onError(Throwable e) { Log.d("sweeney---", "onError: " + e.getMessage()); } @Override public void onNext(WeatherEntity entity) { Log.d("sweeney---", "onNext: "); swipeRefreshLayout.setRefreshing(false); mHeWeatherBean = entity.getHeWeather().get(0); updateView(mHeWeatherBean); SnackbarUtils.Short(drawerLayout, "").show(); } }); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); /* if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { }*/ drawerLayout.closeDrawer(GravityCompat.START); return true; } /** * * @param weather */ private void updateView(HeWeatherBean weather) { ivWeatherImage.setImageResource(ImageUtils.getWeatherImage(weather.getNow().getCond().getTxt())); ivIcon.setImageResource(ImageUtils.getIconByCode(this, weather.getNow().getCond().getCode())); tvTodayWeather.setText(weather.getNow().getCond().getTxt()); tvTemp.setText(getString(R.string.tempC, weather.getNow().getTmp())); tvMaxTemp.setText(getString(R.string.now_max_temp, weather.getDaily_forecast().get(0).getTmp().getMax())); tvMinTemp.setText(getString(R.string.now_min_temp, weather.getDaily_forecast().get(0).getTmp().getMin())); StringBuilder sb = new StringBuilder(); sb.append("").append(weather.getNow().getFl()).append("°"); if (weather.getAqi() != null && !TextUtils.isEmpty(weather.getAqi().getCity().getQlty())) { sb.append(" ").append(weather.getAqi().getCity().getQlty().contains("") ? "" : "").append(weather.getAqi().getCity().getQlty()); } sb.append(" ").append(weather.getNow().getWind().getDir()).append(weather.getNow().getWind().getSc()).append(weather.getNow().getWind().getSc().contains("") ? "" : ""); tvMoreInfo.setText(sb.toString()); lvHourlyForecast.setAdapter(new HourlyForecastAdapter(weather.getHourly_forecast())); lvDailyForecast.setAdapter(new DailyForecastAdapter(weather.getDaily_forecast())); lvSuggestion.setAdapter(new SuggestionAdapter(weather.getSuggestion())); } private void onLocationCity() { mLocationClient = new AMapLocationClient(getApplicationContext()); mLocationClient.setLocationListener(new AMapLocationListener() { @Override public void onLocationChanged(AMapLocation aMapLocation) { if (aMapLocation != null) { if (aMapLocation.getErrorCode() == 0) { //amapLocation cityName = getLocationCityName(aMapLocation.getProvince(), aMapLocation.getCity(), aMapLocation.getDistrict()); collapsingToolbar.setTitle(cityName); loadWeatherData(cityName); Log.d("sweeney---", "onLocationChanged: city = " + cityName); } else { //ErrCodeerrInfo Log.e("AmapError", "location Error, ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo()); } } } }); //AMapLocationClientOption mLocationOption = new AMapLocationClientOption(); //AMapLocationMode.Hight_Accuracy mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy); //false mLocationOption.setOnceLocation(true); //setOnceLocationLatest(boolean b)trueSDK3struesetOnceLocation(boolean b)truefalse mLocationOption.setOnceLocationLatest(true); mLocationClient.setLocationOption(mLocationOption); mLocationClient.startLocation(); } /** * * @param province * @param city * @param district * @return */ private String getLocationCityName(String province, String city, String district) { //district"""" if (district != null) { String districtEnd = district.substring((district.length() - 1), district.length());// if (districtEnd.equals("")) { return district.substring(0, (district.length() - 1)); } else if (districtEnd.equals("")) { return district.substring(0, (district.length() - 1)); } else { return district; } } else if (city != null) {//city"" String cityEnd = city.substring((city.length() - 1), city.length()); if (cityEnd.equals("")) { return city.substring(0, (city.length() - 1)); } else { return city; } } else if (province != null) {//province"""" String provinceEnd = province.substring((province.length() - 1), province.length()); if (provinceEnd.equals("")) { return province.substring(0, (province.length() - 1)); } else if (provinceEnd.equals("")) { return province.substring(0, (province.length() - 1)); } else { return province; } } else { return ""; } } /** * * @param fab * @param start */ public static void voiceAnimation(FloatingActionButton fab, boolean start) { AnimationDrawable animation = (AnimationDrawable) fab.getDrawable(); if (start) { animation.start(); } else { animation.stop(); animation.selectDrawable(animation.getNumberOfFrames() - 1); } } /** * * @param context * @param weather * @return */ public static String voiceWeather(Context context, HeWeatherBean weather) { StringBuilder sb = new StringBuilder(); int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); if (hour >= 7 && hour < 12) { sb.append(""); } else if (hour < 19) { sb.append(""); } else { sb.append(""); } sb.append(""); sb.append(context.getString(R.string.app_name)) .append("") .append(""); sb.append("") .append(weather.getDaily_forecast().get(0).getCond().getTxt_d()) .append("") .append(weather.getDaily_forecast().get(0).getCond().getTxt_n()) .append(""); sb.append("") .append(weather.getDaily_forecast().get(0).getTmp().getMin()) .append("~") .append(weather.getDaily_forecast().get(0).getTmp().getMax()) .append("℃") .append(""); sb.append(weather.getDaily_forecast().get(0).getWind().getDir()) .append(weather.getDaily_forecast().get(0).getWind().getSc()) .append(weather.getDaily_forecast().get(0).getWind().getSc().contains("") ? "" : "") .append(""); return sb.toString(); } }
package com.laytonsmith.core.functions; import com.laytonsmith.PureUtilities.Common.StringUtils; import com.laytonsmith.PureUtilities.LinkedComparatorSet; import com.laytonsmith.PureUtilities.RunnableQueue; import com.laytonsmith.PureUtilities.Version; import com.laytonsmith.abstraction.StaticLayer; import com.laytonsmith.annotations.MEnum; import com.laytonsmith.annotations.OperatorPreferred; import com.laytonsmith.annotations.api; import com.laytonsmith.annotations.core; import com.laytonsmith.annotations.seealso; import com.laytonsmith.core.ArgumentValidation; import com.laytonsmith.core.MSVersion; import com.laytonsmith.core.Optimizable; import com.laytonsmith.core.ParseTree; import com.laytonsmith.core.Script; import com.laytonsmith.core.Static; import com.laytonsmith.core.compiler.FileOptions; import com.laytonsmith.core.constructs.CArray; import com.laytonsmith.core.constructs.CBoolean; import com.laytonsmith.core.constructs.CClosure; import com.laytonsmith.core.constructs.CInt; import com.laytonsmith.core.constructs.CMutablePrimitive; import com.laytonsmith.core.constructs.CNull; import com.laytonsmith.core.constructs.CSlice; import com.laytonsmith.core.constructs.CString; import com.laytonsmith.core.constructs.CVoid; import com.laytonsmith.core.constructs.Construct; import com.laytonsmith.core.constructs.Target; import com.laytonsmith.core.environments.Environment; import com.laytonsmith.core.environments.GlobalEnv; import com.laytonsmith.core.exceptions.CRE.CRECastException; import com.laytonsmith.core.exceptions.CRE.CREFormatException; import com.laytonsmith.core.exceptions.CRE.CREIllegalArgumentException; import com.laytonsmith.core.exceptions.CRE.CREIndexOverflowException; import com.laytonsmith.core.exceptions.CRE.CREInsufficientArgumentsException; import com.laytonsmith.core.exceptions.CRE.CRELengthException; import com.laytonsmith.core.exceptions.CRE.CREPluginInternalException; import com.laytonsmith.core.exceptions.CRE.CRERangeException; import com.laytonsmith.core.exceptions.CRE.CREThrowable; import com.laytonsmith.core.exceptions.CancelCommandException; import com.laytonsmith.core.exceptions.ConfigCompileException; import com.laytonsmith.core.exceptions.ConfigRuntimeException; import com.laytonsmith.core.exceptions.ProgramFlowManipulationException; import com.laytonsmith.core.functions.BasicLogic.equals; import com.laytonsmith.core.functions.BasicLogic.equals_ic; import com.laytonsmith.core.functions.BasicLogic.sequals; import com.laytonsmith.core.functions.DataHandling.array; import com.laytonsmith.core.natives.interfaces.ArrayAccess; import com.laytonsmith.core.natives.interfaces.Iterator; import com.laytonsmith.core.natives.interfaces.Mixed; import java.util.ArrayList; import java.util.EnumSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.TreeSet; @core public class ArrayHandling { public static String docs() { return "This class contains functions that provide a way to manipulate arrays. To create an array, use the" + " <code>array</code> function. For more detailed information on array usage, see the page on" + " [[Arrays|arrays]]"; } @api public static class array_size extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_size"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(args[0].isInstanceOf(CArray.TYPE) && !(args[0] instanceof CMutablePrimitive)) { return new CInt(((CArray) args[0]).size(), t); } throw new CRECastException("Argument 1 of array_size must be an array", t); } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public String docs() { return "int {array} Returns the size of this array as an integer."; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_0_1; } @Override public Boolean runAsync() { return null; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates usage", "array_size(array(1, 2, 3, 4, 5));")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api(environments = {GlobalEnv.class}) @seealso({array_set.class, array.class, com.laytonsmith.tools.docgen.templates.Arrays.class}) public static class array_get extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_get"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { Mixed index; Mixed defaultConstruct = null; if(args.length >= 2) { index = args[1]; } else { index = new CSlice(0, -1, t); } if(args.length >= 3) { defaultConstruct = args[2]; } if(args[0].isInstanceOf(CArray.TYPE)) { CArray ca = (CArray) args[0]; if(index instanceof CSlice) { // Deep clone the array if the "index" is the initial one. if(((CSlice) index).getStart() == 0 && ((CSlice) index).getFinish() == -1) { return ca.deepClone(t); } else if(ca.inAssociativeMode()) { throw new CRECastException("Array slices are not allowed with an associative array", t); } //It's a range long start = ((CSlice) index).getStart(); long finish = ((CSlice) index).getFinish(); try { //Convert negative indexes if(start < 0) { start = ca.size() + start; } if(finish < 0) { finish = ca.size() + finish; } CArray na = ca.createNew(t); if(finish < start) { //return an empty array in cases where the indexes don't make sense return na; } for(long i = start; i <= finish; i++) { try { na.push(ca.get((int) i, t).clone(), t); } catch (CloneNotSupportedException e) { na.push(ca.get((int) i, t), t); } } return na; } catch (NumberFormatException e) { throw new CRECastException("Ranges must be integer numbers, i.e., [0..5]", t); } } else { try { if(!ca.inAssociativeMode()) { if(index instanceof CNull) { throw new CRECastException("Expected a number, but received null instead", t); } long iindex = Static.getInt(index, t); if(iindex < 0) { //negative index, convert to positive index iindex = ca.size() + iindex; } return ca.get(iindex, t); } else { return ca.get(index, t); } } catch (ConfigRuntimeException e) { if(e instanceof CREThrowable && ((CREThrowable) e).isInstanceOf(CREIndexOverflowException.TYPE)) { if(defaultConstruct != null) { return defaultConstruct; } } if(env.getEnv(GlobalEnv.class).GetFlag("array-special-get") != null) { //They are asking for an array that doesn't exist yet, so let's create it now. CArray c; if(ca.inAssociativeMode()) { c = CArray.GetAssociativeArray(t); } else { c = new CArray(t); } ca.set(index, c, t); return c; } throw e; } } } else if(args[0].isInstanceOf(ArrayAccess.TYPE)) { com.laytonsmith.core.natives.interfaces.Iterable aa = (com.laytonsmith.core.natives.interfaces.Iterable) args[0]; if(index instanceof CSlice) { //It's a range int start = (int) ((CSlice) index).getStart(); int finish = (int) ((CSlice) index).getFinish(); try { //Convert negative indexes if(start < 0) { start = (int) aa.size() + start; } if(finish < 0) { finish = (int) aa.size() + finish; } return aa.slice(start, finish + 1, t); } catch (NumberFormatException e) { throw new CRECastException("Ranges must be integer numbers, i.e., [0..5]", t); } } else if(index.isInstanceOf(CInt.TYPE)) { return aa.get(Static.getInt32(index, t), t); } else { return aa.get(index, t); } } else { throw new CRECastException("Argument 1 of array_get must be an array", t); } } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREIndexOverflowException.class}; } @Override public String docs() { return "mixed {array, index, [default]} Returns the element specified at the index of the array." + " If the element doesn't exist, an exception is thrown. ---- You can use a more traditional" + " method to access elements in an array: array[index] is the same as array_get(array, index)," + " where array is a variable, or function that is an array. In fact, the compiler converts" + " array[index] into array_get(array, index). So if there is a problem with your code, you will" + " get an error message about a problem with the array_get function, even though you may not be" + " using that function directly. If using the plain function access, then if a default is" + " provided, the function will always return that value if the array otherwise doesn't have a" + " value there. This is opposed to throwing an exception or returning null."; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_0_1; } @Override public Boolean runAsync() { return null; } @Override public Mixed optimize(Target t, Environment env, Mixed... args) throws ConfigCompileException { if(args.length == 0) { throw new CRECastException("Argument 1 of array_get must be an array", t); } if(args[0].isInstanceOf(ArrayAccess.TYPE)) { ArrayAccess aa = (ArrayAccess) args[0]; if(!aa.canBeAssociative()) { if(!(args[1].isInstanceOf(CInt.TYPE)) && !(args[1] instanceof CSlice)) { throw new ConfigCompileException("Accessing an element as an associative array," + " when it can only accept integers.", t); } } return null; } else { throw new ConfigCompileException("Trying to access an element like an array," + " but it does not support array access.", t); } } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates basic usage", "msg(array(0, 1, 2)[2]);"), new ExampleScript("Demonstrates exception", "msg(array()[1]);"), new ExampleScript("Demonstrates basic functional usage", "msg(array_get(array(1, 2, 3), 2));"), new ExampleScript("Demonstrates default (note that you cannot use the bracket syntax with this)", "msg(array_get(array(), 1, 'default'));")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of( OptimizationOption.OPTIMIZE_CONSTANT ); } } @api @seealso({array_get.class, array.class, array_push.class, com.laytonsmith.tools.docgen.templates.Arrays.class}) @OperatorPreferred("@array[@key] = @value") public static class array_set extends AbstractFunction { @Override public String getName() { return "array_set"; } @Override public Integer[] numArgs() { return new Integer[]{3}; } @Override public boolean useSpecialExec() { return true; } @Override public Mixed execs(Target t, Environment env, Script parent, ParseTree... nodes) { env.getEnv(GlobalEnv.class).SetFlag("array-special-get", true); Mixed array = parent.seval(nodes[0], env); env.getEnv(GlobalEnv.class).ClearFlag("array-special-get"); Mixed index = parent.seval(nodes[1], env); Mixed value = parent.seval(nodes[2], env); if(!(array.isInstanceOf(CArray.TYPE))) { throw new CRECastException("Argument 1 of array_set must be an array", t); } try { ((CArray) array).set(index, value, t); } catch (IndexOutOfBoundsException e) { throw new CREIndexOverflowException("The index " + new CString(index).getQuote() + " is out of bounds", t); } return value; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(args[0].isInstanceOf(CArray.TYPE)) { try { ((CArray) args[0]).set(args[1], args[2], t); } catch (IndexOutOfBoundsException e) { throw new CREIndexOverflowException("The index " + args[1].val() + " is out of bounds", t); } return args[2]; } throw new CRECastException("Argument 1 of array_set must be an array", t); } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREIndexOverflowException.class}; } @Override public String docs() { return "mixed {array, index, value} Sets the value of the array at the specified index." + " The value that was set is returned, to allow for chaining."; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_0_1; } @Override public Boolean runAsync() { return null; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates using assignment", "array @array = array(null);\n" + "msg(@array);\n" + "@array[0] = 'value0';\n" + "msg(@array);"), new ExampleScript("Demonstrates functional usage", "array @array = array(null);\n" + "msg(@array);\n" + "array_set(@array, 0, 'value0');\n" + "msg(@array);")}; } } @api @seealso({array_set.class, array_push_all.class}) @OperatorPreferred("@array[] = @value") public static class array_push extends AbstractFunction { @Override public String getName() { return "array_push"; } @Override public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(args.length < 2) { throw new CREInsufficientArgumentsException("At least 2 arguments must be provided to array_push", t); } if(args[0].isInstanceOf(CArray.TYPE)) { CArray array = (CArray) args[0]; int initialSize = (int) array.size(); for(int i = 1; i < args.length; i++) { array.push(args[i], t); for(Iterator iterator : env.getEnv(GlobalEnv.class).GetArrayAccessIteratorsFor(((ArrayAccess) args[0]))) { //This is always pushing after the current index. //Given that this is the last one, we don't need to waste //time with a call to increment the blacklist items either. iterator.addToBlacklist(initialSize + i - 1); } } return CVoid.VOID; } throw new CRECastException("Argument 1 of array_push must be an array", t); } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public String docs() { return "void {array, value, [value2...]} Pushes the specified value(s) onto the end of the array. Unlike" + " calling array_set(@array, array_size(@array), @value) on a normal array, the size of the array" + " is increased first. The special operator syntax @array[] = 'value' is also supported, as" + " shorthand for array_push()."; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_0_1; } @Override public Boolean runAsync() { return null; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Operator syntax. Note the difference between this and the array clone" + " operator is that this occurs on the Left Hand Side (LHS) of the assignment.", "array @array = array();\n" + "@array[] = 'new value';"), new ExampleScript("Demonstrates functional usage", "array @array = array();\n" + "msg(@array);\n" + "array_push(@array, 0);\n" + "msg(@array);"), new ExampleScript("Demonstrates pushing multiple values (note that it is not possible to use the bracket notation" + " and push multiple values)", "array @array = array();\n" + "msg(@array);\n" + "array_push(@array, 0, 1, 2);\n" + "msg(@array);")}; } } @api public static class array_insert extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREIndexOverflowException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); Mixed value = args[1]; int index = Static.getInt32(args[2], t); try { array.push(value, index, t); //If the push succeeded (actually an insert) we need to check to see if we are currently iterating //and act appropriately. for(Iterator iterator : environment.getEnv(GlobalEnv.class).GetArrayAccessIteratorsFor(array)) { if(index <= iterator.getCurrent()) { //The insertion happened before (or at) this index, so we need to increment the //iterator, as well as increment all the blacklist items above this one. iterator.incrementCurrent(); } else { //The insertion happened after this index, so we need to increment the //blacklist values after this one, and add this index to the blacklist iterator.incrementBlacklistAfter(index); iterator.addToBlacklist(index); } } } catch (IllegalArgumentException e) { throw new CRECastException(e.getMessage(), t); } catch (IndexOutOfBoundsException ex) { throw new CREIndexOverflowException(ex.getMessage(), t); } return CVoid.VOID; } @Override public String getName() { return "array_insert"; } @Override public Integer[] numArgs() { return new Integer[]{3}; } @Override public String docs() { return "void {array, item, index} Inserts an item at the specified index, and shifts all other items in the" + " array to the right one. If index is greater than the size of the array, an IndexOverflowException" + " is thrown, though the index may be equal to the size, in which case this works just like" + " array_push(). The array must be normal though; associative arrays are not supported."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "array @array = array(1, 3, 4);\n" + "array_insert(@array, 2, 1);\n" + "msg(@array);"), new ExampleScript("Usage as if it were array_push", "@array = array(1, 2, 3);\n" + "array_insert(@array, 4, array_size(@array));\n" + "msg(@array);") }; } } @api @seealso({array_index_exists.class, array_scontains.class}) public static class array_contains extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_contains"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws CancelCommandException, ConfigRuntimeException { if(!(args[0].isInstanceOf(CArray.TYPE))) { throw new CRECastException("Argument 1 of " + this.getName() + " must be an array", t); } CArray ca = (CArray) args[0]; for(Mixed key : ca.keySet()) { if(new equals().exec(t, env, ca.get(key, t), args[1]).getBoolean()) { return CBoolean.TRUE; } } return CBoolean.FALSE; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public String docs() { return "boolean {array, testValue} Checks to see if testValue is in array. For associative arrays, only the" + " values are searched, the keys are ignored. If you need to check for the existence of a" + " particular key, use array_index_exists()."; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_0_1; } @Override public Boolean runAsync() { return null; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates finding a value", "array_contains(array(0, 1, 2), 2)"), new ExampleScript("Demonstrates not finding a value", "array_contains(array(0, 1, 2), 5)"), new ExampleScript("Demonstrates finding a value listed multiple times", "array_contains(array(1, 1, 1), 1)"), new ExampleScript("Demonstrates finding a string", "array_contains(array('a', 'b', 'c'), 'b')"), new ExampleScript("Demonstrates finding a value in an associative array", "array_contains(array('a': 1, 'b': 2), 2)") }; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api @seealso({array_contains.class}) public static class array_contains_ic extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_contains_ic"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "boolean {array, testValue} Works like array_contains, except the comparison ignores case."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_3_0; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(args[0].isInstanceOf(CArray.TYPE)) { CArray ca = (CArray) args[0]; for(int i = 0; i < ca.size(); i++) { if(new equals_ic().exec(t, environment, ca.get(i, t), args[1]).getBoolean()) { return CBoolean.TRUE; } } return CBoolean.FALSE; } else { throw new CRECastException("Argument 1 of " + this.getName() + " must be an array", t); } } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates usage", "array_contains_ic(array('A', 'B', 'C'), 'A')"), new ExampleScript("Demonstrates usage", "array_contains_ic(array('A', 'B', 'C'), 'a')"), new ExampleScript("Demonstrates usage", "array_contains_ic(array('A', 'B', 'C'), 'd')")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api @seealso({array_index_exists.class, array_contains.class}) public static class array_scontains extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_scontains"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws CancelCommandException, ConfigRuntimeException { if(!(args[0].isInstanceOf(CArray.TYPE))) { throw new CRECastException("Argument 1 of " + this.getName() + " must be an array", t); } CArray ca = (CArray) args[0]; for(Mixed key : ca.keySet()) { if(new sequals().exec(t, env, ca.get(key, t), args[1]).getBoolean()) { return CBoolean.TRUE; } } return CBoolean.FALSE; } @Override public Class[] thrown() { return new Class[]{CRECastException.class}; } @Override public String docs() { return "boolean {array, testValue} Checks if the array contains a value of the same datatype and value as" + " testValue. For associative arrays, only the values are searched, the keys are ignored." + " If you need to check for the existence of a particular key, use array_index_exists()."; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public Boolean runAsync() { return null; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates finding a value", "array_scontains(array(0, 1, 2), 2)"), new ExampleScript("Demonstrates not finding a value because of a value mismatch", "array_scontains(array(0, 1, 2), 5)"), new ExampleScript("Demonstrates not finding a value because of a type mismatch", "array_scontains(array(0, 1, 2), '2')"), new ExampleScript("Demonstrates finding a value listed multiple times", "array_scontains(array(1, 1, 1), 1)"), new ExampleScript("Demonstrates finding a string", "array_scontains(array('a', 'b', 'c'), 'b')"), new ExampleScript("Demonstrates finding a value in an associative array", "array_scontains(array('a': 1, 'b': 2), 2)") }; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_index_exists extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_index_exists"; } @Override public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } @Override public String docs() { return "boolean {array, index...} Checks to see if the specified array has an element at index. If more" + " than one index is specified, then it recursively checks down nested arrays."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_1_2; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(args[0].isInstanceOf(CArray.TYPE)) { Mixed m = args[0]; for(int i = 1; i < args.length; i++) { if(!(m.isInstanceOf(CArray.TYPE))) { return CBoolean.FALSE; } CArray ca = (CArray) m; if(!ca.inAssociativeMode()) { try { int index = Static.getInt32(args[i], t); if(index >= ca.size() || index < 0) { return CBoolean.FALSE; } } catch (ConfigRuntimeException e) { //They probably sent a key that can't be translated into an int, so it doesn't exist here. return CBoolean.FALSE; } } else { if(!ca.containsKey(args[i].val())) { return CBoolean.FALSE; } } m = ca.get(args[i], t); } return CBoolean.TRUE; } else { throw new CRECastException("Expecting argument 1 to be an array", t); } } @Override public ParseTree optimizeDynamic(Target t, Environment env, Set<Class<? extends Environment.EnvironmentImpl>> envs, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException { if(children.size() < 2) { throw new ConfigCompileException(getName() + " must have 2 or more arguments", t); } return null; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates a true condition", "array_index_exists(array(0, 1, 2), 0)"), new ExampleScript("Demonstrates a false condition", "array_index_exists(array(0, 1, 2), 3)"), new ExampleScript("Demonstrates an associative array", "array_index_exists(array(a: 'A', b: 'B'), 'a')"), new ExampleScript("Demonstrates an associative array", "array_index_exists(array(a: 'A', b: 'B'), 'c')"), new ExampleScript("Demonstrates nested arrays", "// Check to make sure that @array['a']['b']['c'] would work\n" + "@array = array(a: array(b: array(c: null)));\n" + "msg(array_index_exists(@array, 'a', 'b', 'c'));"), new ExampleScript("Demonstrates nested arrays, where the value is not an array (if the first element is" + " not an array an exception will be thrown, but inner values need not be arrays).", "@array = array(a: array(b: 1));\n" + "msg(array_index_exists(@array, 'a', 'b', 'c'));") }; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS, OptimizationOption.OPTIMIZE_DYNAMIC); } } @api public static class array_resize extends AbstractFunction { @Override public String getName() { return "array_resize"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "array {array, size, [fill]} Resizes the given array so that it is at least of size size, filling" + " the blank spaces with fill, or null by default. If the size of the array is already at least" + " size, nothing happens; in other words this function can only be used to increase the size of" + " the array. A reference to the array is returned, for easy chaining."; //+ " If the array is an associative array, the non numeric values are simply copied over."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_2_0; } @Override public Boolean runAsync() { return null; } @Override public CArray exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(args[0].isInstanceOf(CArray.TYPE) && args[1].isInstanceOf(CInt.TYPE)) { CArray original = (CArray) args[0]; int size = (int) ((CInt) args[1]).getInt(); Mixed fill = CNull.NULL; if(args.length == 3) { fill = args[2]; } for(long i = original.size(); i < size; i++) { original.push(fill, t); } } else { throw new CRECastException("Argument 1 must be an array, and argument 2 must be an integer in array_resize", t); } return (CArray) args[0]; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates basic usage", "array @array = array();\n" + "msg(@array);\n" + "array_resize(@array, 2);\n" + "msg(@array);"), new ExampleScript("Demonstrates custom fill", "array @array = array();\n" + "msg(@array);\n" + "array_resize(@array, 2, 'a');\n" + "msg(@array);")}; } } @api public static class range extends AbstractFunction implements Optimizable { @Override public String getName() { return "range"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "array {start, finish, [increment] | finish} Returns an array of numbers from start to (finish - 1)" + " skipping increment integers per count. start defaults to 0, and increment defaults to 1." + " All inputs must be integers. If the input doesn't make sense, it will reasonably degrade, and" + " return an empty array."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_2_0; } @Override public Boolean runAsync() { return null; } @Override public CArray exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { long start = 0; long finish = 0; long increment = 1; if(args.length == 1) { finish = Static.getInt(args[0], t); } else if(args.length == 2) { start = Static.getInt(args[0], t); finish = Static.getInt(args[1], t); } else if(args.length == 3) { start = Static.getInt(args[0], t); finish = Static.getInt(args[1], t); increment = Static.getInt(args[2], t); } if(start < finish && increment < 0 || start > finish && increment > 0 || increment == 0) { return new CArray(t); } CArray ret = new CArray(t); for(long i = start; (increment > 0 ? i < finish : i > finish); i = i + increment) { ret.push(new CInt(i, t), t); } return ret; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "range(10)"), new ExampleScript("Complex usage", "range(0, 10)"), new ExampleScript("With skips", "range(0, 10, 2)"), new ExampleScript("Invalid input", "range(0, 10, -1)"), new ExampleScript("In reverse", "range(10, 0, -1)")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_keys extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_keys"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "array {array} Returns the keys in this array as a normal array. If the array passed in is already a" + " normal array, the keys will be 0 -> (array_size(array) - 1)"; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_3_0; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { // As an exception, strings aren't supported here. There's no reason to do this for a string that isn't accidental. if(args[0].isInstanceOf(ArrayAccess.TYPE) && !(args[0].isInstanceOf(CString.TYPE))) { ArrayAccess ca = (ArrayAccess) args[0]; CArray ca2 = new CArray(t); for(Mixed c : ca.keySet()) { ca2.push(c, t); } return ca2; } else { throw new CRECastException(this.getName() + " expects arg 1 to be an array", t); } } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "array_keys(array('a', 'b', 'c'))"), new ExampleScript("With associative array", "array_keys(array(one: 'a', two: 'b', three: 'c'))")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_normalize extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_normalize"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "array {array} Returns a new normal array, given an associative array. (If the array passed in is" + " not associative, a copy of the array is returned)."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_3_0; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment env, Mixed... args) throws ConfigRuntimeException { if(args[0].isInstanceOf(CArray.TYPE)) { CArray ca = Static.getArray(args[0], t); CArray ca2 = new CArray(t); for(Mixed c : ca.keySet()) { ca2.push(ca.get(c, t), t); } return ca2; } else { throw new CRECastException(this.getName() + " expects arg 1 to be an array", t); } } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "array_normalize(array(one: 'a', two: 'b', three: 'c'))"), new ExampleScript("Usage with normal array", "array_normalize(array(1, 2, 3))")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api @seealso({array_intersect.class}) public static class array_merge extends AbstractFunction implements Optimizable { @Override public String getName() { return "array_merge"; } @Override public Integer[] numArgs() { return new Integer[]{Integer.MAX_VALUE}; } @Override public String docs() { return "array {array1, array2, [arrayN...]} Merges the specified arrays from left to right, and returns a" + " new array. If the array merged is associative, it will overwrite the keys from left to right," + " but if the arrays are normal, the keys are ignored, and values are simply pushed."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREInsufficientArgumentsException.class, CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_3_0; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray newArray = new CArray(t); if(args.length < 2) { throw new CREInsufficientArgumentsException("array_merge must be called with at least two parameters", t); } for(Mixed arg : args) { if(arg.isInstanceOf(ArrayAccess.TYPE)) { com.laytonsmith.core.natives.interfaces.Iterable cur = (com.laytonsmith.core.natives.interfaces.Iterable) arg; if(!cur.isAssociative()) { for(int j = 0; j < cur.size(); j++) { newArray.push(cur.get(j, t), t); } } else { for(Mixed key : cur.keySet()) { if(key.isInstanceOf(CInt.TYPE)) { newArray.set(key, cur.get((int) ((CInt) key).getInt(), t), t); } else { newArray.set(key, cur.get(key.val(), t), t); } } } } else { throw new CRECastException("All arguments to array_merge must be arrays", t); } } return newArray; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "array_merge(array(1), array(2), array(3))"), new ExampleScript("With associative arrays", "array_merge(array(one: 1), array(two: 2), array(three: 3))"), new ExampleScript("With overwrites", "array_merge(array(one: 1), array(one: 2), array(one: 3))")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_remove extends AbstractFunction { @Override public String getName() { return "array_remove"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "mixed {array, index} Removes an index from an array. If the array is a normal" + " array, all values' indices are shifted left one. If the array is associative," + " the index is simply removed. If the index exists, the value removed is returned." + " If the index doesn't exist, the array remains unchanged," + " however it'll throw a RangeException for normal arrays (returns null for associative arrays)."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRERangeException.class, CRECastException.class, CREPluginInternalException.class}; } @Override public boolean isRestricted() { return false; } @Override public MSVersion since() { return MSVersion.V3_3_0; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); if(array.isAssociative()) { return array.remove(args[1]); } else { int index = Static.getInt32(args[1], t); Mixed removed = array.remove(args[1]); //If the removed index is <= the current index, we need to decrement the counter. for(Iterator iterator : environment.getEnv(GlobalEnv.class).GetArrayAccessIteratorsFor(array)) { if(index <= iterator.getCurrent()) { iterator.decrementCurrent(); } } return removed; } } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "assign(@array, array(1, 2, 3))\nmsg(array_remove(@array, 2))\nmsg(@array)"), new ExampleScript("With associative array", "assign(@array, array(one: 'a', two: 'b', three: 'c'))\nmsg(array_remove(@array, 'two'))\nmsg(@array)")}; } } @api @seealso({StringHandling.split.class, Regex.reg_split.class, map_implode.class}) public static class array_implode extends AbstractFunction { @Override public String getName() { return "array_implode"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "string {array, [glue]} Given an array and glue, to-strings all the elements in the array" + " (just the values, not the keys), and joins them with the glue, defaulting to a space." + " For instance array_implode(array(1, 2, 3), '-') will return \"1-2-3\"."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(!(args[0].isInstanceOf(ArrayAccess.TYPE))) { throw new CRECastException("Expecting argument 1 to be an ArrayAccess type object", t); } StringBuilder b = new StringBuilder(); ArrayAccess ca = (ArrayAccess) args[0]; String glue = " "; if(args.length == 2) { glue = Static.getPrimitive(args[1], t).val(); } boolean first = true; for(Mixed key : ca.keySet()) { Mixed value = ca.get(key, t); if(!first) { b.append(glue).append(value.val()); } else { b.append(value.val()); first = false; } } return new CString(b.toString(), t); } @Override public MSVersion since() { return MSVersion.V3_3_0; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "array_implode(array(1, 2, 3), '-')"), new ExampleScript("With associative array", "array_implode(array(one: 'a', two: 'b', three: 'c'), '-')")}; } } @api @seealso({array_implode.class}) public static class map_implode extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = ArgumentValidation.getArray(args[0], t); String innerGlue = ArgumentValidation.getString(args[1], t); String outerGlue = ArgumentValidation.getString(args[2], t); if(!array.isAssociative()) { throw new CRECastException("Expecting an associative array, but a normal array was provided.", t); } StringBuilder b = new StringBuilder(); boolean first = true; for(Mixed key : array.keySet()) { Mixed value = array.get(key, t); if(!first) { b.append(outerGlue); } first = false; b.append(key.val()).append(innerGlue).append(value.val()); } return new CString(b.toString(), t); } @Override public String getName() { return "map_implode"; } @Override public Integer[] numArgs() { return new Integer[]{3}; } @Override public String docs() { return "string {associativeArray, innerGlue, outerGlue} Implodes an associative array. The innerGlue is" + " used to glue the key to the value, and then the outerGlue is used to glue those elements" + " together. This only works with associative arrays, and will throw CastException if the array" + " passed in isa normal array."; } @Override public Version since() { return MSVersion.V3_3_4; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Single element", "map_implode(array('a': 'b'), '=', '&')"), new ExampleScript("Multiple elements", "map_implode(array('a': '1', 'b': '2'), '=', '&')"), }; } } @api public static class cslice extends AbstractFunction implements Optimizable { @Override public String getName() { return "cslice"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "slice {from, to} Dynamically creates an array slice, which can be used with array_get" + " (or the [bracket notation]) to get a range of elements. cslice(0, 5) is equivalent" + " to 0..5 directly in code, however with this function you can also do cslice(@var, @var)," + " or other more complex expressions, which are not possible in static code."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { return new CSlice(Static.getInt(args[0], t), Static.getInt(args[1], t), t); } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "array(1, 2, 3)[cslice(0, 1)]")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_sort extends AbstractFunction implements Optimizable { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREFormatException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(!(args[0].isInstanceOf(CArray.TYPE))) { throw new CRECastException("The first parameter to array_sort must be an array", t); } CArray ca = (CArray) args[0]; CArray.ArraySortType sortType = CArray.ArraySortType.REGULAR; CClosure customSort = null; if(ca.size() <= 1) { return ca; } try { if(args.length == 2) { if(args[1].isInstanceOf(CClosure.TYPE)) { sortType = null; customSort = (CClosure) args[1]; } else { sortType = ArgumentValidation.getEnum(args[1], CArray.ArraySortType.class, t); } } } catch (IllegalArgumentException e) { throw new CREFormatException("The sort type must be one of either: " + StringUtils.Join(CArray.ArraySortType.values(), ", ", " or "), t); } if(sortType == null) { // It's a custom sort, which we have implemented below. if(ca.isAssociative()) { throw new CRECastException("Associative arrays may not be sorted using a custom comparator.", t); } CArray sorted = customSort(ca, customSort, t); //Clear it out and re-apply the values, so this is in place. ca.clear(); for(Mixed c : sorted.keySet()) { ca.set(c, sorted.get(c, t), t); } } else { ca.sort(sortType); } return ca; } private CArray customSort(CArray ca, CClosure closure, Target t) { if(ca.size() <= 1) { return ca; } CArray left = new CArray(t); CArray right = new CArray(t); int middle = (int) (ca.size() / 2); for(int i = 0; i < middle; i++) { left.push(ca.get(i, t), t); } for(int i = middle; i < ca.size(); i++) { right.push(ca.get(i, t), t); } left = customSort(left, closure, t); right = customSort(right, closure, t); return merge(left, right, closure, t); } private CArray merge(CArray left, CArray right, CClosure closure, Target t) { CArray result = new CArray(t); while(left.size() > 0 || right.size() > 0) { if(left.size() > 0 && right.size() > 0) { // Compare the first two elements of each side Mixed l = left.get(0, t); Mixed r = right.get(0, t); Mixed c = closure.executeCallable(null, t, l, r); int value; if(c instanceof CNull) { value = 0; } else if(c.isInstanceOf(CBoolean.TYPE)) { if(((CBoolean) c).getBoolean()) { value = 1; } else { value = -1; } } else { throw new CRECastException("The custom closure did not return a value (or returned an invalid" + " type). It must always return true, false, or null.", t); } if(value <= 0) { result.push(left.get(0, t), t); left.remove(0); } else { result.push(right.get(0, t), t); right.remove(0); } } else if(left.size() > 0) { result.push(left.get(0, t), t); left.remove(0); } else if(right.size() > 0) { result.push(right.get(0, t), t); right.remove(0); } } return result; } @Override public String getName() { return "array_sort"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "array {array, [sortType]} Sorts an array in place, and also returns a reference to the array. + " The complexity of this sort algorithm is guaranteed to be no worse than n log n, as it uses" + " merge sort. The array is sorted in place, a new array is not explicitly created, so if you sort" + " an array that is passed in as a variable, the contents of that variable will be sorted, even if" + " you don't re-assign the returned array back to the variable. If you really need the old array," + " you should create a copy of the array first, like so: assign(@sorted, array_sort(@array[]))." + " The sort type may be one of the following: " + StringUtils.Join(CArray.ArraySortType.values(), ", ", " or ") + ", or it may be a closure, if the sort should follow custom rules (explained below). A regular" + " sort sorts the elements without changing types first. A numeric sort always converts numeric" + " values to numbers first (so 001 becomes 1). A string sort compares values as strings, and a" + " string_ic sort is the same as a string sort, but the comparision is case-insensitive. If the" + " array contains array values, a CastException is thrown; inner arrays cannot be sorted against" + " each other. If the array is associative, a warning will be raised if the General logging" + " channel is set to verbose, because the array's keys will all be lost in the process. To avoid" + " this warning, and to be more explicit, you can use array_normalize() to normalize the array" + " first. Note that the reason this function is an in place sort instead of explicitly cloning the" + " array is because in most cases, you may not need to actually clone the array, an expensive" + " operation. Due to this, it has slightly different behavior than array_normalize, which could" + " have also been implemented in place.\n\nIf the sortType is a closure, it will perform a" + " custom sort type, and the array may contain any values, including sub array values. The closure" + " should accept two values, @left and @right, and should return true if the left value is larger" + " than the right, and false if the left value is smaller than the right, and null if they are" + " equal. The array will then be re-ordered using a merge sort, using your custom comparator to" + " determine the sort order."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of( OptimizationOption.OPTIMIZE_DYNAMIC ); } @Override public ParseTree optimizeDynamic(Target t, Environment env, Set<Class<? extends Environment.EnvironmentImpl>> envs, List<ParseTree> children, FileOptions fileOptions) throws ConfigCompileException, ConfigRuntimeException { if(children.size() == 2) { if(!Construct.IsDynamicHelper(children.get(1).getData())) { try { CArray.ArraySortType.valueOf(children.get(1).getData().val().toUpperCase()); } catch (IllegalArgumentException e) { throw new ConfigCompileException("The sort type must be one of either: " + StringUtils.Join(CArray.ArraySortType.values(), ", ", " or "), t); } } } return null; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Regular sort", "@array = array('a', 2, 4, 'string');\narray_sort(@array, 'REGULAR');\nmsg(@array);"), new ExampleScript("Numeric sort", "@array = array('03', '02', '4', '1');\narray_sort(@array, 'NUMERIC');\nmsg(@array);"), new ExampleScript("String sort", "@array = array('03', '02', '4', '1');\narray_sort(@array, 'STRING');\nmsg(@array);"), new ExampleScript("String sort (with words)", "@array = array('Zeta', 'zebra', 'Minecraft', 'mojang', 'Appliance', 'apple');\narray_sort(@array, 'STRING');\nmsg(@array);"), new ExampleScript("Ignore case sort", "@array = array('Zeta', 'zebra', 'Minecraft', 'mojang', 'Appliance', 'apple');\narray_sort(@array, 'STRING_IC');\nmsg(@array);"), new ExampleScript("Custom sort", "@array = array(\n" + "\tarray(name: 'Jack', age: 20),\n" + "\tarray(name: 'Jill', age: 19)\n" + ");\n" + "msg(\"Before sort: @array\");\n" + "array_sort(@array, closure(@left, @right){\n" + "\t return(@left['age'] > @right['age']);\n" + "});\n" + "msg(\"After sort: @array\");") }; } } @api public static class array_sort_async extends AbstractFunction { RunnableQueue queue = new RunnableQueue("MethodScript-arraySortAsync"); boolean started = false; private void startup() { if(!started) { queue.invokeLater(null, new Runnable() { @Override public void run() { //This warms up the queue. Apparently. } }); StaticLayer.GetConvertor().addShutdownHook(new Runnable() { @Override public void run() { queue.shutdown(); started = false; } }); started = true; } } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { startup(); final CArray array = Static.getArray(args[0], t); final CString sortType = new CString(args.length > 2 ? args[1].val() : CArray.ArraySortType.REGULAR.name(), t); final CClosure callback = Static.getObject((args.length == 2 ? args[1] : args[2]), t, CClosure.class); queue.invokeLater(environment.getEnv(GlobalEnv.class).GetDaemonManager(), new Runnable() { @Override public void run() { Mixed c = new array_sort().exec(Target.UNKNOWN, null, array, sortType); callback.executeCallable(environment, t, new Mixed[]{c}); } }); return CVoid.VOID; } @Override public String getName() { return "array_sort_async"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "void {array, [sortType], closure(array)} Works like array_sort, but does the sort on another" + " thread, then calls the closure and sends it the sorted array. This is useful if the array" + " is large enough to actually \"stall\" the server when doing the sort. Sort type should be" + " one of " + StringUtils.Join(CArray.ArraySortType.values(), ", ", " or "); } @Override public MSVersion since() { return MSVersion.V3_3_1; } } @api public static class array_remove_values extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); //This needs to be in terms of array_remove, to ensure that the iteration //logic is followed. We will iterate backwards, however, to make the //process more efficient, unless this is an associative array. if(array.isAssociative()) { array.removeValues(args[1]); } else { for(long i = array.size() - 1; i >= 0; i if(BasicLogic.equals.doEquals(array.get(i, t), args[1])) { new array_remove().exec(t, environment, array, new CInt(i, t)); } } } return CVoid.VOID; } @Override public String getName() { return "array_remove_values"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {array, value} Removes all instances of value from the specified array." + " For instance, array_remove_values(array(1, 2, 2, 3), 2) would produce the" + " array(1, 3). Note that it returns void however, so it will simply in place" + " modify the array passed in, much like array_remove."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "assign(@array, array(1, 2, 2, 3))\nmsg(@array)\narray_remove_values(@array, 2)\nmsg(@array)")}; } } @api public static class array_indexes extends AbstractFunction implements Optimizable { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(!(args[0].isInstanceOf(CArray.TYPE))) { throw new CRECastException("Expected parameter 1 to be an array, but was " + args[0].val(), t); } return ((CArray) args[0]).indexesOf(args[1]); } @Override public String getName() { return "array_indexes"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "array {array, value} Returns an array with all the keys of the specified array" + " at which the specified value is equal. That is, for the array(1, 2, 2, 3), if" + " value were 2, would return array(1, 2). If the value cannot be found in the" + " array at all, an empty array will be returned."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "assign(@array, array(1, 2, 2, 3))\nmsg(array_indexes(@array, 2))"), new ExampleScript("Not found", "assign(@array, array(1, 2, 2, 3))\nmsg(array_indexes(@array, 5))")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_index extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray ca = (CArray) new array_indexes().exec(t, environment, args); if(ca.isEmpty()) { return CNull.NULL; } else { return ca.get(0, t); } } @Override public String getName() { return "array_index"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "mixed {array, value} Works exactly like array_indexes(array, value)[0], except in the case where" + " the value is not found, returns null. That is to say, if the value is contained in an" + " array (even multiple times) the index of the first element is returned."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "assign(@array, array(1, 2, 2, 3))\nmsg(array_index(@array, 2))"), new ExampleScript("Not found", "assign(@array, array(1, 2, 2, 3))\nmsg(array_index(@array, 5))")}; } } @api public static class array_last_index extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray ca = (CArray) new array_indexes().exec(t, environment, args); if(ca.isEmpty()) { return CNull.NULL; } else { return ca.get(ca.size() - 1, t); } } @Override public String getName() { return "array_last_index"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "mixed {array, value} Finds the index in the array where value occurs last. If" + " the value is not found, returns null. That is to say, if the value is contained in an" + " array (even multiple times) the index of the last element is returned."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "assign(@array, array(1, 2, 2, 3))\nmsg(array_last_index(@array, 2))"), new ExampleScript("Not found", "assign(@array, array(1, 2, 2, 3))\nmsg(array_last_index(@array, 5))")}; } } @api public static class array_reverse extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(args[0].isInstanceOf(CArray.TYPE)) { ((CArray) args[0]).reverse(t); } return CVoid.VOID; } @Override public String getName() { return "array_reverse"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "void {array} Reverses an array in place. However, if the array is associative, throws a" + " CastException, since associative arrays are more like a map."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "assign(@array, array(1, 2, 3))\nmsg(@array)\narray_reverse(@array)\nmsg(@array)"), new ExampleScript("Failure", "assign(@array, array(one: 1, two: 2))\narray_reverse(@array)") }; } } @api public static class array_rand extends AbstractFunction implements Optimizable { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRERangeException.class, CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } Random r = new Random(System.currentTimeMillis()); @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { long number = 1; boolean getKeys = true; CArray array = Static.getArray(args[0], t); CArray newArray = new CArray(t); if(array.isEmpty()) { return newArray; } if(args.length > 1) { number = Static.getInt(args[1], t); } if(number < 1) { throw new CRERangeException("number may not be less than 1.", t); } if(number > array.size()) { throw new CRERangeException("Number cannot be larger than array size", t); } if(args.length > 2) { getKeys = ArgumentValidation.getBoolean(args[2], t); } LinkedHashSet<Integer> randoms = new LinkedHashSet<>(); while(randoms.size() < number) { randoms.add(java.lang.Math.abs(r.nextInt() % (int) array.size())); } List<Mixed> keySet = new ArrayList<>(array.keySet()); for(Integer i : randoms) { if(getKeys) { newArray.push(keySet.get(i), t); } else { newArray.push(array.get(keySet.get(i), t), t); } } return newArray; } @Override public String getName() { return "array_rand"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2, 3}; } @Override public String docs() { return "array {array, [number, [getKeys]]} Returns a random selection of keys or values from an array." + " The array may be either normal or associative. Number defaults to 1, and getKey defaults to true." + " If number is greater than the size of the array, a RangeException is thrown. No value will be" + " returned twice from the array however, one it is \"drawn\" from the array, it is not placed" + " back in. The order of the elements in the array will also be random, if order is important," + " use array_sort()."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Usage with a normal array", "assign(@array, array('a', 'b', 'c', 'd', 'e'))\nmsg(array_rand(@array))", "{1}"), new ExampleScript("Usage with a normal array, using getKeys false, and returning 2 results", "assign(@array, array('a', 'b', 'c', 'd', 'e'))\nmsg(array_rand(@array, 2, false))", "{b, c}"), new ExampleScript("Usage with an associative array", "assign(@array, array(one: 'a', two: 'b', three: 'c', four: 'd', five: 'e'))\nmsg(array_rand(@array))", "two")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_unique extends AbstractFunction implements Optimizable { // Variable is more clear when named after the function it represents. @SuppressWarnings("checkstyle:constantname") private static final equals equals = new equals(); // Variable is more clear when named after the function it represents. @SuppressWarnings("checkstyle:constantname") private static final BasicLogic.sequals sequals = new BasicLogic.sequals(); @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public CArray exec(final Target t, final Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); boolean compareTypes = true; if(args.length == 2) { compareTypes = ArgumentValidation.getBoolean(args[1], t); } final boolean fCompareTypes = compareTypes; if(array.inAssociativeMode()) { return array.clone(); } else { List<Mixed> asList = array.asList(); CArray newArray = new CArray(t); Set<Mixed> set = new LinkedComparatorSet<>(asList, new LinkedComparatorSet.EqualsComparator<Mixed>() { @Override public boolean checkIfEquals(Mixed item1, Mixed item2) { return (fCompareTypes && ArgumentValidation.getBoolean(sequals.exec(t, environment, item1, item2), t)) || (!fCompareTypes && ArgumentValidation.getBoolean(equals.exec(t, environment, item1, item2), t)); } }); for(Mixed c : set) { newArray.push(c, t); } return newArray; } } @Override public String getName() { return "array_unique"; } @Override public Integer[] numArgs() { return new Integer[]{1, 2}; } @Override public String docs() { return "array {array, [compareTypes]} Removes all non-unique values from an array. + " compareTypes is true by default, which means that in the array array(1, '1'), nothing would be" + " removed from the array, since both values are different data types. However, if compareTypes is" + " false, then the first value would remain, but the second value would be removed. A new array is" + " returned. If the array is associative, by definition, there are no unique values, so a clone of" + " the array is returned."; } @Override public MSVersion since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "array_unique(array(1, 2, 2, 3, 4))"), new ExampleScript("No removal of different datatypes", "array_unique(array(1, '1'))"), new ExampleScript("Removal of different datatypes, by setting compareTypes to false", "array_unique(array(1, '1'), false)")}; } @Override public Set<OptimizationOption> optimizationOptions() { return EnumSet.of(OptimizationOption.NO_SIDE_EFFECTS); } } @api public static class array_filter extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { com.laytonsmith.core.natives.interfaces.Iterable array; CClosure closure; if(!(args[0] instanceof com.laytonsmith.core.natives.interfaces.Iterable)) { throw new CRECastException("Expecting an array for argument 1", t); } if(!(args[1].isInstanceOf(CClosure.TYPE))) { throw new CRECastException("Expecting a closure for argument 2", t); } array = (com.laytonsmith.core.natives.interfaces.Iterable) args[0]; closure = (CClosure) args[1]; CArray newArray; if(array.isAssociative()) { newArray = CArray.GetAssociativeArray(t); for(Mixed key : array.keySet()) { Mixed value = array.get(key, t); Mixed ret = closure.executeCallable(environment, t, key, value); boolean bret = ArgumentValidation.getBooleanish(ret, t); if(bret) { newArray.set(key, value, t); } } } else { newArray = new CArray(t); for(int i = 0; i < array.size(); i++) { Mixed key = new CInt(i, t); Mixed value = array.get(i, t); Mixed ret = closure.executeCallable(environment, t, key, value); if(ret == CNull.NULL) { ret = CBoolean.FALSE; } boolean bret = ArgumentValidation.getBooleanish(ret, t); if(bret) { newArray.push(value, t); } } } return newArray; } @Override public String getName() { return "array_filter"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "array {array, boolean closure(key, value)} Filters an array by callback. The items in the array are" + " iterated over, each one sent to the closure one at a time, as key, value. The closure should" + " return true if the item should be included in the array, or false if not. The filtered array is" + " then returned by the function. If the array is associative, the keys will continue to map to" + " the same values, however a normal array, the values are simply pushed onto the new array, and" + " won't correspond to the same values per se."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Pulls out only the odd numbers", "@array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);\n" + "@newArray = array_filter(@array, closure(@key, @value){\n" + "\treturn(@value % 2 == 1);\n" + "});\n" + "msg(@newArray);\n"), new ExampleScript("Pulls out only the odd numbers in an associative array", "@array = array('one': 1, 'two': 2, 'three': 3, 'four': 4);\n" + "@newArray = array_filter(@array, closure(@key, @value){\n" + "\treturn(@value % 2 == 1);\n" + "});\n" + "msg(@newArray);\n") }; } } @api public static class array_deep_clone extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREInsufficientArgumentsException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(args.length != 1) { throw new CREInsufficientArgumentsException("Expecting exactly one argument", t); } if(!(args[0].isInstanceOf(CArray.TYPE))) { throw new CRECastException("Expecting argument 1 to be an array", t); } return ((CArray) args[0]).deepClone(t); } @Override public String getName() { return "array_deep_clone"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "array {array} Performs a deep clone on an array (as opposed to a shallow clone). This is useful" + " for multidimensional arrays. See the examples for more info."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates that the array is cloned.", "@array = array(1, 2, 3, 4)\n" + "@deepClone = array_deep_clone(@array)\n" + "@deepClone[1] = 'newValue'\n" + "msg(@array)\nmsg(@deepClone)"), new ExampleScript("Demonstrated that arrays within the array are also cloned by a deep clone.", "@array = array(array('value'))\n" + "@deepClone = array_deep_clone(@array)\n" + "@deepClone[0][0] = 'newValue'\n" + "msg(@array)\nmsg(@deepClone)") }; } } @api public static class array_shallow_clone extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREInsufficientArgumentsException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { if(args.length != 1) { throw new CREInsufficientArgumentsException("Expecting exactly one argument", t); } if(!(args[0].isInstanceOf(CArray.TYPE))) { throw new CRECastException("Expecting argument 1 to be an array", t); } CArray array = (CArray) args[0]; CArray shallowClone = (array.isAssociative() ? CArray.GetAssociativeArray(t) : new CArray(t)); for(Mixed key : array.keySet()) { shallowClone.set(key, array.get(key, t), t); } return shallowClone; } @Override public String getName() { return "array_shallow_clone"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "array {array} Performs a shallow clone on an array (as opposed to a deep clone)." + " See the examples for more info."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Demonstrates that the array is cloned.", "@array = array(1, 2, 3, 4)\n" + "@shallowClone = array_shallow_clone(@array)\n" + "@shallowClone[1] = 'newValue'\n" + "msg(@array)\nmsg(@shallowClone)"), new ExampleScript("Demonstrated that arrays within the array are not cloned by a shallow clone.", "@array = array(array('value'))\n" + "@shallowClone = array_shallow_clone(@array)\n" + "@shallowClone[0][0] = 'newValue'\n" + "msg(@array)\nmsg(@shallowClone)") }; } } @api public static class array_iterate extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); CClosure closure = Static.getObject(args[1], t, CClosure.class); for(Mixed key : array.keySet()) { try { closure.executeCallable(environment, t, key, array.get(key, t)); } catch (ProgramFlowManipulationException ex) { // Ignored } } return array; } @Override public String getName() { return "array_iterate"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "array {array, closure} Iterates across an array, calling the closure for each value of the array." + " The closure should accept two arguments, the key and the value. This method can be used in some" + " code to increase readability, to increase re-usability, or keep variables created in a loop in" + " an isolated scope. Note that this runs at approximately the same speed as a for loop, which is" + " probably slower than a foreach loop. Any values returned from the closure are silently ignored." + " Returns a reference to the original array."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic use with normal arrays", "@array = array(1, 2, 3);\n" + "array_iterate(@array, closure(@key, @value){\n" + "\tmsg(@value);\n" + "});"), new ExampleScript("Use with associative arrays", "@array = array(one: 1, two: 2, three: 3);\n" + "array_iterate(@array, closure(@key, @value){\n" + "\tmsg(\"@key: @value\");\n" + "});") }; } } @api public static class array_reduce extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREIllegalArgumentException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); CClosure closure = Static.getObject(args[1], t, CClosure.class); if(array.isEmpty()) { return CNull.NULL; } if(array.size() == 1) { // This line looks bad, but all it does is return the first (and since we know only) value in the array, // whether or not it is associative or normal. return array.get(array.keySet().toArray(new Mixed[0])[0], t); } List<Mixed> keys = new ArrayList<>(array.keySet()); Mixed lastValue = array.get(keys.get(0), t); for(int i = 1; i < keys.size(); ++i) { lastValue = closure.executeCallable(environment, t, lastValue, array.get(keys.get(i), t)); if(lastValue instanceof CVoid) { throw new CREIllegalArgumentException("The closure passed to " + getName() + " cannot return void.", t); } } return lastValue; } @Override public String getName() { return "array_reduce"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "mixed {array, closure} Reduces an array to a single value. This is useful for, for instance," + " summing the values of an array. The previously calculated value, then the next value of the" + " array are sent to the closure, which is expected to return a value, based on the two values," + " which will be sent again to the closure as the new calculated value. If the array is empty," + " null is returned, and if the array has exactly one value in it, only that value is returned." + " Associative arrays are supported, but the order is based on the key order, which may not be as" + " expected. The keys of the array are ignored."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Summing the values of an array", "@array = array(1, 2, 4, 8);\n" + "@sum = array_reduce(@array, closure(@soFar, @next){\n" + "\treturn(@soFar + @next);\n" + "});\n" + "msg(@sum);"), new ExampleScript("Combining the strings in an array", "@array = array('a', 'b', 'c');\n" + "@string = array_reduce(@array, closure(@soFar, @next){\n" + "\treturn(@soFar . @next);\n" + "});\n" + "msg(@string);") }; } } @api public static class array_reduce_right extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREIllegalArgumentException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); CClosure closure = Static.getObject(args[1], t, CClosure.class); if(array.isEmpty()) { return CNull.NULL; } if(array.size() == 1) { // This line looks bad, but all it does is return the first (and since we know only) value in the array, // whether or not it is associative or normal. return array.get(array.keySet().toArray(new Mixed[0])[0], t); } List<Mixed> keys = new ArrayList<>(array.keySet()); Mixed lastValue = array.get(keys.get(keys.size() - 1), t); for(int i = keys.size() - 2; i >= 0; --i) { lastValue = closure.executeCallable(environment, t, lastValue, array.get(keys.get(i), t)); if(lastValue instanceof CVoid) { throw new CREIllegalArgumentException("The closure passed to " + getName() + " cannot return void.", t); } } return lastValue; } @Override public String getName() { return "array_reduce_right"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "mixed {array, closure} Reduces an array to a single value. This works in reverse of array_reduce()." + " This is useful for, for instance, summing the values of an array. The previously calculated" + " value, then the previous value of the array are sent to the closure, which is expected to" + " return a value, based on the two values, which will be sent again to the closure as the new" + " calculated value. If the array is empty, null is returned, and if the array has exactly one" + " value in it, only that value is returned. Associative arrays are supported, but the order is" + " based on the key order, which may not be as expected. The keys of the array are ignored."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Summing the values of an array", "@array = array(1, 2, 4, 8);\n" + "@sum = array_reduce_right(@array, closure(@soFar, @next){\n" + "\treturn(@soFar + @next);\n" + "});\n" + "msg(@sum);"), new ExampleScript("Combining the strings in an array", "@array = array('a', 'b', 'c');\n" + "@string = array_reduce_right(@array, closure(@soFar, @next){\n" + "\treturn(@soFar . @next);\n" + "});\n" + "msg(@string);") }; } } @api public static class array_every extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); CClosure closure = Static.getObject(args[1], t, CClosure.class); for(Mixed c : array.keySet()) { Mixed fr = closure.executeCallable(environment, t, array.get(c, t)); boolean ret = ArgumentValidation.getBooleanish(fr, t); if(ret == false) { return CBoolean.FALSE; } } return CBoolean.TRUE; } @Override public String getName() { return "array_every"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "boolean {array, closure} Returns true if every value in the array meets some test, which the closure" + " should return true or false about. Not all values will necessarily be checked, once a value is" + " determined to fail the check, execution is stopped, and false is returned. The closure will be" + " passed each value in the array, one at a time, and must return a boolean."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "@array = array(1, 3, 5);\n" + "@arrayIsAllOdds = array_every(@array, closure(@value){\n" + "\treturn(@value % 2 == 1);\n" + "});\n" + "msg(@arrayIsAllOdds);"), new ExampleScript("Basic usage, with false condition", "@array = array(1, 3, 4);\n" + "@arrayIsAllOdds = array_every(@array, closure(@value){\n" + "\treturn(@value % 2 == 1);\n" + "});\n" + "msg(@arrayIsAllOdds);") }; } } @api public static class array_some extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); CClosure closure = Static.getObject(args[1], t, CClosure.class); for(Mixed c : array.keySet()) { Mixed fr = closure.executeCallable(environment, t, array.get(c, t)); boolean ret = ArgumentValidation.getBooleanish(fr, t); if(ret == true) { return CBoolean.TRUE; } } return CBoolean.FALSE; } @Override public String getName() { return "array_some"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "boolean {array, closure} Returns true if any value in the array meets some test, which the closure" + " should return true or false about. Not all values will necessarily be checked, once a value is" + " determined to pass the check, execution is stopped, and true is returned. The closure will be" + " passed each value in the array, one at a time, and must return a boolean."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "@array = array(2, 4, 8);\n" + "@arrayHasOdds = array_some(@array, closure(@value){\n" + "\treturn(@value % 2 == 1);\n" + "});\n" + "msg(@arrayHasOdds);"), new ExampleScript("Basic usage, with true condition", "@array = array(2, 3, 4);\n" + "@arrayHasOdds = array_some(@array, closure(@value){\n" + "\treturn(@value % 2 == 1);\n" + "});\n" + "msg(@arrayHasOdds);") }; } } @api public static class array_map extends AbstractFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREIllegalArgumentException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); CClosure closure = Static.getObject(args[1], t, CClosure.class); CArray newArray = (array.isAssociative() ? CArray.GetAssociativeArray(t) : new CArray(t, (int) array.size())); for(Mixed c : array.keySet()) { Mixed fr = closure.executeCallable(environment, t, array.get(c, t)); if(fr.isInstanceOf(CVoid.TYPE)) { throw new CREIllegalArgumentException("The closure passed to " + getName() + " must return a value.", t); } newArray.set(c, fr, t); } return newArray; } @Override public String getName() { return "array_map"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "array {array, closure} Calls the closure on each element of an array," + " and returns an array that contains the results."; } @Override public Version since() { return MSVersion.V3_3_1; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "@areaOfSquare = closure(@sideLength){\n" + "\treturn(@sideLength ** 2);\n" + "};\n" + "// A collection of square sides\n" + "@squares = array(1, 4, 8);\n" + "@areas = array_map(@squares, @areaOfSquare);\n" + "msg(@areas);"), new ExampleScript("Parsing a csv file with minimal code", "string @file = 'a, b, c\\nz, y, x\\n1, 2, 3\\n99, 98, 97'; // Could be a read()\n" + "array @list = array_map(split('\\n', @file), closure(@line) {\n" + " return(split(',', @line));\n" + "});\n" + "msg(@list);") }; } } @api @seealso({array_merge.class}) public static class array_intersect extends AbstractFunction { @MEnum("ms.lang.ArrayIntersectComparisonMode") public static enum ArrayIntersectComparisonMode { EQUALS(new equals()), STRICT_EQUALS(new sequals()), HASH(null); private final Function comparisonFunction; private ArrayIntersectComparisonMode(Function f) { this.comparisonFunction = f; } public Function getComparisonFunction() { return comparisonFunction; } } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CREIllegalArgumentException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray one = Static.getArray(args[0], t); CArray two = Static.getArray(args[1], t); CClosure closure = null; ArrayIntersectComparisonMode mode = ArrayIntersectComparisonMode.HASH; boolean associativeMode = one.isAssociative() || two.isAssociative(); if(args.length > 2) { if(associativeMode) { throw new CREIllegalArgumentException("For associative arrays, only 2 parameters may be provided," + " the comparison mode value is not used.", t); } if(args[2].isInstanceOf(CClosure.TYPE)) { closure = Static.getObject(args[2], t, CClosure.class); } else { mode = ArgumentValidation.getEnum(args[2], ArrayIntersectComparisonMode.class, t); } } CArray ret = new CArray(t); if(!associativeMode && closure == null && mode == ArrayIntersectComparisonMode.HASH) { // Optimize for O(n log n) method Set<Integer> a2Set = new TreeSet<>(); for(Mixed c : two) { a2Set.add(c.hashCode()); } // Iterate one, and check if the hash of each value is in the set. If so, add it. for(Mixed c : one) { if(a2Set.contains(c.hashCode())) { ret.push(c, t); } } } else { Mixed[] k1 = new Mixed[(int) one.size()]; Mixed[] k2 = new Mixed[(int) two.size()]; one.keySet().toArray(k1); two.keySet().toArray(k2); equals equals = new equals(); Function comparisonFunction = mode.getComparisonFunction(); i: for(int i = 0; i < k1.length; i++) { for(int j = 0; j < k2.length; j++) { if(associativeMode) { if(equals.exec(t, environment, k1[i], k2[j]).getBoolean()) { ret.set(k1[i], one.get(k1[i], t), t); continue i; } } else { if(closure == null) { if(comparisonFunction != null) { if(ArgumentValidation.getBoolean(comparisonFunction.exec(t, environment, one.get(k1[i], t), two.get(k2[j], t) ), t)) { ret.push(one.get(k1[i], t), t); continue i; } } else { throw new Error(); } } else { Mixed fre = closure.executeCallable(environment, t, one.get(k1[i], t), two.get(k2[j], t)); boolean res = ArgumentValidation.getBoolean(fre, fre.getTarget()); if(res) { ret.push(one.get(k1[i], t), t); continue i; } } } } } } return ret; } @Override public String getName() { return "array_intersect"; } @Override public Integer[] numArgs() { return new Integer[]{2, 3}; } @Override public String docs() { return "array {array1, array2, [comparisonMode]|array1, array2, comparisonClosure} Returns an array that is" + " the intersection of the two provided arrays. If either" + " array is associative, it puts the function in associative mode. For normal arrays, the values" + " are compared, and for associative arrays, the keys are compared, but the values are taken from" + " the left array. comparisonMode is only applicable for normal arrays, and defaults to HASH, but" + " determines the mode in which the system decides" + " if two values are equal or not. A closure may be sent" + " instead, which should return true if the two values are considered equals or not. Using the HASH" + " mode is fastest, as this puts the function in an optimizing mode, and it can run at O(n log n)." + " Otherwise, the runtime is O(n**2). The results between HASH and STRICT_EQUALS should almost never" + " be different, and so in that case using STRICT_EQUALS has a lower performance for no gain," + " but there may be some cases where using" + " the hash code is not desirable. EQUALS is necessary if you wish to disregard typing, so that" + " array(1, 2, 3) and array('1', '2', '3') are considered equal. Duplicate values in the left" + " array are duplicated, but duplicates in the right are not."; } @Override public Version since() { return MSVersion.V3_3_3; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Usage with associative array", "array_intersect(array(one: 1, five: 5), array(one: 1, three: 3))"), new ExampleScript("Usage with normal arrays. The default comparison method is HASH", "array_intersect(array(1, 2, 3), array(2, 3, 4))"), new ExampleScript("Demonstrates that STRICT_EQUALS does not consider different types to be equal", "array_intersect(array('1', '2', '3'), array(1, 2, 3), 'STRICT_EQUALS')"), new ExampleScript("Note that the results of this method are the same as the previous example," + " but this version would be faster, and is preferred in all but the most exceptional cases.", "array_intersect(array('1', '2', '3'), array(1, 2, 3), 'HASH')"), new ExampleScript("Demonstrates usage with equals. Note that '1' == 1 (but does not === 1) but since" + " the comparison method uses equals, not sequals, these arrays are considered equivalent.", "array_intersect(array('1', '2', '3'), array(1, 2, 3), 'EQUALS')"), new ExampleScript("Usage with a custom closure", "array_intersect(\n" + "\tarray(array(id: 1, qty: 2), array(id: 2, qty: 5)),\n" + "\tarray(array(id: 1, qty: 2), array(id: 5, qty: 10)),\n" + "\tclosure(@a, @b) {\n" + "\t\treturn(@a['id'] == @b['id']);\n" + "})"), new ExampleScript("The value is taken from the left array. This is not important for primitives, but" + " when using arrays and a custom closure, it may make a difference.", "array_intersect(\n" + "\tarray(array(id: 1, pos: 'left')),\n" + "\tarray(array(id: 1, pos: 'right')),\n" + "\tclosure(@a, @b) {\n" + "\t\treturn(@a['id'] == @b['id']);\n" + "})"), new ExampleScript("Demonstrates behavior with duplicate values", "msg(array_intersect(\n" + "\tarray(1, 1, 1, 2, 3),\n" + "\tarray(1, 2)));\n" + "msg(array_intersect(\n" + "\tarray(1, 2, 3),\n" + "\tarray(1, 1, 1)));") }; } } @api public static class array_subset_of extends AbstractFunction { @Override public Version since() { return MSVersion.V3_3_2; } @Override public String getName() { return "array_subset_of"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CREIllegalArgumentException.class}; } @Override public String docs() { return "boolean {array, array} " + "Returns true if first array is a subset of second array."; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { Mixed constA = args[0]; Mixed constB = args[1]; if(!(constA.isInstanceOf(CArray.TYPE))) { throw new CREIllegalArgumentException("Expecting an array, but received " + constA, t); } if(!(constB.isInstanceOf(CArray.TYPE))) { throw new CREIllegalArgumentException("Expecting an array, but received " + constB, t); } return CBoolean.get(subsetOf(constA, constB, t)); } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Basic usage", "@arrayA = array(0, 1)\n" + "@arrayB = array(0, 1, 5, 9)\n" + "array_subset_of(@arrayA, @arrayB)"), new ExampleScript("Basic usage", "@arrayA = array(0, 1)\n" + "@arrayB = array(0, 2, 5, 9)\n" + "array_subset_of(@arrayA, @arrayB)"), new ExampleScript("Mix array", "@arrayA = array(a: 1, b: array('one', 'two'))\n" + "@arrayB = array(a: 1, b: array('one', 'two', 'three'), c: 3)\n" + "array_subset_of(@arrayA, @arrayB)"), new ExampleScript("Mix array", "@arrayA = array(a: 1, b: array('one', 'two'))\n" + "@arrayB = array(a: 1, b: array('two', 'one', 'three'), c: 3)\n" + "array_subset_of(@arrayA, @arrayB)") }; } public boolean subsetOf(Mixed constA, Mixed constB, Target t) { if(!constA.typeof().equals(constB.typeof())) { return false; } if(constA.isInstanceOf(CArray.TYPE)) { CArray arrA = (CArray) constA; CArray arrB = (CArray) constB; if(arrA.isAssociative() != arrB.isAssociative()) { return false; } if(arrA.isAssociative()) { for(String key : arrA.stringKeySet()) { if(!arrB.containsKey(key)) { return false; } Mixed eltA = arrA.get(key, t); Mixed eltB = arrB.get(key, t); if(!subsetOf(eltA, eltB, t)) { return false; } } } else { for(int i = 0; i < arrA.size(); i++) { if(!arrB.containsKey(i)) { return false; } Mixed eltA = arrA.get(i, t); Mixed eltB = arrB.get(i, t); if(!subsetOf(eltA, eltB, t)) { return false; } } } } else if(!equals.doEquals(constA, constB)) { return false; } return true; } } @api @seealso(array_push.class) public static class array_push_all extends CompositeFunction { @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class}; } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public String getName() { return "array_push_all"; } @Override public Integer[] numArgs() { return new Integer[]{2}; } @Override public String docs() { return "void {array, values} Pushes all the values of an array individually. If you try to push an array" + " onto array_push, this will give you a two dimensional array, this method pushes the sub values" + " of the values array into the destination array."; } @Override public Version since() { return MSVersion.V3_3_4; } @Override protected String script() { return getBundledCode(); } } @api @seealso(array_rand.class) public static class array_get_rand extends AbstractFunction { @Override public String getName() { return "array_get_rand"; } @Override public Integer[] numArgs() { return new Integer[]{1}; } @Override public String docs() { return "mixed {array} Returns a random value from an array." + " If the array is empty a LengthException is thrown."; } @Override public Class<? extends CREThrowable>[] thrown() { return new Class[]{CRECastException.class, CRELengthException.class}; } Random rand = new Random(); @Override public Mixed exec(Target t, Environment environment, Mixed... args) throws ConfigRuntimeException { CArray array = Static.getArray(args[0], t); if(array.isEmpty()) { throw new CRELengthException("Array is empty", t); } List<Mixed> keySet = new ArrayList<>(array.keySet()); return array.get(keySet.get(java.lang.Math.abs(rand.nextInt() % (int) array.size())), t); } @Override public boolean isRestricted() { return false; } @Override public Boolean runAsync() { return null; } @Override public Version since() { return MSVersion.V3_3_4; } @Override public ExampleScript[] examples() throws ConfigCompileException { return new ExampleScript[]{ new ExampleScript("Normal array usage", "array_get_rand(array(1, 2, 3, 4, 5))"), new ExampleScript("Associative array usage", "array_get_rand(array(one: 1, two: 2, three: 3, four: 4, five: 5))"), }; } } }
package com.sanchez.fmf.fragment; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AutoCompleteTextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.places.Places; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.sanchez.fmf.R; import com.sanchez.fmf.adapter.PlaceAutocompleteAdapter; import java.util.ArrayList; import java.util.List; import java.util.Locale; import butterknife.Bind; import butterknife.ButterKnife; public class MainFragment extends Fragment implements GoogleApiClient.OnConnectionFailedListener{ public String TAG = MainFragment.class.getSimpleName(); @Bind(R.id.search_autocomplete) AutoCompleteTextView mSearchAutocomplete; private static final int GOOGLE_API_CLIENT_ID = 0; private static final LatLngBounds BOUNDS_NORTH_AMERICA = new LatLngBounds(new LatLng(18.000000, -64.000000), new LatLng(67.000000, -165.000000)); private GoogleApiClient googleApiClient; private PlaceAutocompleteAdapter mAutocompleteAdapter; public static MainFragment newInstance() { MainFragment fragment = new MainFragment(); return fragment; } public MainFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); googleApiClient = new GoogleApiClient .Builder(getActivity()) .addApi(Places.GEO_DATA_API) .enableAutoManage((FragmentActivity) getActivity(), GOOGLE_API_CLIENT_ID, this) .build(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_main, container, false); ButterKnife.bind(this, v); mAutocompleteAdapter = new PlaceAutocompleteAdapter(getActivity(), android.R.layout.simple_list_item_1, googleApiClient, BOUNDS_NORTH_AMERICA, null); mSearchAutocomplete.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS); mSearchAutocomplete.setAdapter(mAutocompleteAdapter); return v; } @Override public void onConnectionFailed(ConnectionResult connectionResult) { Log.e(TAG, "Google Places API connection failed with error code: " + connectionResult.getErrorCode()); Toast.makeText(getActivity(), "Google Places API unavailable right now. Error code:" + connectionResult.getErrorCode(), Toast.LENGTH_LONG).show(); } private class GetCoordinatesFromLocation extends AsyncTask<String, Void, ArrayList<Double>> { @Override protected ArrayList<Double> doInBackground(String... location) { ArrayList<Double> returnList = new ArrayList<Double>(); try { Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault()); List<Address> addresses = geocoder.getFromLocationName(location[0], 1); if(addresses.size() > 0) { Address address = addresses.get(0); returnList.add(address.getLatitude()); returnList.add(address.getLongitude()); return returnList; } else { return null; } } catch (Exception e) { Log.e(TAG, e.getMessage()); Toast.makeText(getActivity(), "Geocoder error", Toast.LENGTH_LONG).show(); } return null; } @Override protected void onPostExecute(ArrayList<Double> result) { if(result != null) { Toast.makeText(getActivity(), "Coords: lat=" + result.get(0) + " lon=" + result.get(1), Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), "Invalid input", Toast.LENGTH_LONG).show(); } } } }
/** * (TMS) */ package com.lhjz.portal.controller; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.lhjz.portal.base.BaseController; import com.lhjz.portal.entity.Label; import com.lhjz.portal.entity.Language; import com.lhjz.portal.entity.Project; import com.lhjz.portal.entity.Translate; import com.lhjz.portal.entity.TranslateItem; import com.lhjz.portal.entity.TranslateItemHistory; import com.lhjz.portal.entity.security.User; import com.lhjz.portal.model.RespBody; import com.lhjz.portal.pojo.Enum.Action; import com.lhjz.portal.pojo.Enum.Status; import com.lhjz.portal.pojo.Enum.Target; import com.lhjz.portal.pojo.ProjectForm; import com.lhjz.portal.repository.AuthorityRepository; import com.lhjz.portal.repository.LabelRepository; import com.lhjz.portal.repository.LanguageRepository; import com.lhjz.portal.repository.ProjectRepository; import com.lhjz.portal.repository.TranslateItemHistoryRepository; import com.lhjz.portal.repository.TranslateItemRepository; import com.lhjz.portal.repository.TranslateRepository; import com.lhjz.portal.repository.UserRepository; import com.lhjz.portal.util.StringUtil; import com.lhjz.portal.util.WebUtil; /** * * @author xi * * @date 2015328 1:19:05 * */ @Controller @RequestMapping("admin/project") public class ProjectController extends BaseController { static Logger logger = LoggerFactory.getLogger(ProjectController.class); @Autowired TranslateRepository translateRepository; @Autowired TranslateItemRepository translateItemRepository; @Autowired TranslateItemHistoryRepository translateItemHistoryRepository; @Autowired ProjectRepository projectRepository; @Autowired LanguageRepository languageRepository; @Autowired LabelRepository labelRepository; @Autowired UserRepository userRepository; @Autowired AuthorityRepository authorityRepository; private boolean isContainsMainLanguage(ProjectForm projectForm) { String[] lngs = projectForm.getLanguages().split(","); for (String lng : lngs) { if (lng.equals(String.valueOf(projectForm.getLanguage()))) { return true; } } return false; } @RequestMapping(value = "create", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody create(@Valid ProjectForm projectForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream() .map(err -> err.getDefaultMessage()) .collect(Collectors.joining("<br/>"))); } Project project3 = projectRepository.findOneByName(projectForm .getName()); if (project3 != null) { return RespBody.failed("!"); } if (!isContainsMainLanguage(projectForm)) { return RespBody.failed("!"); } Project project = new Project(); project.setCreateDate(new Date()); project.setCreator(WebUtil.getUsername()); project.setDescription(projectForm.getDesc()); project.setName(projectForm.getName()); project.setStatus(Status.New); project.setLanguage(languageRepository.findOne(projectForm .getLanguage())); String[] lngArr = projectForm.getLanguages().split(","); List<Long> collect = Arrays.asList(lngArr).stream().map((lng) -> { return Long.valueOf(lng); }).collect(Collectors.toList()); List<Language> languages = languageRepository.findAll(collect); project.getLanguages().addAll(languages); List<User> watchers = null; if (StringUtil.isNotEmpty(projectForm.getWatchers())) { watchers = userRepository.findAll(Arrays.asList(projectForm .getWatchers().split(","))); project.getWatchers().addAll(watchers); } Project project2 = projectRepository.saveAndFlush(project); for (Language language : languages) { language.getProjects().add(project2); } languageRepository.save(languages); languageRepository.flush(); if (watchers != null) { for (User user : watchers) { user.getWatcherProjects().add(project2); } userRepository.save(watchers); userRepository.flush(); } log(Action.Create, Target.Project, projectForm); return RespBody.succeed(project2); } private boolean isExistLanguage(Set<Language> lngs, Language lng) { for (Language language : lngs) { if (language.getId().equals(lng.getId())) { return true; } } return false; } private boolean isExistWatcher(Set<User> watchers, User user) { for (User watcher : watchers) { if (watcher.getUsername().equals(user.getUsername())) { return true; } } return false; } @RequestMapping(value = "update", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody update(@RequestParam("id") Long id, @Valid ProjectForm projectForm, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return RespBody.failed(bindingResult.getAllErrors().stream() .map(err -> err.getDefaultMessage()) .collect(Collectors.joining("<br/>"))); } if (!isContainsMainLanguage(projectForm)) { return RespBody.failed("!"); } Project project = projectRepository.findOne(id); project.setDescription(projectForm.getDesc()); Project project2 = projectRepository.findOneByName(projectForm .getName()); if (project2 == null) { project.setName(projectForm.getName()); } project.setStatus(Status.Updated); project.setUpdateDate(new Date()); project.setUpdater(WebUtil.getUsername()); if (!project.getLanguage().getId().equals(projectForm.getLanguage())) { project.setLanguage(languageRepository.findOne(projectForm .getLanguage())); } String[] lngArr = projectForm.getLanguages().split(","); List<Long> collect = Arrays.asList(lngArr).stream().map((lng) -> { return Long.valueOf(lng); }).collect(Collectors.toList()); Set<Language> languages = project.getLanguages(); for (Language language : languages) { if (!collect.contains(language.getId())) { language.getProjects().remove(project); } } HashSet<Language> languages2 = new HashSet<Language>( languageRepository.findAll(collect)); for (Language language : languages2) { if (!isExistLanguage(languages, language)) { language.getProjects().add(project); } } languageRepository.save(languages); languageRepository.save(languages2); languageRepository.flush(); if (StringUtil.isNotEmpty(projectForm.getWatchers())) { List<String> watchers = Arrays.asList(projectForm.getWatchers() .split(",")); Set<User> watchers2 = project.getWatchers(); for (User user : watchers2) { if (!watchers.contains(user.getUsername())) { user.getWatcherProjects().remove(project); } } List<User> watcher3 = userRepository.findAll(watchers); for (User user : watcher3) { if (!isExistWatcher(watchers2, user)) { user.getWatcherProjects().add(project); } } userRepository.save(watchers2); userRepository.save(watcher3); languageRepository.flush(); project.setWatchers(new HashSet<User>(watcher3)); } else { project.getWatchers().stream().forEach((w) -> { w.getWatcherProjects().remove(project); }); userRepository.save(project.getWatchers()); userRepository.flush(); project.getWatchers().clear(); } project.setLanguages(languages2); projectRepository.saveAndFlush(project); log(Action.Update, Target.Project, projectForm); return RespBody.succeed(project); } @RequestMapping(value = "delete", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody delete(@RequestParam("id") Long id) { Project project = projectRepository.findOne(id); if (project == null) { return RespBody.failed(""); } Set<Language> languages = project.getLanguages(); for (Language language : languages) { language.getProjects().remove(project); } languageRepository.save(languages); languageRepository.flush(); Set<Translate> translates = project.getTranslates(); Set<TranslateItem> translateItems = new HashSet<TranslateItem>(); Set<TranslateItemHistory> translateItemHistories = new HashSet<TranslateItemHistory>(); Set<Label> labels = new HashSet<Label>(); translates.stream().forEach((t) -> { Set<TranslateItem> translateItems2 = t.getTranslateItems(); translateItems2.stream().forEach((ti) -> { ti.setTranslate(null); Set<TranslateItemHistory> translateItemHistories2 = ti.getTranslateItemHistories(); translateItemHistories2.stream().forEach((h -> { h.setTranslateItem(null); })); translateItemHistories.addAll(translateItemHistories2); }); translateItems.addAll(translateItems2); Set<Label> labels2 = t.getLabels(); labels2.stream().forEach((l) -> { l.setTranslate(null); }); labels.addAll(labels2); t.setProject(null); }); translateItemHistoryRepository.deleteInBatch(translateItemHistories); translateItemHistoryRepository.flush(); translateItemRepository.deleteInBatch(translateItems); translateItemRepository.flush(); labelRepository.deleteInBatch(labels); labelRepository.flush(); Set<User> watchers = project.getWatchers(); for (User user : watchers) { user.getWatcherProjects().remove(project); } userRepository.save(watchers); userRepository.flush(); Set<User> users = project.getUsers(); users.stream().forEach((u) -> { u.getProjects().remove(project); }); userRepository.save(users); userRepository.flush(); translateRepository.deleteInBatch(translates); translateRepository.flush(); projectRepository.delete(project); projectRepository.flush(); log(Action.Delete, Target.Project, id); return RespBody.succeed(id); } @RequestMapping(value = "deleteWatcher", method = RequestMethod.POST) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN", "ROLE_USER" }) public RespBody deleteWatcher(@RequestParam("id") Long id, @RequestParam("username") String username) { Project project = projectRepository.findOne(id); if (project == null) { return RespBody.failed(""); } User watcher = userRepository.findOne(username); if (watcher == null) { return RespBody.failed(""); } watcher.getWatcherProjects().remove(project); project.getWatchers().remove(watcher); userRepository.saveAndFlush(watcher); projectRepository.saveAndFlush(project); log(Action.Update, Target.Project, project); return RespBody.succeed(id); } @RequestMapping(value = "get", method = RequestMethod.GET) @ResponseBody @Secured({ "ROLE_SUPER", "ROLE_ADMIN" }) public RespBody get(@RequestParam("id") Long id) { Project project = projectRepository.findOne(id); if (project == null) { return RespBody.failed(""); } log(Action.Read, Target.Project, id); return RespBody.succeed(project); } }
package com.lothrazar.samscontent; import net.minecraft.block.Block; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import com.lothrazar.util.Reference; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; public class HandlerBonemealUse { private boolean isUsingBonemeal(ItemStack held ) { Item heldItem = (held == null) ? null : held.getItem(); if(heldItem == null){return false;} if(heldItem.equals(Items.dye) && held.getItemDamage() == Reference.dye_bonemeal) return true; else return false; } @SubscribeEvent public void onPlayerLeftClick(PlayerInteractEvent event) { if(event.world.isRemote){return;}//stop it from doing a secod ghost item drop if(ModSamsContent.settings.betterBonemeal == false) { return; } if(event.action == event.action.LEFT_CLICK_BLOCK) {return;} ItemStack held = event.entityPlayer.getCurrentEquippedItem(); if(isUsingBonemeal(held) ) { //was event.x, event.y, event.z Block blockClicked = event.entityPlayer.worldObj.getBlockState(event.pos).getBlock(); //if(blockClicked != Blocks.yellow_flower && blockClicked != Blocks.red_flower) {return;} if(blockClicked == null || blockClicked == Blocks.air ){return;} //event.entityPlayer.worldObj.getBlockState(event.pos) //new method: the Block itself tells what number to return, not the world. //the world wraps up the state of the block that we can query, and the //block class translates if ( blockClicked.equals(Blocks.yellow_flower))//yellow flowers have no damage variations { if(event.entityPlayer.capabilities.isCreativeMode == false) held.stackSize if(held.stackSize == 0) event.entityPlayer.inventory.setInventorySlotContents(event.entityPlayer.inventory.currentItem, null); event.entity.entityDropItem( new ItemStack(Blocks.yellow_flower ,1), 1); } if ( blockClicked.equals(Blocks.red_flower)) //the red flower is ALL the flowers { int blockClickedDamage = Blocks.red_flower.getMetaFromState(event.entityPlayer.worldObj.getBlockState(event.pos)); if(event.entityPlayer.capabilities.isCreativeMode == false) held.stackSize if(held.stackSize == 0) event.entityPlayer.inventory.setInventorySlotContents(event.entityPlayer.inventory.currentItem, null); event.entity.entityDropItem( new ItemStack(Blocks.red_flower ,1,blockClickedDamage), 1);//quantity = 1 } if ( blockClicked.equals(Blocks.waterlily)) { if(event.entityPlayer.capabilities.isCreativeMode == false) held.stackSize if(held.stackSize == 0) event.entityPlayer.inventory.setInventorySlotContents(event.entityPlayer.inventory.currentItem, null); event.entity.entityDropItem( new ItemStack(Blocks.waterlily ,1), 1); } } } }
package com.xlythe.sms.receiver; import android.app.Notification; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.provider.MediaStore; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.app.RemoteInput; import android.support.v4.app.TaskStackBuilder; import android.text.Html; import android.text.Spanned; import android.text.TextUtils; import android.util.Log; import com.xlythe.sms.MainActivity; import com.xlythe.sms.MessageActivity; import com.xlythe.sms.R; import com.xlythe.sms.drawable.ProfileDrawable; import com.xlythe.textmanager.text.Attachment; import com.xlythe.textmanager.text.Text; import com.xlythe.textmanager.text.TextManager; import com.xlythe.textmanager.text.Thread; import com.xlythe.textmanager.text.util.Utils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; public class Notifications { private static final String TAG = "Notifications"; private static final String EXTRA_INLINE_REPLY = "inline_reply"; private static final String EXTRA_TEXT = "text"; private static final String EXTRA_THREAD_ID = "thread_id"; private static final String TEXTS_VISIBLE_IN_NOTIFICATION = "texts_visible_in_notification"; private static final String NOTIFICATIONS = "notifications"; private static final String NOTIFICATION_IDS = "notification_ids"; private static final int GROUP_SUMMARY_ID = 12345; private static TextManager mManager; public static void buildNotification(Context context, Text text) { if (MessageActivity.isVisible(text.getThreadId())) { Log.w(TAG, "This thread is already visible to the user"); return; } mManager = TextManager.getInstance(context); Set<Text> texts = getVisibleTexts(context, text); buildNotification(context, getTextsFromSameSender(text, texts), text.getThreadId().hashCode()); buildGroupSummary(context, texts, GROUP_SUMMARY_ID); } private static void buildNotification(Context context, Set<Text> texts, int id) { Log.v(TAG, "Building a notification"); context = context.getApplicationContext(); addNotificationId(context, id); NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.fetch_icon_notif) .setColor(context.getResources().getColor(R.color.colorPrimary)) .setAutoCancel(true) .setDeleteIntent(buildOnDismissIntent(context, id, texts, false /*dismissAll*/)) .setContentIntent(buildOnClickIntent(context, id, texts)) .setLights(Color.WHITE, 500, 1500) .setDefaults(Notification.DEFAULT_SOUND) .setPriority(Notification.PRIORITY_HIGH) .setCategory(Notification.CATEGORY_MESSAGE) .setGroup(TAG); if (sameSender(texts)) { Log.v(TAG, "All texts are from the same sender"); Text randomText = texts.iterator().next(); ProfileDrawable icon = new ProfileDrawable(context, mManager.getMembersExceptMe(randomText).get()); builder.setLargeIcon(drawableToBitmap(icon)) .addAction(buildReplyAction(context, id, randomText)); } if (texts.size() == 1) { Log.v(TAG, "There's only one text"); buildDetailedNotification(context, texts.iterator().next(), builder); } else { buildSummaryNotification(context, texts, builder); } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(id, builder.build()); } private static void buildGroupSummary(Context context, Set<Text> texts, int id) { Log.v(TAG, "Building group summary"); context = context.getApplicationContext(); NotificationCompat.Builder builder = new NotificationCompat.Builder(context) .setSmallIcon(R.drawable.fetch_icon_notif) .setColor(context.getResources().getColor(R.color.colorPrimary)) .setAutoCancel(true) .setDeleteIntent(buildOnDismissIntent(context, id, texts, true /*dismissAll*/)) .setContentIntent(buildOnClickIntent(context, id, texts)) .setLights(Color.WHITE, 500, 1500) .setDefaults(Notification.DEFAULT_SOUND) .setPriority(Notification.PRIORITY_HIGH) .setCategory(Notification.CATEGORY_MESSAGE) .setGroup(TAG) .setGroupSummary(true); if (sameSender(texts)) { Log.v(TAG, "All texts are from the same sender"); Text randomText = texts.iterator().next(); ProfileDrawable icon = new ProfileDrawable(context, mManager.getMembersExceptMe(randomText).get()); builder.setLargeIcon(drawableToBitmap(icon)) .addAction(buildReplyAction(context, id, randomText)); } if (texts.size() == 1) { Log.v(TAG, "There's only one text"); buildDetailedNotification(context, texts.iterator().next(), builder); } else { buildSummaryNotification(context, texts, builder); } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.notify(id, builder.build()); } private static boolean sameSender(Set<Text> texts) { String prevNumber = null; for (Text text : texts) { if (prevNumber != null) { if (!prevNumber.equals(text.getThreadId())) { return false; } } prevNumber = text.getThreadId(); } return true; } /** * Dismisses all notifications for the given thread */ public static void dismissNotification(Context context, long threadId) { dismissNotification(context, Long.toString(threadId)); } /** * Dismisses all notifications for the given thread */ public static void dismissNotification(Context context, Thread thread) { dismissNotification(context, thread.getId()); } /** * Dismisses all notifications for the given thread */ public static void dismissNotification(Context context, String threadId) { // Clean up any data regarding this thread clearNotification(context, threadId); // Dismiss the notification for the thread NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(threadId.hashCode()); // If there are no notifications left, dismiss the summary too Set<Text> texts = getVisibleTexts(context); if (texts.isEmpty()) { notificationManager.cancel(GROUP_SUMMARY_ID); } else { buildGroupSummary(context, texts, GROUP_SUMMARY_ID); } } /** * Dismisses all notifications */ public static void dismissAllNotifications(Context context) { // Dismiss all notifications we've created NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancelAll(); // Stop persisting the data from those notifications clearAllNotifications(context); } /** * Stops persisting any notifications related to the given thread */ private static void clearNotification(Context context, String threadId) { // Grab all the notifications SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); Set<String> dataSet = prefs.getStringSet(NOTIFICATIONS, new HashSet<String>()); // Loop over them and remove any that have the same id as the thread Iterator<String> iterator = dataSet.iterator(); while (iterator.hasNext()) { String serializedData = iterator.next(); Text text = Text.fromBytes(Utils.hexToBytes(serializedData)); if (threadId.equals(text.getThreadId())) { iterator.remove(); } } // Re-save the notifications editor.putStringSet(NOTIFICATIONS, dataSet); editor.apply(); } /** * Stops persisting notification data */ private static void clearAllNotifications(Context context) { context = context.getApplicationContext(); SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); editor.clear(); editor.apply(); } /** * Returns the texts we're currently showing in the notification. */ private static Set<Text> getVisibleTexts(Context context) { return getVisibleTexts(context, null); } /** * Returns the texts we're currently showing in the notification. Text, if not null, is added to that set. */ private static Set<Text> getVisibleTexts(Context context, Text text) { Set<Text> texts = new HashSet<>(); SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); Set<String> dataSet = prefs.getStringSet(NOTIFICATIONS, new HashSet<String>()); if (text != null) { dataSet.add(Utils.bytesToHex(text.toBytes())); editor.putStringSet(NOTIFICATIONS, dataSet); editor.apply(); } for (String serializedData : dataSet) { texts.add(Text.fromBytes(Utils.hexToBytes(serializedData))); } return texts; } private static void addNotificationId(Context context, int id) { SharedPreferences prefs = getSharedPreferences(context); SharedPreferences.Editor editor = prefs.edit(); Set<String> idsAsStrings = prefs.getStringSet(NOTIFICATION_IDS, new HashSet<String>()); idsAsStrings.add(Integer.toString(id)); editor.putStringSet(NOTIFICATION_IDS, idsAsStrings); editor.apply(); } private static Set<Integer> getNotificationIds(Context context) { Set<Integer> ids = new HashSet<>(); SharedPreferences prefs = getSharedPreferences(context); Set<String> idsAsStrings = prefs.getStringSet(NOTIFICATION_IDS, new HashSet<String>()); for (String string : idsAsStrings) { ids.add(Integer.parseInt(string)); } return ids; } private static Set<Text> getTextsFromSameSender(Text original, Set<Text> texts) { Set<Text> sameGroup = new HashSet<>(); for (Text text : texts) { if (text.getThreadIdAsLong() == original.getThreadIdAsLong()) { sameGroup.add(text); } } return sameGroup; } private static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap; if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if(bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } private static PendingIntent buildOnClickIntent(Context context, int requestCode, Set<Text> texts) { TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); Intent intent; if (sameSender(texts)) { intent = new Intent(context, MessageActivity.class); stackBuilder.addParentStack(MessageActivity.class); String threadId = texts.iterator().next().getThreadId(); intent.putExtra(MessageActivity.EXTRA_THREAD_ID, threadId); } else { intent = new Intent(context, MainActivity.class); stackBuilder.addParentStack(MainActivity.class); } stackBuilder.addNextIntent(intent); return stackBuilder.getPendingIntent(requestCode, PendingIntent.FLAG_UPDATE_CURRENT); } private static PendingIntent buildOnDismissIntent(Context context, int requestCode, Set<Text> texts, boolean dismissAll) { Intent dismissIntent = new Intent(context, OnDismissReceiver.class); if (!dismissAll) { // All texts are by the same sender, so grab one of the threads String threadId = texts.iterator().next().getThreadId(); dismissIntent.putExtra(EXTRA_THREAD_ID, threadId); } return PendingIntent.getBroadcast(context, requestCode, dismissIntent, PendingIntent.FLAG_UPDATE_CURRENT); } private static NotificationCompat.Action buildReplyAction(Context context, int requestCode, Text text) { RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_INLINE_REPLY) .setLabel(context.getString(R.string.action_reply)) .build(); Intent replyIntent = new Intent(context, OnReplyReceiver.class); replyIntent.putExtra(EXTRA_TEXT, text); PendingIntent onReplyPendingIntent = PendingIntent.getBroadcast(context, requestCode, replyIntent, PendingIntent.FLAG_UPDATE_CURRENT); return new NotificationCompat.Action.Builder(R.drawable.ic_send, context.getString(R.string.action_reply), onReplyPendingIntent) .addRemoteInput(remoteInput) .build(); } /** * Only one message, can be text or Image/Video thumbnail */ private static void buildDetailedNotification(Context context, Text text, NotificationCompat.Builder builder) { builder.setContentTitle(mManager.getSender(text).get().getDisplayName()); if (text.getAttachment() != null && text.getAttachment().getType() == Attachment.Type.IMAGE) { NotificationCompat.BigPictureStyle pictureStyle = new NotificationCompat.BigPictureStyle(); try { Spanned s = Html.fromHtml(italic(context.getString(R.string.notification_label_picture))); ProfileDrawable icon = new ProfileDrawable(context, mManager.getMembersExceptMe(text).get()); Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), text.getAttachment().getUri()); builder.setLargeIcon(bitmap) .setContentText(s) .setStyle(pictureStyle); pictureStyle.setBigContentTitle(mManager.getSender(text).get().getDisplayName()) .bigLargeIcon(drawableToBitmap(icon)) .setSummaryText(s) .bigPicture(bitmap); } catch (IOException e) { e.printStackTrace(); } } else { NotificationCompat.BigTextStyle textStyle = new NotificationCompat.BigTextStyle(); builder.setStyle(textStyle); textStyle.setBigContentTitle(mManager.getSender(text).get().getDisplayName()); // Maybe add video too, but we have a problem with thumbnails without glide if (text.getAttachment() != null && text.getAttachment().getType() == Attachment.Type.VIDEO) { Spanned s = Html.fromHtml(italic(context.getString(R.string.notification_label_video))); builder.setContentText(s); textStyle.bigText(s); } else if (text.getAttachment() != null && text.getAttachment().getType() == Attachment.Type.VOICE) { Spanned s = Html.fromHtml(italic(context.getString(R.string.notification_label_voice))); builder.setContentText(s); textStyle.bigText(s); } else { builder.setContentText(text.getBody()); textStyle.bigText(text.getBody()); } } } /** * Multiple messages, should all look the same unless its only one conversation */ private static void buildSummaryNotification(Context context, Set<Text> texts, NotificationCompat.Builder builder) { NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); Set<String> names = new HashSet<>(); inboxStyle.setBigContentTitle(context.getString(R.string.notification_label_new_messages, texts.size())); List<Text> sortedTexts = new ArrayList<>(texts); Collections.sort(sortedTexts); for (Text text: sortedTexts) { if (text.getAttachment() != null) { int typeString = 0; switch(text.getAttachment().getType()) { case IMAGE: typeString = R.string.notification_label_picture; break; case VIDEO: typeString = R.string.notification_label_video; break; case VOICE: typeString = R.string.notification_label_voice; break; } inboxStyle.addLine(Html.fromHtml( bold(mManager.getSender(text).get().getDisplayName()) + " " + italic(context.getString(typeString)))); } else { String body = text.getBody(); if (body == null) body = ""; inboxStyle.addLine(Html.fromHtml( bold(mManager.getSender(text).get().getDisplayName()) + " " + body)); } names.add(mManager.getSender(text).get().getDisplayName()); } builder.setContentTitle(context.getString(R.string.notification_label_new_messages, texts.size())) .setContentText(TextUtils.join(", ", names)) .setStyle(inboxStyle); } private static String italic(String string) { return "<i>" + string + "</i>"; } private static String bold(String string) { return "<b>" + string + "</b>"; } private static SharedPreferences getSharedPreferences(Context context) { return context.getApplicationContext().getSharedPreferences(TEXTS_VISIBLE_IN_NOTIFICATION, Context.MODE_PRIVATE); } public static final class OnReplyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { CharSequence reply = getMessageText(intent); Text text = getText(intent); if (!TextUtils.isEmpty(reply)) { Log.d(TAG, "Sending reply"); mManager.send(new Text.Builder() .message(reply.toString()) .addRecipients(mManager.getMembersExceptMe(text).get()) .build()); } else { Log.w(TAG, "Was told to send a reply, but there was no message. Opening activity for thread " + text.getThreadId()); Intent startActivity = new Intent(context, MessageActivity.class); startActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity.putExtra(MessageActivity.EXTRA_THREAD_ID, text.getThreadId()); context.startActivity(startActivity); } Notifications.dismissNotification(context, text.getThreadId()); } private CharSequence getMessageText(Intent intent) { Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); if (remoteInput != null) { return remoteInput.getCharSequence(EXTRA_INLINE_REPLY); } return null; } private Text getText(Intent intent) { return intent.getParcelableExtra(EXTRA_TEXT); } } public static final class OnDismissReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.v(TAG, "Clearing notifications"); if (intent.hasExtra(EXTRA_THREAD_ID)) { String threadId = intent.getStringExtra(EXTRA_THREAD_ID); Notifications.dismissNotification(context, threadId); } else { Notifications.dismissAllNotifications(context); } } } }
package com.machinezoo.sourceafis; import java.util.*; import gnu.trove.map.hash.*; public class FingerprintMatcher { /* * API roadmap: * + FingerprintMatcher(FingerprintTemplate) * - index(FingerprintTemplate) * + FingerprintMatcher(FingerprintTemplate, FingerprintMatcherOptions) * + compare(FingerprintTemplate) - returns bits of evidence instead of current score * - match(FingerprintTemplate) * + maybe features to support 1:N identification (parallelization, score adjustment, person model, ...) * * FingerprintMatcherOptions: * + matchX(boolean) - enable or disable various parts of the matcher for performance reasons * + cpu(long) - automated feature/algorithm selection to target CPU cycles per candidate * * FingerprintEvidence: * = calculation of effective score in multi-finger or 1:N matching * + add(double) * + add(FingerprintPosition, double) * + add(FingerprintEvidence) * + top(int subset, int population) * + sum() * + thresholdAtFMR(double) - might have variant, still unclear */ private volatile ImmutableMatcher immutable = ImmutableMatcher.empty; /** * Instantiate an empty fingerprint matcher. * Empty matcher does not match any {@link FingerprintTemplate} passed to {@link #match(FingerprintTemplate)}. * You can call {@link #index(FingerprintTemplate)} to index probe fingerprint * and {@link #match(FingerprintTemplate)} to match it to some candidate fingerprint. * * @see #index(FingerprintTemplate) */ public FingerprintMatcher() { } /** * Enable algorithm transparency. * Since {@link FingerprintTransparency} is activated automatically via thread-local variable * in recent versions of SourceAFIS, this method does nothing in current version of SourceAFIS. * It will be removed in some later version. * * @param transparency * target {@link FingerprintTransparency} or {@code null} to disable algorithm transparency * @return {@code this} (fluent method) * * @see FingerprintTransparency */ @Deprecated public FingerprintMatcher transparency(FingerprintTransparency transparency) { return this; } /** * Build search data structures over probe fingerprint template. * Once this method is called, it is possible to call {@link #match(FingerprintTemplate)} to compare fingerprints. * <p> * This method is heavy in terms of RAM footprint and CPU usage. * Initialized {@code FingerprintMatcher} should be reused for multiple {@link #match(FingerprintTemplate)} calls in 1:N matching. * * @param probe * probe fingerprint template to be matched to candidate fingerprints * @return {@code this} (fluent method) * @throws NullPointerException * if {@code probe} is {@code null} * * @see #match(FingerprintTemplate) */ public FingerprintMatcher index(FingerprintTemplate probe) { Objects.requireNonNull(probe); ImmutableTemplate template = probe.immutable; immutable = new ImmutableMatcher(template, buildEdgeHash(template)); return this; } private TIntObjectHashMap<List<IndexedEdge>> buildEdgeHash(ImmutableTemplate template) { TIntObjectHashMap<List<IndexedEdge>> map = new TIntObjectHashMap<>(); for (int reference = 0; reference < template.minutiae.length; ++reference) for (int neighbor = 0; neighbor < template.minutiae.length; ++neighbor) if (reference != neighbor) { IndexedEdge edge = new IndexedEdge(template.minutiae, reference, neighbor); for (int hash : shapeCoverage(edge)) { List<IndexedEdge> list = map.get(hash); if (list == null) map.put(hash, list = new ArrayList<>()); list.add(edge); } } FingerprintTransparency.current().logEdgeHash(map); return map; } private List<Integer> shapeCoverage(EdgeShape edge) { int minLengthBin = (edge.length - Parameters.maxDistanceError) / Parameters.maxDistanceError; int maxLengthBin = (edge.length + Parameters.maxDistanceError) / Parameters.maxDistanceError; int angleBins = (int)Math.ceil(2 * Math.PI / Parameters.maxAngleError); int minReferenceBin = (int)(DoubleAngle.difference(edge.referenceAngle, Parameters.maxAngleError) / Parameters.maxAngleError); int maxReferenceBin = (int)(DoubleAngle.add(edge.referenceAngle, Parameters.maxAngleError) / Parameters.maxAngleError); int endReferenceBin = (maxReferenceBin + 1) % angleBins; int minNeighborBin = (int)(DoubleAngle.difference(edge.neighborAngle, Parameters.maxAngleError) / Parameters.maxAngleError); int maxNeighborBin = (int)(DoubleAngle.add(edge.neighborAngle, Parameters.maxAngleError) / Parameters.maxAngleError); int endNeighborBin = (maxNeighborBin + 1) % angleBins; List<Integer> coverage = new ArrayList<>(); for (int lengthBin = minLengthBin; lengthBin <= maxLengthBin; ++lengthBin) for (int referenceBin = minReferenceBin; referenceBin != endReferenceBin; referenceBin = (referenceBin + 1) % angleBins) for (int neighborBin = minNeighborBin; neighborBin != endNeighborBin; neighborBin = (neighborBin + 1) % angleBins) coverage.add((referenceBin << 24) + (neighborBin << 16) + lengthBin); return coverage; } public double match(FingerprintTemplate candidate) { Objects.requireNonNull(candidate); MatchBuffer buffer = MatchBuffer.current(); buffer.selectMatcher(immutable); buffer.selectCandidate(candidate.immutable); return buffer.match(); } }
package com.zulip.android; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import android.annotation.TargetApi; import android.app.Activity; import android.content.ClipData; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.util.SparseArray; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import com.j256.ormlite.stmt.QueryBuilder; import com.j256.ormlite.stmt.Where; public class MessageListFragment extends Fragment implements MessageListener { public interface Listener { void onListResume(MessageListFragment f); void openCompose(Stream stream, String topic); void openCompose(String pmRecipients); void openCompose(final MessageType type, String stream, String topic, String pmRecipients); void addToList(Message message); void muteTopic(Message message); } private static final String PARAM_FILTER = "filter"; NarrowFilter filter; private Listener mListener; private ListView listView; private View loadIndicatorTop; private View loadIndicatorBottom; private View bottom_list_spacer; public ZulipApp app; SparseArray<Message> messageIndex; MessageAdapter adapter; boolean loadingMessages = true; // Whether we've loaded all available messages in that direction boolean loadedToTop = false; boolean loadedToBottom = false; int firstMessageId = -1; int lastMessageId = -1; boolean paused = false; boolean initialized = false; public static MessageListFragment newInstance(NarrowFilter filter) { MessageListFragment fragment = new MessageListFragment(); Bundle args = new Bundle(); args.putParcelable(PARAM_FILTER, filter); fragment.setArguments(args); return fragment; } public MessageListFragment() { app = ZulipApp.get(); // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { filter = getArguments().getParcelable(PARAM_FILTER); } messageIndex = new SparseArray<Message>(); adapter = new MessageAdapter(getActivity(), new ArrayList<Message>()); } public void onPause() { super.onPause(); paused = true; } public void onResume() { super.onResume(); mListener.onListResume(this); paused = false; } public void onActivityResume() { // Only when the activity resumes, not when the fragment is brought to // the top showLoadIndicatorBottom(true); loadingMessages = true; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_message_list, container, false); listView = (ListView) view.findViewById(R.id.listview); // Load indicator View loadTopParent = inflater.inflate(R.layout.list_loading, null); View loadBottomParent = inflater.inflate(R.layout.list_loading, null); loadIndicatorTop = ((LinearLayout) loadTopParent).getChildAt(0); loadIndicatorBottom = ((LinearLayout) loadBottomParent).getChildAt(0); listView.addHeaderView(loadTopParent, null, false); listView.addFooterView(loadBottomParent, null, false); // Spacer bottom_list_spacer = new ImageView(getActivity()); size_bottom_spacer(); listView.addFooterView(this.bottom_list_spacer); listView.setAdapter(adapter); // We want blue highlights when you longpress listView.setDrawSelectorOnTop(true); registerForContextMenu(listView); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { final int near = 6; if (!paused && !loadingMessages && firstMessageId > 0 && lastMessageId > 0) { if (firstVisibleItem + visibleItemCount > totalItemCount - near) { // At the bottom of the list if (!loadedToBottom) { Log.i("scroll", "Starting request below"); loadMoreMessages(LoadPosition.BELOW); } } if (firstVisibleItem < near) { // At the top of the list if (!loadedToTop) { Log.i("scroll", "Starting request above"); loadMoreMessages(LoadPosition.ABOVE); } } } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { try { // Scrolling messages isn't meaningful unless we have // messages to scroll. Message message = ((Message) view.getItemAtPosition(view .getFirstVisiblePosition())); int mID = message.getID(); if (filter == null && app.getPointer() < mID) { Log.i("scrolling", "Now at " + mID); (new AsyncPointerUpdate(app)).execute(mID); app.setPointer(mID); } app.markMessageAsRead(message); } catch (NullPointerException e) { Log.w("scrolling", "Could not find a location to scroll to!"); } } }); listView.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { try { int mID = (Integer) view.getTag(R.id.messageID); if (app.getPointer() < mID) { Log.i("keyboard", "Now at " + mID); (new AsyncPointerUpdate(app)).execute(mID); app.setPointer(mID); } } catch (NullPointerException e) { Log.e("selected", "None, because we couldn't find the tag."); } } @Override public void onNothingSelected(AdapterView<?> parent) { // pass } }); return view; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (Listener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement Listener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } void showLoadIndicatorBottom(boolean show) { loadIndicatorBottom.setVisibility(show ? View.VISIBLE : View.GONE); } void showLoadIndicatorTop(boolean show) { loadIndicatorTop.setVisibility(show ? View.VISIBLE : View.GONE); } private Message itemFromMenuInfo(ContextMenuInfo menuInfo) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; // Subtract 1 because it counts the header return adapter.getItem(info.position - 1); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); Message msg = itemFromMenuInfo(menuInfo); if (msg == null) { return; } if (msg.getType().equals(MessageType.STREAM_MESSAGE)) { MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.context_stream, menu); } else if (msg.getPersonalReplyTo(app).length > 1) { MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.context_private, menu); } else { MenuInflater inflater = getActivity().getMenuInflater(); inflater.inflate(R.menu.context_single_private, menu); } } @Override public boolean onContextItemSelected(MenuItem item) { Message message = itemFromMenuInfo(item.getMenuInfo()); switch (item.getItemId()) { case R.id.reply_to_stream: mListener.openCompose(message.getStream(), message.getSubject()); return true; case R.id.reply_to_private: mListener.openCompose(message.getReplyTo(app)); return true; case R.id.reply_to_sender: mListener.openCompose(message.getSender().getEmail()); return true; case R.id.narrow_to_private: if (getActivity() instanceof NarrowListener) { ((NarrowListener) getActivity()).onNarrow(new NarrowFilterPM(Arrays.asList(message.getRecipients(app)))); } return true; case R.id.narrow_to_stream: if (getActivity() instanceof NarrowListener) { ((NarrowListener) getActivity()).onNarrow(new NarrowFilterStream(message.getStream(), null)); } return true; case R.id.narrow_to_subject: if (getActivity() instanceof NarrowListener) { ((NarrowListener) getActivity()).onNarrow(new NarrowFilterStream(message.getStream(), message.getSubject())); } return true; case R.id.copy_message: copyMessage(message); return true; default: return super.onContextItemSelected(item); } } public void onReadyToDisplay(boolean registered) { if (initialized && !registered) { // Already have state, and already processed any events that came in // when resuming the existing queue. showLoadIndicatorBottom(false); loadingMessages = false; Log.i("onReadyToDisplay", "just a resume"); return; } adapter.clear(); messageIndex.clear(); firstMessageId = -1; lastMessageId = -1; loadingMessages = true; showLoadIndicatorBottom(true); fetch(); initialized = true; } private void fetch() { final AsyncGetOldMessages oldMessagesReq = new AsyncGetOldMessages(this); oldMessagesReq.execute(app.getPointer(), LoadPosition.INITIAL, 100, 100, filter); } private void selectPointer() { if (filter != null) { Where<Message, Object> filteredWhere; try { filteredWhere = filter.modWhere(app.getDao(Message.class) .queryBuilder().where()); filteredWhere.and().le(Message.ID_FIELD, app.getPointer()); QueryBuilder<Message, Object> closestQuery = app.getDao( Message.class).queryBuilder(); closestQuery.orderBy(Message.TIMESTAMP_FIELD, false).setWhere( filteredWhere); listView.setSelection(adapter.getPosition(closestQuery .queryForFirst())); } catch (SQLException e) { throw new RuntimeException(e); } } else { int anc = app.getPointer(); selectMessage(getMessageById(anc)); } } private void size_bottom_spacer() { @SuppressWarnings("deprecation") // needed for compat with API <13 int windowHeight = ((WindowManager) app .getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay() .getHeight(); AbsListView.LayoutParams params = new AbsListView.LayoutParams(0, 0); params.height = windowHeight / 2; this.bottom_list_spacer.setLayoutParams(params); } @SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void copyMessage(Message msg) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) app .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(ClipData.newPlainText("Zulip Message", msg.getContent())); } else { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) app .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(msg.getContent()); } } public void onNewMessages(Message[] messages) { onMessages(messages, LoadPosition.NEW, false, false, false); } public void onMessages(Message[] messages, LoadPosition pos, boolean moreAbove, boolean moreBelow, boolean noFurtherMessages) { if (!initialized) { return; } Log.i("onMessages", "Adding " + messages.length + " messages at " + pos); // Collect state used to maintain scroll position int topPosBefore = listView.getFirstVisiblePosition(); View topView = listView.getChildAt(0); int topOffsetBefore = (topView != null) ? topView.getTop() : 0; if (topOffsetBefore >= 0 && !moreAbove && !noFurtherMessages) { // If the loading indicator was visible, show a new message in the // space it took up. If it was not visible, avoid jumping. topOffsetBefore -= loadIndicatorTop.getHeight(); } int addedCount = 0; if (pos == LoadPosition.NEW) { if (!loadedToBottom) { // If we don't have intermediate messages loaded, don't add new // messages -- they'll be loaded when we scroll down. Log.i("onMessage", "skipping new message " + messages[0].getID() + " " + app.getMaxMessageId()); return; } } for (int i = 0; i < messages.length; i++) { Message message = messages[i]; if (filter != null && !filter.matches(message)) { continue; } if (this.messageIndex.get(message.getID()) != null) { // Already have this message. Log.i("onMessage", "Already have " + message.getID()); continue; } this.messageIndex.append(message.getID(), message); Stream stream = message.getStream(); if (filter == null && stream != null && !stream.getInHomeView()) { continue; } if (pos == LoadPosition.NEW || pos == LoadPosition.BELOW) { this.adapter.add(message); } else if (pos == LoadPosition.ABOVE || pos == LoadPosition.INITIAL) { // TODO: Does this copy the array every time? this.adapter.insert(message, addedCount); addedCount++; } if (message.getID() > lastMessageId) { lastMessageId = message.getID(); } if (message.getID() < firstMessageId || firstMessageId == -1) { firstMessageId = message.getID(); } } if (pos == LoadPosition.ABOVE) { showLoadIndicatorTop(moreAbove); // Restore the position of the top item this.listView.setSelectionFromTop(topPosBefore + addedCount, topOffsetBefore); if (noFurtherMessages) { loadedToTop = true; } } else if (pos == LoadPosition.BELOW) { showLoadIndicatorBottom(moreBelow); if (noFurtherMessages || listHasMostRecent()) { loadedToBottom = true; } } else if (pos == LoadPosition.INITIAL) { selectPointer(); showLoadIndicatorTop(moreAbove); showLoadIndicatorBottom(moreBelow); if (noFurtherMessages || listHasMostRecent()) { loadedToBottom = true; } } loadingMessages = moreAbove || moreBelow; } public void onMessageError(LoadPosition pos) { loadingMessages = false; // Keep the loading indicator there to indicate that it was not // successful } public void loadMoreMessages(LoadPosition pos) { int above = 0; int below = 0; int around; if (pos == LoadPosition.ABOVE) { above = 100; around = firstMessageId; showLoadIndicatorTop(true); } else if (pos == LoadPosition.BELOW) { below = 100; around = lastMessageId; showLoadIndicatorBottom(true); } else { Log.e("loadMoreMessages", "Invalid position"); return; } Log.i("loadMoreMessages", "" + around + " " + pos + " " + above + " " + below); loadingMessages = true; AsyncGetOldMessages oldMessagesReq = new AsyncGetOldMessages(this); oldMessagesReq.execute(around, pos, above, below, filter); } public Boolean listHasMostRecent() { return lastMessageId == app.getMaxMessageId(); } public void selectMessage(final Message message) { listView.setSelection(adapter.getPosition(message)); } public Message getMessageById(int id) { return this.messageIndex.get(id); } }
package devded.silkyland.cmrurun; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Handler; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import org.json.JSONArray; import org.json.JSONObject; import java.io.IOException; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; private double cmruLatADouble = 18.807093, cmruLngADouble = 98.98641; private double userLatADouble, userLngADouble; private LocationManager locationManager; private Criteria criteria; private String userIDString, userNameString,goldString; private static final String urlEditLocation = "http://swiftcodingthai.com/cmru/edit_location_master.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_layout); //Setup userLatADouble = cmruLatADouble; userLngADouble = cmruLngADouble; locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); //Get Value From Intent userIDString = getIntent().getStringExtra("userID"); userNameString = getIntent().getStringExtra("Name"); goldString = getIntent().getStringExtra("Gold"); Log.d("30JuneV1", "userID ==> " + userIDString); Log.d("30JuneV1", "userName ==> " + userNameString); // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } // Main Method private class SynLocation extends AsyncTask<Void, Void, String> { private static final String urlJON = "http://swiftcodingthai.com/cmru/get_user_master.php"; private MyData myData; @Override protected String doInBackground(Void... voids) { try { OkHttpClient okHttpClient = new OkHttpClient(); Request.Builder builder = new Request.Builder(); Request request = builder.url(urlJON).build(); Response response = okHttpClient.newCall(request).execute(); return response.body().string(); } catch (Exception e) { Log.d("30JuneV1", "e doIn ==> " + e.toString()); return null; } } // doIn @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.d("30JuneV1", "JSON ==> " + s); myData = new MyData(); int[] intIcon = myData.getAvatarInts(); try { JSONArray jsonArray = new JSONArray(s); for (int i=0;i<jsonArray.length();i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String strName = jsonObject.getString("Name"); int iconMaker = intIcon[Integer.parseInt(jsonObject.getString("Avata"))]; double douLat = Double.parseDouble(jsonObject.getString("Lat")); double douLng = Double.parseDouble(jsonObject.getString("Lng")); LatLng latLng = new LatLng(douLat, douLng); mMap.addMarker(new MarkerOptions() .position(latLng) .icon(BitmapDescriptorFactory.fromResource(iconMaker)) .title(strName)); } //for } catch (Exception e) { Log.d("30JuneV1", "e onPost ==> " + e.toString()); } } } // SynLocation Class @Override protected void onResume() { super.onResume(); locationManager.removeUpdates(locationListener); Location networkLocation = myFindLocation(LocationManager.NETWORK_PROVIDER); if (networkLocation != null) { userLatADouble = networkLocation.getLatitude(); userLngADouble = networkLocation.getLongitude(); } Location gpsLocation = myFindLocation(LocationManager.GPS_PROVIDER); if (gpsLocation != null) { userLatADouble = gpsLocation.getLatitude(); userLngADouble = gpsLocation.getLongitude(); } Log.d("29JuneV1", "userLat ==> " + userLatADouble); Log.d("29JuneV1", "userLat ==> " + userLngADouble); } //onResume @Override protected void onStop() { super.onStop(); locationManager.removeUpdates(locationListener); } public Location myFindLocation(String strProvider) { Location location = null; if (locationManager.isProviderEnabled(strProvider)) { locationManager.requestLocationUpdates(strProvider, 1000, 10, locationListener); location = locationManager.getLastKnownLocation(strProvider); } else { Log.d("29JuneV1", "Cannot Find Location"); } return location; } public LocationListener locationListener = new LocationListener() { @Override public void onLocationChanged(Location location) { userLatADouble = location.getLatitude(); userLngADouble = location.getLongitude(); } //onLocationChang @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } }; @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; //Setup to CMRU LatLng latLng = new LatLng(cmruLatADouble, cmruLngADouble); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16)); createStationMaker(); myLoop(); } // onMapReady private void myLoop() { Log.d("29JuneV1","userLat ==> " + userLatADouble); Log.d("29JuneV1","userLng ==> " + userLngADouble); mMap.clear(); createStationMaker(); editLocation(); checkDistance(); SynLocation synLocation = new SynLocation(); synLocation.execute(); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { myLoop(); } }, 3000); } private void checkDistance() { MyData myData = new MyData(); double[] latStationDoubles = myData.getLatStationDoubles(); double[] lngStationDoubles = myData.getLngStationDoubles(); double douMyDistance = Math.sin(deg2rad(userLatADouble)) * Math.sin(deg2rad(latStationDoubles[Integer.parseInt(goldString)])) + Math.cos(deg2rad(userLatADouble)) * Math.cos(deg2rad(latStationDoubles[Integer.parseInt(goldString)])) * Math.cos(deg2rad((userLngADouble - lngStationDoubles[Integer.parseInt(goldString)]))); douMyDistance = Math.acos(douMyDistance); douMyDistance = rad2deg(douMyDistance); douMyDistance = douMyDistance * 60 * 1.15115 * 1.609344 * 1000; Log.d("30juneV2", "myDistance เทียบกับ ฐานที่ " + goldString + "มีค่าเท่ากับ " + douMyDistance); } // checkDistance private double rad2deg(double douMyDistance) { double result = 0; result = douMyDistance * 180 / Math.PI; return result; } private double deg2rad(double userLatADouble) { double result = 0; result = userLatADouble * Math.PI / 180; return result; } private void editLocation() { OkHttpClient okHttpClient = new OkHttpClient(); RequestBody requestBody = new FormEncodingBuilder() .add("isAdd", "true") .add("id", userIDString) .add("Lat", Double.toString(userLatADouble)) .add("Lng", Double.toString(userLngADouble)) .build(); Request.Builder builder = new Request.Builder(); Request request = builder.url(urlEditLocation).post(requestBody).build(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { } }); } // editLocation private void createStationMaker() { MyData myData = new MyData(); double[] latDoubles = myData.getLatStationDoubles(); double[] lngDoubles = myData.getLngStationDoubles(); int[] iconInts = myData.getIconStationInts(); for (int i=0;i<latDoubles.length;i++) { LatLng latLng = new LatLng(latDoubles[i], lngDoubles[i]); mMap.addMarker(new MarkerOptions().position(latLng) .icon(BitmapDescriptorFactory.fromResource(iconInts[i])) .title("ด่าน " + Integer.toString(i+1))); } } // create StationMaker } // Main Class
// Burp Suite Logger++ // Developed by Soroush Dalili (@irsdl) package com.nccgroup.loggerplusplus.about; import com.coreyd97.BurpExtenderUtilities.Alignment; import com.coreyd97.BurpExtenderUtilities.PanelBuilder; import com.coreyd97.BurpExtenderUtilities.Preferences; import com.nccgroup.loggerplusplus.util.Globals; import com.nccgroup.loggerplusplus.util.userinterface.NoTextSelectionCaret; import com.nccgroup.loggerplusplus.util.userinterface.WrappedTextPane; import javax.swing.*; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; public class AboutPanel extends JPanel { private final Preferences preferences; private JComponent panel; public AboutPanel(Preferences preferences){ this.setLayout(new BorderLayout()); this.preferences = preferences; this.panel = buildMainPanel(); this.add(panel, BorderLayout.NORTH); this.setMinimumSize(panel.getSize()); this.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON2){ AboutPanel.this.removeAll(); panel = buildMainPanel(); AboutPanel.this.add(panel, BorderLayout.NORTH); AboutPanel.this.setMinimumSize(panel.getSize()); AboutPanel.this.revalidate(); AboutPanel.this.repaint(); } } }); } private JComponent buildMainPanel(){ JLabel headerLabel = new JLabel("Logger++"); Font font = this.getFont().deriveFont(32f).deriveFont(this.getFont().getStyle() | Font.BOLD); headerLabel.setFont(font); headerLabel.setHorizontalAlignment(SwingConstants.CENTER); JLabel subtitle = new JLabel("Advanced multithreaded logging tool"); Font subtitleFont = subtitle.getFont().deriveFont(16f).deriveFont(subtitle.getFont().getStyle() | Font.ITALIC); subtitle.setFont(subtitleFont); subtitle.setHorizontalAlignment(SwingConstants.CENTER); JSeparator separator = new JSeparator(SwingConstants.HORIZONTAL); JPanel separatorPadding = new JPanel(); separatorPadding.setBorder(BorderFactory.createEmptyBorder(0,0,7,0)); BufferedImage twitterImage = loadImage("TwitterLogo.png"); JButton twitterButton; if(twitterImage != null){ twitterButton = new JButton("Follow me (@CoreyD97) on Twitter", new ImageIcon(scaleImageToWidth(twitterImage, 20))); twitterButton.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); twitterButton.setIconTextGap(7); }else{ twitterButton = new JButton("Follow me (@CoreyD97) on Twitter"); } twitterButton.setMaximumSize(new Dimension(0, 10)); twitterButton.addActionListener(actionEvent -> { try { Desktop.getDesktop().browse(new URI(Globals.TWITTER_URL)); } catch (IOException | URISyntaxException e) {} }); JButton irsdlTwitterButton; if(twitterImage != null){ irsdlTwitterButton = new JButton("Follow Soroush (@irsdl) on Twitter", new ImageIcon(scaleImageToWidth(twitterImage, 20))); irsdlTwitterButton.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); irsdlTwitterButton.setIconTextGap(7); }else{ irsdlTwitterButton = new JButton("Follow Soroush (@irsdl) on Twitter"); } irsdlTwitterButton.setMaximumSize(new Dimension(0, 10)); irsdlTwitterButton.addActionListener(actionEvent -> { try { Desktop.getDesktop().browse(new URI(Globals.IRSDL_TWITTER_URL)); } catch (IOException | URISyntaxException e) {} }); JButton nccTwitterButton; BufferedImage nccImage = loadImage("NCCGroup.png"); if(nccImage != null){ nccTwitterButton = new JButton("Follow NCC Group on Twitter", new ImageIcon(scaleImageToWidth(nccImage, 20))); nccTwitterButton.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); nccTwitterButton.setIconTextGap(7); }else{ nccTwitterButton = new JButton("Follow NCC Group on Twitter"); } nccTwitterButton.addActionListener(actionEvent -> { try { Desktop.getDesktop().browse(new URI(Globals.NCC_TWITTER_URL)); } catch (IOException | URISyntaxException e) {} }); String githubLogoFilename = "GitHubLogo" + (UIManager.getLookAndFeel().getName().equalsIgnoreCase("darcula") ? "White" : "Black") + ".png"; BufferedImage githubImage = loadImage(githubLogoFilename); // JButton viewOnGithubButton; JButton submitFeatureRequestButton; JButton reportBugButton; if(githubImage != null){ // viewOnGithubButton = new JButton("View Project on GitHub", new ImageIcon(scaleImageToWidth(githubImage, 20))); // viewOnGithubButton.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); // viewOnGithubButton.setIconTextGap(7); submitFeatureRequestButton = new JButton("Submit Feature Request", new ImageIcon(scaleImageToWidth(githubImage, 20))); submitFeatureRequestButton.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); submitFeatureRequestButton.setIconTextGap(7); reportBugButton = new JButton("Report an Issue", new ImageIcon(scaleImageToWidth(githubImage, 20))); reportBugButton.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); reportBugButton.setIconTextGap(7); }else{ // viewOnGithubButton = new JButton("View Project on GitHub"); submitFeatureRequestButton = new JButton("Submit Feature Request", new ImageIcon(scaleImageToWidth(githubImage, 20))); reportBugButton = new JButton("Report an Issue", new ImageIcon(scaleImageToWidth(githubImage, 20))); } // viewOnGithubButton.addActionListener(actionEvent -> { // try { // Desktop.getDesktop().browse(new URI(Globals.GITHUB_URL)); // } catch (IOException | URISyntaxException e) {} submitFeatureRequestButton.addActionListener(actionEvent -> { try { Desktop.getDesktop().browse(new URI(Globals.GITHUB_FEATURE_URL)); } catch (IOException | URISyntaxException e) {} }); reportBugButton.addActionListener(actionEvent -> { try { Desktop.getDesktop().browse(new URI(Globals.GITHUB_BUG_URL)); } catch (IOException | URISyntaxException e) {} }); BufferedImage nccLargeImage = loadImage("NCCLarge.png"); ImageIcon nccLargeImageIcon = new ImageIcon(scaleImageToWidth(nccLargeImage, 300)); JLabel nccBranding = new JLabel(nccLargeImageIcon); nccBranding.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { int width = e.getComponent().getWidth(); nccLargeImageIcon.setImage(scaleImageToWidth(nccLargeImage, width)); } }); JLabel createdBy = new JLabel("Developed by: Corey Arthur ( @CoreyD97 )"); createdBy.setHorizontalAlignment(SwingConstants.CENTER); createdBy.setBorder(BorderFactory.createEmptyBorder(0,0,7,0)); JLabel ideaBy = new JLabel("Originally by: Soroush Dalili ( @irsdl )"); ideaBy.setHorizontalAlignment(SwingConstants.CENTER); ideaBy.setBorder(BorderFactory.createEmptyBorder(0,0,7,0)); JLabel version = new JLabel("Version: " + Globals.VERSION); version.setBorder(BorderFactory.createEmptyBorder(0,0,7,0)); version.setHorizontalAlignment(SwingConstants.CENTER); JComponent creditsPanel = PanelBuilder.build(new JComponent[][]{ new JComponent[]{createdBy}, new JComponent[]{ideaBy}, new JComponent[]{version}, new JComponent[]{nccBranding}, new JComponent[]{nccBranding} }, Alignment.FILL, 1, 1); WrappedTextPane aboutContent = new WrappedTextPane(); aboutContent.setLayout(new BorderLayout()); aboutContent.setEditable(false); aboutContent.setOpaque(false); aboutContent.setCaret(new NoTextSelectionCaret(aboutContent)); JScrollPane aboutScrollPane = new JScrollPane(aboutContent); aboutScrollPane.setBorder(null); aboutScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); Style bold = aboutContent.getStyledDocument().addStyle("bold", null); StyleConstants.setBold(bold, true); Style italics = aboutContent.getStyledDocument().addStyle("italics", null); StyleConstants.setItalic(italics, true); try { String featuresTitle = "Features\n\n"; String features = " \u2022 Log requests from all tools\n" + " \u2022 Define filters to search requests\n" + " \u2022 Create rules to highlight interesting requests\n" + " \u2022 Grep all entries for regex patterns and extract matching groups\n" + " \u2022 Import entries from WStalker, OWASP ZAP\n" + " \u2022 Export entries to elasticsearch, CSV\n" + " \u2022 Multithreaded\n\n" + "Want a feature implementing? Make a request using the buttons above!\n" + "Want to help improve Logger++? Submit a pull request!\n\n" + "Like the extension? Let me know by giving it a star on GitHub.\n\n"; String thanksTo = "Thanks To:\n"; String thanksText = "Shaddy, ours-code, jselvi, jaesbit, wotgl, StanHVA, theblackturtle, cnotin, latacora-tomekr, JulianVolodia"; String[] sections = new String[]{featuresTitle, features, thanksTo, thanksText}; Style[] styles = new Style[]{bold, null, null, italics}; StyledDocument document = aboutContent.getStyledDocument(); for (int i = 0; i < sections.length; i++) { String section = sections[i]; document.insertString(document.getLength(), String.valueOf(section), styles[i]); } } catch (Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); } aboutContent.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); JScrollPane aboutContentScrollPane = new JScrollPane(aboutContent); aboutContentScrollPane.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); JPanel panel = PanelBuilder.build(new JComponent[][]{ new JComponent[]{headerLabel, headerLabel}, new JComponent[]{subtitle, subtitle}, new JComponent[]{separator, separator}, new JComponent[]{separatorPadding, separatorPadding}, new JComponent[]{creditsPanel, twitterButton}, new JComponent[]{creditsPanel, irsdlTwitterButton}, new JComponent[]{creditsPanel, nccTwitterButton}, new JComponent[]{creditsPanel, submitFeatureRequestButton}, new JComponent[]{creditsPanel, reportBugButton}, new JComponent[]{aboutContentScrollPane, aboutContentScrollPane}, }, new int[][]{ new int[]{1,1}, new int[]{1,1}, new int[]{1,1}, new int[]{1,1}, new int[]{1,1}, new int[]{1,1}, new int[]{1,1}, new int[]{1,1}, new int[]{0,0}, }, Alignment.TOPMIDDLE, 0.5, 0.9); return panel; } private BufferedImage loadImage(String filename){ ClassLoader cldr = this.getClass().getClassLoader(); URL imageURLMain = cldr.getResource(filename); if(imageURLMain != null) { Image original = new ImageIcon(imageURLMain).getImage(); ImageIcon originalIcon = new ImageIcon(original); BufferedImage bufferedImage = new BufferedImage(originalIcon.getIconWidth(), originalIcon.getIconHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.drawImage(originalIcon.getImage(), null, null); return bufferedImage; } return null; } private Image scaleImageToWidth(BufferedImage image, int width){ int height = (int) (Math.floor((image.getHeight() * width) / (double) image.getWidth())); return image.getScaledInstance(width, height, Image.SCALE_SMOOTH); } }
package fi.bitrite.android.ws.ui; import android.accounts.Account; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.SparseArray; import android.view.Gravity; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.inject.Inject; import butterknife.BindView; import butterknife.ButterKnife; import dagger.android.AndroidInjection; import dagger.android.DispatchingAndroidInjector; import dagger.android.support.HasSupportFragmentInjector; import fi.bitrite.android.ws.R; import fi.bitrite.android.ws.api.AuthenticationController; import fi.bitrite.android.ws.auth.AccountManager; import fi.bitrite.android.ws.di.account.AccountComponent; import fi.bitrite.android.ws.di.account.AccountComponentManager; import fi.bitrite.android.ws.model.SimpleUser; import fi.bitrite.android.ws.repository.MessageRepository; import fi.bitrite.android.ws.repository.Resource; import fi.bitrite.android.ws.ui.listadapter.NavigationListAdapter; import fi.bitrite.android.ws.ui.model.NavigationItem; import fi.bitrite.android.ws.ui.util.ActionBarTitleHelper; import fi.bitrite.android.ws.ui.util.NavigationController; import fi.bitrite.android.ws.util.LoggedInUserHelper; import fi.bitrite.android.ws.util.SerialCompositeDisposable; import io.reactivex.Maybe; import io.reactivex.MaybeObserver; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; // AppScope public class MainActivity extends AppCompatActivity implements HasSupportFragmentInjector { private static final String KEY_MESSAGE_THREAD_ID = "thread_id"; private final NavigationItem mMessageNavigationItem = new NavigationItem( NavigationController.NAVIGATION_TAG_MESSAGE_THREADS, R.drawable.ic_message_grey600_24dp, R.string.navigation_item_messages); private final List<NavigationItem> mPrimaryNavigationItems = Arrays.asList( // Map new NavigationItem(NavigationController.NAVIGATION_TAG_MAP, R.drawable.ic_map_grey600_24dp, R.string.navigation_item_map), // Starred users new NavigationItem(NavigationController.NAVIGATION_TAG_FAVORITE_USERS, R.drawable.ic_favorite_grey600_24dp, R.string.navigation_item_favorites), // Messages mMessageNavigationItem ); private final List<NavigationItem> mSecondaryNavigationItems = Arrays.asList( // Settings new NavigationItem(NavigationController.NAVIGATION_TAG_SETTINGS, R.drawable.ic_settings_grey600_24dp, R.string.navigation_item_settings), // About new NavigationItem(NavigationController.NAVIGATION_TAG_ABOUT, R.drawable.ic_info_grey600_24dp, R.string.navigation_item_about) ); @Inject ActionBarTitleHelper mActionBarTitleHelper; @Inject AccountComponentManager mAccountComponentManager; @Inject AccountManager mAccountManager; @BindView(R.id.main_layout_drawer) DrawerLayout mMainLayout; @BindView(R.id.main_toolbar) Toolbar mToolbar; @BindView(R.id.nav_img_user_photo) ImageView mImgUserPhoto; @BindView(R.id.nav_lbl_fullname) TextView mLblFullname; @BindView(R.id.nav_lbl_username) TextView mLblUsername; @BindView(R.id.nav_lst_primary_navigation) ListView mPrimaryNavigationList; @BindView(R.id.nav_lst_secondary_navigation) ListView mSecondaryNavigationList; private ActionBarDrawerToggle mDrawerToggle; private NavigationController mNavigationController; private final SerialCompositeDisposable mCreateDestroyDisposables = new SerialCompositeDisposable(); private final SerialCompositeDisposable mResumePauseDisposables = new SerialCompositeDisposable(); /** * Creates an intent that sends, when used, the user to that message thread. This is needed for * notifications. */ public static Intent createForMessageThread(Context context, int threadId) { Intent intent = new Intent(context, MainActivity.class); intent.putExtra(KEY_MESSAGE_THREAD_ID, threadId); return intent; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { mCreateDestroyDisposables.reset(); // super.onCreate() re-constructs the previous state - i.e. might start a fragment. We need // an account to be able to show any fragments. AndroidInjection.inject(this); mAccountHelper.switchAccount(mAccountManager.getCurrentAccount().getValue().data); // If there is no account it could be that the app was put to the background and eventually // got destroyed. Then the user removed their Warmshowers account on the device. When they // restart the app there is a savedInstanceState. However, the account is no longer around. // Therefore, start without any saved instance state when having no account around. super.onCreate(mAccountHelper.hasAccount() ? savedInstanceState : null); setContentView(R.layout.activity_main); ButterKnife.bind(this); mNavigationController = new NavigationController(getSupportFragmentManager()); setSupportActionBar(mToolbar); // We need to decorate the home button (burger) as up. This is only needed because in the // ActionBarDrawerToggle constructor that icon (the back arrow) is remembered as the one // that is shown when we disable the drawer indicator (we do this when the home button // should act as us and clicking it should not open the drawer menu). Afterwards, the home // button is decorated as a burger again. getSupportActionBar().setDisplayHomeAsUpEnabled(true); mDrawerToggle = new ActionBarDrawerToggle(this, mMainLayout, mToolbar, R.string.drawer_open, R.string.drawer_close); // The drawer toggle breaks the click listener on the home button (when it is displayed as // up). We fix that. mDrawerToggle.setToolbarNavigationClickListener(view -> onSupportNavigateUp()); mDrawerToggle.getDrawerArrowDrawable() .setColor(getResources().getColor(android.R.color.white)); mDrawerToggle.setDrawerSlideAnimationEnabled(false); mMainLayout.addDrawerListener(mDrawerToggle); // Sets up the navigation. It is divided in different groups which are shown below // each other. // Primary navigation. NavigationListAdapter primaryNavigationListAdapter = NavigationListAdapter.create( this, mPrimaryNavigationItems, mNavigationController.getTopLevelNavigationItemTag()); mCreateDestroyDisposables.add(primaryNavigationListAdapter.getOnClickSubject() .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onNavigationItemClicked)); mPrimaryNavigationList.setAdapter(primaryNavigationListAdapter); // Secondary navigation. NavigationListAdapter secondaryNavigationListAdapter = NavigationListAdapter.create( this, mSecondaryNavigationItems, mNavigationController.getTopLevelNavigationItemTag()); mCreateDestroyDisposables.add(secondaryNavigationListAdapter.getOnClickSubject() .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::onNavigationItemClicked)); mSecondaryNavigationList.setAdapter(secondaryNavigationListAdapter); // Listen for changes in the back stack getSupportFragmentManager().addOnBackStackChangedListener(this::onFragmentBackStackChanged); onFragmentBackStackChanged(); // First we show the main fragment to have something on the backstack. moveToMainFragmentIfNeeded(); handleActionIntents(getIntent()); } @Override public void onResume() { super.onResume(); mResumePauseDisposables.reset(); mAccountManager.setMainActivity(this); mAccountHelper.resume(); // Listens for ActionBar title changes. mResumePauseDisposables.add(mActionBarTitleHelper.get() .observeOn(AndroidSchedulers.mainThread()) .subscribe(mToolbar::setTitle)); // Listens for logged-in user changes. Modifying the backstack is only allowed when the // activity is around. mResumePauseDisposables.add(mAccountManager.getCurrentAccount() .subscribe(nullableAccount -> { Account previousAccount = mAccountHelper.mAccount; mAccountHelper.switchAccount(nullableAccount.data); if (nullableAccount.isNull() || previousAccount != null && !previousAccount.equals(nullableAccount.data)) { // We are doing an actual account switch. Clear the backstack. mNavigationController.clearBackStack(); } moveToMainFragmentIfNeeded(); })); } @Override public void onPause() { mResumePauseDisposables.dispose(); mAccountManager.setMainActivity(null); mAccountHelper.pause(); super.onPause(); } @Override public void onDestroy() { mCreateDestroyDisposables.dispose(); super.onDestroy(); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); handleActionIntents(intent); } private void handleActionIntents(Intent intent) { if (mAccountHelper.hasAccount()) { // We need an account to be able to show any fragments. handleSearchIntent(intent); handleMessageThreadIntent(intent); } } private void handleSearchIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); mNavigationController.navigateToSearch(query); } } private void handleMessageThreadIntent(Intent intent) { int threadId = intent.getIntExtra(KEY_MESSAGE_THREAD_ID, -1); if (threadId != -1) { // TODO(saemy): Ensure back action is to message threads. mNavigationController.navigateToMessageThread(threadId); } } private void moveToMainFragmentIfNeeded() { if (mAccountHelper.hasAccount() && mNavigationController.isBackstackEmpty()) { // There is a new account we switch to -> show the main fragment. mNavigationController.navigateToMainFragment(); } } @Override public DispatchingAndroidInjector<Fragment> supportFragmentInjector() { return mAccountHelper.mDispatchingAndroidInjector; } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } private void onFragmentBackStackChanged() { boolean showHomeAsUp = mNavigationController.isShowHomeAsUp(); // We disable the drawer indicator if we want to show the up action. This decorates the home // button as a back arrow and clicking it won't show the drawer menu anymore. mDrawerToggle.setDrawerIndicatorEnabled(!showHomeAsUp); } @Override public void onBackPressed() { if (mMainLayout.isDrawerOpen(Gravity.START)) { mMainLayout.closeDrawers(); return; } super.onBackPressed(); } @Override public boolean onSupportNavigateUp() { // This method is called when the up button in the toolbar is pressed. We pop the back stack. if (super.onSupportNavigateUp()) { return true; } // FIXME(saemy): This should move one level up in the tag-uri of the navigation controller. getSupportFragmentManager().popBackStack(); return true; } private void onNavigationItemClicked(NavigationItem navigationItem) { final String itemTag = navigationItem.tag; // Closes the drawer. mMainLayout.closeDrawers(); // No action if this is the current fragment. if (itemTag.equals(mNavigationController.getTopLevelNavigationItemTag().getValue())) { return; } // Shows the fragment. mNavigationController.navigateToTag(itemTag); } @NonNull public NavigationController getNavigationController() { return mNavigationController; } private int mNextRequestCode = 0; private final SparseArray<MaybeObserver<? super Intent>> mActivityResultReactors = new SparseArray<>(); public Maybe<Intent> startActivityForResultRx(Intent intent) { return new Maybe<Intent>() { @Override protected void subscribeActual(MaybeObserver<? super Intent> observer) { int requestCode = mNextRequestCode++; mActivityResultReactors.append(requestCode, observer); MainActivity.super.startActivityForResult(intent, requestCode); } }; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { MaybeObserver<? super Intent> observer = mActivityResultReactors.get(requestCode); if (observer != null) { mActivityResultReactors.remove(requestCode); if (data != null) { observer.onSuccess(data); } else { observer.onComplete(); } } else { super.onActivityResult(requestCode, resultCode, data); } } /** * This class can inject itself into an accountComponent. This is the bridge to get access to * the account scope from the appScoped {@link MainActivity}. */ private final AccountHelper mAccountHelper = new AccountHelper(); public class AccountHelper { @Inject Account mAccount; @Inject AuthenticationController mAuthenticationController; @Inject DispatchingAndroidInjector<Fragment> mDispatchingAndroidInjector; @Inject LoggedInUserHelper mLoggedInUserHelper; @Inject MessageRepository mMessageRepository; private boolean mIsPaused = true; private CompositeDisposable mDisposables; void switchAccount(Account account) { if (mAccount == account) { return; } // Pause the old. doPause(); mAccount = account; // Initialize the new. if (hasAccount()) { AccountComponent accountComponent = mAccountComponentManager.get(mAccount); accountComponent.inject(this); } // Resume the new. doResume(); } boolean hasAccount() { return mAccount != null; } void resume() { mIsPaused = false; doResume(); } private void doResume() { if (!mIsPaused && hasAccount()) { mDisposables = new CompositeDisposable(); mDisposables.add(handleLoggedInUser()); mDisposables.add(handleNewMessageThreadCount()); } } void pause() { mIsPaused = true; doPause(); } private void doPause() { if (mDisposables != null) { mDisposables.dispose(); } } /** * Updates the profile picture and account details of the logged in user in the navigation. */ private Disposable handleLoggedInUser() { return mLoggedInUserHelper.getRx() .observeOn(AndroidSchedulers.mainThread()) .subscribe(maybeUser -> { if (maybeUser.isNonNull()) { SimpleUser loggedInUser = maybeUser.data; mLblFullname.setText(loggedInUser.fullname); mLblUsername.setText(loggedInUser.name); String profilePhotoUrl = loggedInUser.profilePicture.getSmallUrl(); if (TextUtils.isEmpty(profilePhotoUrl)) { mImgUserPhoto.setImageResource( R.drawable.default_userinfo_profile); } else { Picasso.with(MainActivity.this) .load(profilePhotoUrl) .into(mImgUserPhoto); // largeUrl } } else { // TODO(saemy): Error handling... } }); } /** * Registers itself for message thread updates and keeps the notification count on the * message navigation item up to date. */ private Disposable handleNewMessageThreadCount() { class Container { // We need a final object. Disposable disposable; } Container container = new Container(); Set<Integer> newThreads = new HashSet<>(); return mMessageRepository .getAll() .subscribe(messageThreadObservables -> { if (container.disposable != null) { container.disposable.dispose(); } container.disposable = Observable.mergeDelayError(messageThreadObservables) .observeOn(Schedulers.computation()) .filter(Resource::hasData) .map(resource -> resource.data) // The next filter returns true if the new-status changed. .filter(thread -> thread.hasNewMessages() ? newThreads.add(thread.id) : newThreads.remove(thread.id)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(thread -> mMessageNavigationItem.notificationCount.onNext( newThreads.size())); }); } } }
package jp.pycon.pyconjp2016app.Util; import android.support.annotation.NonNull; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.concurrent.TimeUnit; public class DateUtil { private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; private static final String TIME_FORMAT = "HH:mm"; private static final String DISPLAY_DATE_FORMAT = "yyyy/MM/dd HH:mm"; private static final String DUMMY_DATE = "2016-09-21"; /** * 13:00 * @param time 13:00:00 * @return 13:00 */ @NonNull public static String toTimeFormattedString(String time) { java.text.DateFormat df1 = new SimpleDateFormat(DATE_FORMAT, Locale.US); java.text.DateFormat df2 = new SimpleDateFormat(TIME_FORMAT, Locale.US); try { Date date = df1.parse(DUMMY_DATE + " " + time); return df2.format(date); } catch (ParseException e) { // nop } return ""; } /** * 2016/09/21 13:00 - 13:30 * @param day 2016-09-21 * @param start 13:00:00 * @param end 13:30:00 * @return 2016/09/21 13:00 - 13:30 */ public static String toStartToEndFormattedString(String day, String start, String end) { java.text.DateFormat df1 = new SimpleDateFormat(DATE_FORMAT, Locale.US); java.text.DateFormat df2 = new SimpleDateFormat(DISPLAY_DATE_FORMAT, Locale.US); java.text.DateFormat df3 = new SimpleDateFormat(TIME_FORMAT, Locale.US); try { Date startDate = df1.parse(day + " " + start); Date endDate = df1.parse(day + " " + end); String startStr = df2.format(startDate); String endStr = df3.format(endDate); return startStr + " - " + endStr; } catch (ParseException e) { // nop } return ""; } /** * * @param day * @param start * @param duration * @return */ public static long toNotificationMills(String day, String start, int duration) { Date date = null; SimpleDateFormat df = new SimpleDateFormat(DATE_FORMAT, Locale.JAPAN); try { date = df.parse(day + " " + start); } catch (ParseException e) { //nop } if (date != null) { return date.getTime() - TimeUnit.MINUTES.toMillis(duration); } return 0; } }
package com.redhat.ceylon.compiler.loader; import java.util.Map; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.compiler.typechecker.model.Module; public class JsonModule extends Module { private Map<String,Object> model; private final JsModuleManager modman; JsonModule(JsModuleManager manager) { modman = manager; } @SuppressWarnings("unchecked") public void setModel(Map<String, Object> value) { if (model != null) { throw new IllegalStateException("JsonModule should only receive model once"); } model = value; for (Map.Entry<String, Object> e : model.entrySet()) { String k = e.getKey(); if (!k.startsWith("$mod-")) { com.redhat.ceylon.compiler.typechecker.model.Package pkg = getDirectPackage(k); if (pkg == null) { pkg = modman.createPackage(k, this); } if (pkg instanceof JsonPackage && ((JsonPackage)pkg).getModel() == null) { ((JsonPackage) pkg).setModel((Map<String,Object>)e.getValue()); } } } } public Map<String, Object> getModel() { return model; } void loadDeclarations() { if (model != null) { for (com.redhat.ceylon.compiler.typechecker.model.Package pkg : getPackages()) { if (pkg instanceof JsonPackage) { ((JsonPackage) pkg).loadDeclarations(); } } } } @SuppressWarnings("unchecked") public Map<String,Object> getModelForPackage(String name) { return model == null ? null : (Map<String,Object>)model.get(name); } @Override public com.redhat.ceylon.compiler.typechecker.model.Package getPackage(String name) { final com.redhat.ceylon.compiler.typechecker.model.Package p = super.getPackage(name); if (p == null) { throw new CompilerErrorException("Package " + name + " not available"); } return p; } }
package com.seleniumtests.controller; import java.util.Collection; import java.util.List; import org.testng.Assert; import org.testng.Reporter; /** * soft assert - test case continues when validation fails. * soft assert is enabled only if context softAssertEnabled is set to true. */ public class CustomAssertion { private static void addVerificationFailure(Throwable e) { SeleniumTestsContextManager.getThreadContext().addVerificationFailures(Reporter.getCurrentTestResult(), e); Logging.log(null, "Assertion Failure: " + e.getMessage(), true, true); } // CustomAssertion Methods public static void assertEquals(boolean actual, boolean expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(byte actual, byte expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(byte[] actual, byte[] expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(char actual, char expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(Collection actual, Collection expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(double actual, double expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(float actual, float expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(int actual, int expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(long actual, long expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(Object actual, Object expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(Object[] actual, Object[] expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(short actual, short expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertEquals(String actual, String expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertEquals(actual, expected, message); } else { Assert.assertEquals(actual, expected, message); } } public static void assertFalse(boolean condition, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertFalse(condition, message); } else { Assert.assertFalse(condition, message); } } public static void assertNotNull(Object object, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertNotNull(object, message); } else { Assert.assertNotNull(object, message); } } public static void assertNotSame(Object actual, Object expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertNotSame(actual, expected, message); } else { Assert.assertNotSame(actual, expected, message); } } public static void assertNull(Object object, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertNull(object, message); } else { Assert.assertNull(object, message); } } public static void assertSame(Object actual, Object expected, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertSame(actual, expected, message); } else { Assert.assertSame(actual, expected, message); } } public static void assertTrue(boolean condition, String message) { if (SeleniumTestsContextManager.getThreadContext().isSoftAssertEnabled()) { softAssertTrue(condition, message); } else { Assert.assertTrue(condition, message); } } public static void fail(String message) { Assert.fail(message); } public static List<Throwable> getVerificationFailures() { return SeleniumTestsContextManager.getThreadContext().getVerificationFailures(Reporter.getCurrentTestResult()); } // Soft CustomAssertion Methods public static void softAssertEquals(boolean actual, boolean expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(byte actual, byte expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(byte[] actual, byte[] expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(char actual, char expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(Collection actual, Collection expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(double actual, double expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(float actual, float expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(int actual, int expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(long actual, long expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(Object actual, Object expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(Object[] actual, Object[] expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(short actual, short expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertEquals(String actual, String expected, String message) { try { Assert.assertEquals(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertFalse(boolean condition, String message) { try { Assert.assertFalse(condition, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertNotNull(Object object, String message) { try { Assert.assertNotNull(object, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertNotSame(Object actual, Object expected, String message) { try { Assert.assertNotSame(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertNull(Object object, String message) { try { Assert.assertNull(object, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertSame(Object actual, Object expected, String message) { try { Assert.assertSame(actual, expected, message); } catch (Throwable e) { addVerificationFailure(e); } } public static void softAssertTrue(boolean condition, String message) { try { Assert.assertTrue(condition, message); } catch (Throwable e) { addVerificationFailure(e); } } }
package me.hanthong.capstone.sync; import android.accounts.Account; import android.app.Notification; import android.app.PendingIntent; import android.content.AbstractThreadedSyncAdapter; import android.content.ContentProviderClient; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SyncResult; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.util.Log; import com.einmalfel.earl.EarlParser; import com.einmalfel.earl.Feed; import com.einmalfel.earl.RSSEnclosure; import com.einmalfel.earl.RSSFeed; import com.einmalfel.earl.RSSItem; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import java.util.zip.DataFormatException; import me.hanthong.capstone.DetailActivity; import me.hanthong.capstone.R; import me.hanthong.capstone.data.NewsColumns; import me.hanthong.capstone.data.NewsProvider; /** * Handle the transfer of data between a server and an * app, using the Android sync adapter framework. */ public class SyncAdapter extends AbstractThreadedSyncAdapter { final static String LOG_TAG = "SyncAdapter"; // Global variables // Define a variable to contain a content resolver instance ContentResolver mContentResolver; String mNewsID; /** * Set up the sync adapter */ public SyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); /* * If your app uses a content resolver, get an instance of it * from the incoming Context */ mContentResolver = context.getContentResolver(); } /** * Set up the sync adapter. This form of the * constructor maintains compatibility with Android 3.0 * and later platform versions */ public SyncAdapter( Context context, boolean autoInitialize, boolean allowParallelSyncs) { super(context, autoInitialize, allowParallelSyncs); /* * If your app uses a content resolver, get an instance of it * from the incoming Context */ mContentResolver = context.getContentResolver(); } /* * Specify the code you want to run in the sync adapter. The entire * sync adapter runs in a background thread, so you don't have to set * up your own background processing. */ @Override public void onPerformSync( Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) { /* * Put the data transfer code here. */ Log.d(LOG_TAG, "syncWork"); // Instantiate the RequestQueue. String url = "http://englishnews.thaipbs.or.th/feed/"; try { InputStream inputStream = new URL(url).openConnection().getInputStream(); Feed feed = EarlParser.parseOrThrow(inputStream, 0); Log.i("Feed", "Processing feed: " + feed.getTitle()); ArrayList<ContentValues> cvArray = new ArrayList<>(); if (RSSFeed.class.isInstance(feed)) { RSSFeed rssFeed = (RSSFeed) feed; for (RSSItem item : rssFeed.items) { String title = item.getTitle(); //Log.i("Feed", "Item title: " + (title == null ? "N/A" : title)); Date date = new Date(item.pubDate.getTime()); SimpleDateFormat sdf = new SimpleDateFormat("d LLL yyyy HH:mm", Locale.getDefault()); RSSEnclosure enclosure = item.enclosures.get(0); ContentValues contentValues = new ContentValues(); contentValues.put(NewsColumns.TITLE, item.getTitle()); contentValues.put(NewsColumns.LINK, item.getLink()); contentValues.put(NewsColumns.DESCRIPTION, item.getDescription()); contentValues.put(NewsColumns.FAV, 0); contentValues.put(NewsColumns.DATE, sdf.format(date)); contentValues.put(NewsColumns.PHOTO, enclosure.getLink()); String select = "("+NewsColumns.TITLE+ " = ? )"; Cursor check = mContentResolver.query(NewsProvider.Lists.LISTS,new String[]{ NewsColumns.TITLE}, select,new String[]{item.getTitle()},null,null); check.moveToFirst(); if(check.getCount() > 0) { int columIndex = check.getColumnIndex(NewsColumns.TITLE); if (item.getTitle().compareTo(check.getString(columIndex)) == 1 ) { cvArray.add(contentValues); } }else{ cvArray.add(contentValues); } check.close(); } } ContentValues[] cc = new ContentValues[cvArray.size()]; cvArray.toArray(cc); mContentResolver.bulkInsert(NewsProvider.Lists.LISTS, cc); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); if(cc.length>0 && prefs.getBoolean(getContext().getString(R.string.pref_notification_key),true) ) { showNotifications(); } //Cursor c = mContentResolver.query(NewsProvider.Lists.LISTS,new String[]{ NewsColumns._ID},null,null,null); Log.d("Provider data", Integer.toString(cc.length)); //c.close(); }catch (MalformedURLException e) { Log.d("Url","error"); }catch (IOException e){ Log.d("IO","ERROR"); }catch (XmlPullParserException e) { Log.d("XML","error"); }catch (DataFormatException e){ Log.d("Date","Error"); }catch (NullPointerException e){ e.printStackTrace(); } } private void showNotifications() { String order = NewsColumns.DATE+" DESC"; Cursor c = mContentResolver.query(NewsProvider.Lists.LISTS,new String[]{ NewsColumns._ID,NewsColumns.TITLE,NewsColumns.DATE},null,null,order); c.moveToFirst(); Intent resultIntent = new Intent(getContext(), DetailActivity.class); resultIntent.putExtra("news_id",c.getString(c.getColumnIndex(NewsColumns._ID))); PendingIntent resultPendingIntent = PendingIntent.getActivity( getContext(), 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext()) .setSmallIcon(R.mipmap.ic_launcher) .setDefaults(Notification.DEFAULT_ALL) .setAutoCancel(true) .setContentTitle(c.getString(c.getColumnIndex(NewsColumns.TITLE))) .setContentText(c.getString(c.getColumnIndex(NewsColumns.DATE))); builder.setContentIntent(resultPendingIntent); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getContext()); notificationManager.notify(1, builder.build()); c.close(); } }
package net.misykat.misykatbandung.data; import net.misykat.misykatbandung.SoundCloudHelper; import net.misykat.misykatbandung.util.ISO8601; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class Track { String id; String fullTitle; String speakerName; String title; String waveformUrl; String urn; Calendar lastModified; Calendar createdAt; String genre; String permalinkUrl; String uri; String artworkUrl; Integer fullDuration; private Track() { } public Track(String id, String fullTitle, String waveformUrl, String urn, Calendar lastModified, String genre, String permalinkUrl, String uri, String artworkUrl, Integer fullDuration, Calendar createdAt) { this.id = id; this.waveformUrl = waveformUrl; this.urn = urn; this.lastModified = lastModified; this.genre = genre; this.permalinkUrl = permalinkUrl; this.uri = uri; this.artworkUrl = artworkUrl; this.fullDuration = fullDuration; this.createdAt = createdAt; setFullTitle(fullTitle); } void setFullTitle(String fullTitle) { this.fullTitle = fullTitle; if (fullTitle.contains(":")) { String[] titles = fullTitle.split(":"); speakerName = titles[0].trim(); title = titles[1].trim(); } else if (fullTitle.contains(";")) { String[] titles = fullTitle.split(";"); speakerName = titles[0].trim(); title = titles[1].trim(); } else if (fullTitle.contains(" - ")) { String[] titles = fullTitle.split("-"); speakerName = titles[0].trim(); title = titles[1].trim(); } else { title = fullTitle; } } public String getId() { return id; } public String getFullTitle() { return fullTitle; } public String getSpeakerName() { return speakerName; } public String getTitle() { return title; } public String getWaveformUrl() { return waveformUrl; } public String getUrn() { return urn; } public Calendar getLastModified() { return lastModified; } public String getGenre() { return genre; } public String getPermalinkUrl() { return permalinkUrl; } public String getUri() { return uri; } public String getArtworkUrl() { return artworkUrl; } public Integer getFullDuration() { return fullDuration; } public String getStreamUrl() { return uri + "&clientId" + SoundCloudHelper.CLIENT_ID; } public Calendar getCreatedAt() { return createdAt; } public static Track fromJson(JSONObject o) { Track t = new Track(); t.id = getString(o, "id"); t.artworkUrl = getString(o, "artwork_url"); t.fullDuration = getInteger(o, "full_duration"); t.setFullTitle(getString(o, "title")); t.waveformUrl = getString(o, "waveform_url"); t.urn = getString(o, "urn"); t.uri = getString(o, "uri"); t.lastModified = getCalendar(o, "last_modified"); t.createdAt = getCalendar(o, "created_at"); t.genre = getString(o, "genre"); t.permalinkUrl = getString(o, "permalink_url"); return t; } private static Calendar getCalendar(JSONObject o, String attr) { try { return ISO8601.toCalendar(o.getString(attr)); } catch (JSONException e) { return null; } catch (ParseException e) { e.printStackTrace(); return null; } } private static Integer getInteger(JSONObject o, String attr) { try { return o.getInt(attr); } catch (JSONException e) { return null; } } public static String getString(JSONObject o, String attr) { try { return o.getString(attr); } catch (JSONException e) { return null; } } }
package com.splicemachine.utils; import java.util.Comparator; public class ComparableComparator<E extends Comparable<E>> implements Comparator<E>{ private static final ComparableComparator INSTANCE = new ComparableComparator(); @SuppressWarnings("unchecked") public static <E extends Comparable<E>>Comparator<? super E> newComparator(){ return (Comparator<E>)INSTANCE; } public int compare(E o1, E o2) { if(o1==null){ if(o2==null) return 0; return -1; }else if(o2==null) return 1; else return o1.compareTo(o2); } }
package net.polybugger.artemis; import android.content.Intent; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.design.widget.Snackbar; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.internal.CallbackManagerImpl; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FacebookAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import java.util.Arrays; import java.util.Set; public class SignInActivity extends AppCompatActivity implements SignInMethodFragment.SignInListener, GoogleApiClient.OnConnectionFailedListener { public static final int RC_GOOGLE_SIGN_IN = 1; public static final int RC_FACEBOOK = 7000; private FirebaseAuth mAuth; private FirebaseAuth.AuthStateListener mAuthListener; private GoogleApiClient mGoogleApiClient; private CallbackManager mCallbackManager; private SignInLoaderDialogFragment mLoaderDialogFragment; public enum SignInMethod { EMAIL_PASSWORD, GOOGLE, FACEBOOK, ANONYMOUS } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAuth = FirebaseAuth.getInstance(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser firebaseUser = mAuth.getCurrentUser(); if(firebaseUser != null) { } else { } } }; // Configure Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); FacebookSdk.sdkInitialize(getApplicationContext(), SignInActivity.RC_FACEBOOK); mCallbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { AccessToken accessToken = loginResult.getAccessToken(); Set<String> declinedPermissions = accessToken.getDeclinedPermissions(); if(declinedPermissions.contains("email")) { LoginManager.getInstance().logOut(); snackbarSignInFailed(false); } else { facebookSign(accessToken); } } @Override public void onCancel() { LoginManager.getInstance().logOut(); snackbarSignInFailed(false); } @Override public void onError(FacebookException error) { LoginManager.getInstance().logOut(); snackbarSignInFailed(false); } }); setContentView(R.layout.activity_sign_in); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); if(getSupportActionBar() != null) { getSupportActionBar().setTitle(R.string.sign_in); } SharedPreferences sharedPrefs = getSharedPreferences(getString(R.string.preferences_file), MODE_PRIVATE); boolean isSignedIn = sharedPrefs.getBoolean(getString(R.string.preference_is_signed_in_key), getResources().getBoolean(R.bool.preference_default_is_signed_in)); if(isSignedIn) { String defaultSignInMethodString = getString(R.string.preference_default_sign_in_method); SignInMethod defaultSignInMethod = SignInMethod.ANONYMOUS; try { defaultSignInMethod = SignInMethod.valueOf(defaultSignInMethodString); } catch(IllegalArgumentException iae) { if(BuildConfig.DEBUG) { Log.e(MainActivity.class.toString(), "Invalid default sign in method!"); } } catch(NullPointerException npe) { if (BuildConfig.DEBUG) { Log.e(MainActivity.class.toString(), "Missing default sign in method!"); } } SignInMethod signInMethod = defaultSignInMethod; try { signInMethod = SignInMethod.valueOf(sharedPrefs.getString(getString(R.string.preference_sign_in_method_key), defaultSignInMethodString)); } catch(IllegalArgumentException iae) { if (BuildConfig.DEBUG) { Log.e(MainActivity.class.toString(), "Invalid sign in method!"); } } catch(NullPointerException npe) { if (BuildConfig.DEBUG) { Log.e(MainActivity.class.toString(), "Missing sign in method!"); } } String email = sharedPrefs.getString(getString(R.string.preference_sign_in_email_key), null); String password = sharedPrefs.getString(getString(R.string.preference_sign_in_password_key), null); signIn(email, password, signInMethod); } else { FragmentManager fm = getSupportFragmentManager(); SignInMethodFragment signInMethodFragment = (SignInMethodFragment) fm.findFragmentByTag(SignInMethodFragment.TAG); if(signInMethodFragment == null) { signInMethodFragment = SignInMethodFragment.newInstance(); fm.beginTransaction().replace(R.id.fragment_container, signInMethodFragment, SignInMethodFragment.TAG).commit(); } } } @Override public void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } @Override public void onStop() { super.onStop(); if(mAuthListener != null) { mAuth.removeAuthStateListener(mAuthListener); } } @Override protected void onResume() { super.onResume(); } @Override public void onBackPressed() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case RC_GOOGLE_SIGN_IN: // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); googleSignIn(data); break; default: // facebook if(FacebookSdk.isFacebookRequestCode(requestCode)) { if(requestCode == CallbackManagerImpl.RequestCodeOffset.Login.toRequestCode()) { mCallbackManager.onActivityResult(requestCode, resultCode, data); } } else { snackbarSignInFailed(false); } } } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { snackbarSignInFailed(false); } @Override public void signIn(String email, String password, SignInMethod signInMethod) { switch(signInMethod) { case EMAIL_PASSWORD: emailPasswordSignIn(email, password); break; case ANONYMOUS: anonymousSignIn(); break; case GOOGLE: Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_GOOGLE_SIGN_IN); break; case FACEBOOK: LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "public_profile")); break; default: anonymousSignIn(); } } private void emailPasswordSignIn(final String email, final String password) { FragmentManager fm = getSupportFragmentManager(); mLoaderDialogFragment = (SignInLoaderDialogFragment) fm.findFragmentByTag(SignInLoaderDialogFragment.TAG); if(mLoaderDialogFragment == null) { mLoaderDialogFragment = SignInLoaderDialogFragment.newInstance(); mLoaderDialogFragment.show(fm, SignInLoaderDialogFragment.TAG); } mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { mLoaderDialogFragment.dismiss(); if(task.isSuccessful()) { SharedPreferences sharedPrefs = getSharedPreferences(getString(R.string.preferences_file), MODE_PRIVATE); sharedPrefs.edit().putBoolean(getString(R.string.preference_is_signed_in_key), true) .putString(getString(R.string.preference_sign_in_email_key), email) .putString(getString(R.string.preference_sign_in_password_key), password) .putString(getString(R.string.preference_sign_in_method_key), SignInMethod.EMAIL_PASSWORD.toString()) .apply(); startMainActivity(); } else { snackbarSignInFailed(true); } } }); } private void anonymousSignIn() { FragmentManager fm = getSupportFragmentManager(); mLoaderDialogFragment = (SignInLoaderDialogFragment) fm.findFragmentByTag(SignInLoaderDialogFragment.TAG); if(mLoaderDialogFragment == null) { mLoaderDialogFragment = SignInLoaderDialogFragment.newInstance(); mLoaderDialogFragment.show(fm, SignInLoaderDialogFragment.TAG); } mAuth.signInAnonymously().addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { mLoaderDialogFragment.dismiss(); if(task.isSuccessful()) { SharedPreferences sharedPrefs = getSharedPreferences(getString(R.string.preferences_file), MODE_PRIVATE); sharedPrefs.edit().putBoolean(getString(R.string.preference_is_signed_in_key), true) .putString(getString(R.string.preference_sign_in_method_key), SignInMethod.ANONYMOUS.toString()) .apply(); startMainActivity(); } else { snackbarSignInFailed(false); } } }); } private void googleSignIn(Intent data) { FragmentManager fm = getSupportFragmentManager(); mLoaderDialogFragment = (SignInLoaderDialogFragment) fm.findFragmentByTag(SignInLoaderDialogFragment.TAG); if(mLoaderDialogFragment == null) { mLoaderDialogFragment = SignInLoaderDialogFragment.newInstance(); mLoaderDialogFragment.show(fm, SignInLoaderDialogFragment.TAG); } boolean signInFailed = true; GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); if(result.isSuccess()) { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = result.getSignInAccount(); if(account != null) { signInFailed = false; AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null); mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { mLoaderDialogFragment.dismiss(); if(task.isSuccessful()) { SharedPreferences sharedPrefs = getSharedPreferences(getString(R.string.preferences_file), MODE_PRIVATE); sharedPrefs.edit().putBoolean(getString(R.string.preference_is_signed_in_key), true) .putString(getString(R.string.preference_sign_in_method_key), SignInMethod.GOOGLE.toString()) .apply(); startMainActivity(); } else { snackbarSignInFailed(false); } } }); } } if(signInFailed) { mLoaderDialogFragment.dismiss(); snackbarSignInFailed(false); } } private void facebookSign(AccessToken accessToken) { FragmentManager fm = getSupportFragmentManager(); mLoaderDialogFragment = (SignInLoaderDialogFragment) fm.findFragmentByTag(SignInLoaderDialogFragment.TAG); if(mLoaderDialogFragment == null) { mLoaderDialogFragment = SignInLoaderDialogFragment.newInstance(); mLoaderDialogFragment.show(fm, SignInLoaderDialogFragment.TAG); } AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken()); mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { mLoaderDialogFragment.dismiss(); if(task.isSuccessful()) { SharedPreferences sharedPrefs = getSharedPreferences(getString(R.string.preferences_file), MODE_PRIVATE); sharedPrefs.edit().putBoolean(getString(R.string.preference_is_signed_in_key), true) .putString(getString(R.string.preference_sign_in_method_key), SignInMethod.FACEBOOK.toString()) .apply(); startMainActivity(); } else { LoginManager.getInstance().logOut(); snackbarSignInFailed(false); } } }); } private void startMainActivity() { Intent intent = new Intent(SignInActivity.this, MainActivity.class); Bundle args = new Bundle(); intent.putExtras(args); startActivity(intent); finish(); } private void snackbarSignInFailed(boolean focusEmailTextEdit) { SharedPreferences sharedPrefs = getSharedPreferences(getString(R.string.preferences_file), MODE_PRIVATE); sharedPrefs.edit().putBoolean(getString(R.string.preference_is_signed_in_key), false).apply(); Snackbar.make(findViewById(R.id.coordinator_layout), R.string.error_sign_in_failed, Snackbar.LENGTH_SHORT).show(); FragmentManager fm = getSupportFragmentManager(); SignInMethodFragment signInMethodFragment = (SignInMethodFragment) fm.findFragmentByTag(SignInMethodFragment.TAG); if(signInMethodFragment == null) { signInMethodFragment = SignInMethodFragment.newInstance(); fm.beginTransaction().replace(R.id.fragment_container, signInMethodFragment, SignInMethodFragment.TAG).commit(); } else if(focusEmailTextEdit) { signInMethodFragment.focusEmailPassword(); } } }
package com.vaguehope.onosendai.ui.pref; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.Spinner; import com.vaguehope.onosendai.R; import com.vaguehope.onosendai.config.Column; import com.vaguehope.onosendai.config.Prefs; import com.vaguehope.onosendai.util.CollectionHelper; import com.vaguehope.onosendai.util.EqualHelper; import com.vaguehope.onosendai.util.StringHelper; class ColumnDialog { private static final List<Duration> REFRESH_DURAITONS = CollectionHelper.listOf( new Duration(0, "Never"), new Duration(15, "15 minutes"), new Duration(30, "30 minutes"), new Duration(45, "45 minutes"), new Duration(60, "1 hour"), new Duration(60 * 2, "2 hours"), new Duration(60 * 3, "3 hours"), new Duration(60 * 6, "6 hours"), new Duration(60 * 12, "12 hours"), new Duration(60 * 24, "24 hours") ); private final int id; private final String accountId; private final Column initialValue; private final View llParent; private final EditText txtTitle; private final Spinner spnPosition; private final EditText txtResource; private final Spinner spnRefresh; private final CheckBox chkNotify; private final CheckBox chkDelete; public ColumnDialog (final Context context, final Prefs prefs, final int id, final String accountId) { this(context, prefs, id, accountId, null); } public ColumnDialog (final Context context, final Prefs prefs, final Column initialValue) { this(context, prefs, initialValue != null ? initialValue.getId() : null, initialValue != null ? initialValue.getAccountId() : null, initialValue); } private ColumnDialog (final Context context, final Prefs prefs, final int id, final String accountId, final Column initialValue) { if (prefs == null) throw new IllegalArgumentException("Prefs can not be null."); if (initialValue != null && initialValue.getId() != id) throw new IllegalStateException("ID and initialValue ID do not match."); if (initialValue != null && !EqualHelper.equal(initialValue.getAccountId(), accountId)) throw new IllegalStateException("Account ID and initialValue account ID do not match."); this.id = id; this.accountId = accountId; this.initialValue = initialValue; LayoutInflater inflater = LayoutInflater.from(context); this.llParent = inflater.inflate(R.layout.columndialog, null); this.txtTitle = (EditText) this.llParent.findViewById(R.id.txtTitle); this.spnPosition = (Spinner) this.llParent.findViewById(R.id.spnPosition); this.txtResource = (EditText) this.llParent.findViewById(R.id.txtResource); this.spnRefresh = (Spinner) this.llParent.findViewById(R.id.spnRefresh); this.chkNotify = (CheckBox) this.llParent.findViewById(R.id.chkNotify); this.chkDelete = (CheckBox) this.llParent.findViewById(R.id.chkDelete); final ArrayAdapter<Integer> posAdapter = new ArrayAdapter<Integer>(context, R.layout.numberspinneritem); posAdapter.addAll(CollectionHelper.sequence(1, prefs.readColumnIds().size() + (initialValue == null ? 1 : 0))); this.spnPosition.setAdapter(posAdapter); final ArrayAdapter<Duration> refAdapter = new ArrayAdapter<Duration>(context, R.layout.numberspinneritem); refAdapter.addAll(REFRESH_DURAITONS); this.spnRefresh.setAdapter(refAdapter); this.chkDelete.setChecked(false); if (initialValue != null) { this.txtTitle.setText(initialValue.getTitle()); this.spnPosition.setSelection(posAdapter.getPosition(Integer.valueOf(prefs.readColumnPosition(initialValue.getId()) + 1))); this.txtResource.setText(initialValue.getResource()); setDurationSpinner(initialValue.getRefreshIntervalMins(), refAdapter); if (StringHelper.isEmpty(accountId)) this.spnRefresh.setEnabled(false); this.chkNotify.setChecked(initialValue.isNotify()); this.chkDelete.setVisibility(View.VISIBLE); } else { this.spnPosition.setSelection(posAdapter.getCount() - 1); // Last item. setDurationSpinner(0, refAdapter); // Default to no background refresh. this.chkDelete.setVisibility(View.GONE); } } private void setDurationSpinner (final int mins, final ArrayAdapter<Duration> refAdapter) { final Duration duration = new Duration(mins > 0 ? mins : 0); final int pos = refAdapter.getPosition(duration); if (pos < 0) refAdapter.add(duration); // Allow for any value to have been chosen before. this.spnRefresh.setSelection(pos < 0 ? refAdapter.getPosition(duration) : pos); } public Column getInitialValue () { return this.initialValue; } public View getRootView () { return this.llParent; } public void setResource (final String resource) { this.txtResource.setText(resource); } public void setTitle (final String title) { this.txtTitle.setText(title); } /** * 0 based. */ public int getPosition () { return ((Integer) this.spnPosition.getSelectedItem()) - 1; } public boolean isDeleteSelected () { return this.chkDelete.isChecked(); } public Column getValue () { return new Column(this.id, this.txtTitle.getText().toString(), this.accountId, this.txtResource.getText().toString(), ((Duration) this.spnRefresh.getSelectedItem()).getMins(), this.initialValue != null ? this.initialValue.getExcludeColumnIds() : null, // TODO GUI for excludes. this.chkNotify.isChecked()); } private static class Duration { private final int mins; private final String title; public Duration (final int mins) { this(mins, null); } public Duration (final int mins, final String title) { this.mins = mins; this.title = title; } public int getMins () { return this.mins; } @Override public String toString () { return this.title; } @Override public boolean equals (final Object o) { if (o == null) return false; if (o == this) return true; if (!(o instanceof Duration)) return false; final Duration that = (Duration) o; return this.mins == that.mins; } @Override public int hashCode () { return this.mins; } } }
package org.literacyapp.receiver; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.util.Log; import org.literacyapp.LiteracyApplication; import org.literacyapp.service.ContentSynchronizationJobService; import org.literacyapp.service.FaceRecognitionTrainingJobService; import org.literacyapp.service.ScreenOnService; import org.literacyapp.service.synchronization.AuthenticationJobService; import org.literacyapp.service.synchronization.MergeSimilarStudentsJobService; public class BootReceiver extends BroadcastReceiver { public static final int MINUTES_BETWEEN_AUTHENTICATIONS = 30; private static final int MINUTES_BETWEEN_FACE_RECOGNITION_TRAININGS = 15; private static final int HOURS_BETWEEN_MERGING_SIMILAR_STUDENTS = 24; @Override public void onReceive(Context context, Intent intent) { Log.d(getClass().getName(), "onReceive"); // // Automatically open application // Intent bootIntent = new Intent(context, MainActivity.class); // bootIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // context.startActivity(bootIntent); // Initiate background job for synchronizing with server content ComponentName componentName = new ComponentName(context, ContentSynchronizationJobService.class); JobInfo.Builder builder = new JobInfo.Builder(LiteracyApplication.CONTENT_SYNCRHONIZATION_JOB_ID, componentName); builder.setPeriodic(1000 * 60 * 30); // Every 30 minutes JobInfo jobInfo = builder.build(); JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobScheduler.schedule(jobInfo); // Initiate background job for face recognition training scheduleFaceRecognitionTranining(context); // Initiate background job for face recognition authentication scheduleAuthentication(context, MINUTES_BETWEEN_AUTHENTICATIONS); // Initiate background job for merging similar students scheduleMergeSimilarStudents(context); // Start service for detecting when the screen is turned on Intent screenOnServiceIntent = new Intent(context, ScreenOnService.class); context.startService(screenOnServiceIntent); // TODO: trigger the same code as in ScreenOnReceiver } public static void scheduleFaceRecognitionTranining(Context context){ ComponentName componentNameFaceRecognitionTranining = new ComponentName(context, FaceRecognitionTrainingJobService.class); JobInfo.Builder builderFaceRecognitionTranining = new JobInfo.Builder(LiteracyApplication.FACE_RECOGNITION_TRAINING_JOB_ID, componentNameFaceRecognitionTranining); int faceRecognitionTrainingPeriodic = MINUTES_BETWEEN_FACE_RECOGNITION_TRAININGS * 60 * 1000; builderFaceRecognitionTranining.setPeriodic(faceRecognitionTrainingPeriodic); // Every 15 minutes JobInfo faceRecognitionTrainingJobInfo = builderFaceRecognitionTranining.build(); JobScheduler jobSchedulerFaceRecognitionTranining = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobSchedulerFaceRecognitionTranining.schedule(faceRecognitionTrainingJobInfo); Log.i(context.getClass().getName(), "FACE_RECOGNITION_TRAINING_JOB with ID " + LiteracyApplication.FACE_RECOGNITION_TRAINING_JOB_ID + " has been scheduled with periodic time = " + faceRecognitionTrainingPeriodic); } public static void scheduleAuthentication(Context context, int minutesBetweenAuthentications){ ComponentName componentNameAuthentication = new ComponentName(context, AuthenticationJobService.class); JobInfo.Builder builderAuthentication = new JobInfo.Builder(LiteracyApplication.AUTHENTICATION_JOB_ID, componentNameAuthentication); int authenticationPeriodic = minutesBetweenAuthentications * 60 * 1000; builderAuthentication.setPeriodic(authenticationPeriodic); JobInfo authenticationJobInfo = builderAuthentication.build(); JobScheduler jobSchedulerAuthentication = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobSchedulerAuthentication.schedule(authenticationJobInfo); Log.i(context.getClass().getName(), "AUTHENTICATION_JOB with ID " + LiteracyApplication.AUTHENTICATION_JOB_ID + " has been scheduled with periodic time = " + authenticationPeriodic); } public static void scheduleMergeSimilarStudents(Context context){ ComponentName componentNameMergeSimilarStudents = new ComponentName(context, MergeSimilarStudentsJobService.class); JobInfo.Builder builderMergeSimilarStudents = new JobInfo.Builder(LiteracyApplication.MERGE_SIMILAR_STUDENTS_JOB_ID, componentNameMergeSimilarStudents); boolean requiresCharging = true; builderMergeSimilarStudents.setRequiresCharging(requiresCharging); int mergeSimilarStudentsPeriodic = HOURS_BETWEEN_MERGING_SIMILAR_STUDENTS * 60 * 60 * 1000; builderMergeSimilarStudents.setPeriodic(mergeSimilarStudentsPeriodic); JobInfo mergeSimilarStudentsJobInfo = builderMergeSimilarStudents.build(); JobScheduler jobSchedulerMergeSimilarStudents = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); jobSchedulerMergeSimilarStudents.schedule(mergeSimilarStudentsJobInfo); Log.i(context.getClass().getName(), "MERGE_SIMILAR_STUDENTS_JOB with ID " + LiteracyApplication.MERGE_SIMILAR_STUDENTS_JOB_ID + " has been scheduled with periodic time = " + mergeSimilarStudentsPeriodic + " requiresCharging = " + requiresCharging); } }
package com.vaguehope.onosendai.update; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import org.json.JSONException; import twitter4j.TwitterException; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.NetworkInfo.State; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import com.vaguehope.onosendai.C; import com.vaguehope.onosendai.config.Account; import com.vaguehope.onosendai.config.Column; import com.vaguehope.onosendai.config.Config; import com.vaguehope.onosendai.model.Tweet; import com.vaguehope.onosendai.model.TweetList; import com.vaguehope.onosendai.provider.ProviderMgr; import com.vaguehope.onosendai.provider.successwhale.SuccessWhaleException; import com.vaguehope.onosendai.provider.successwhale.SuccessWhaleFeed; import com.vaguehope.onosendai.provider.successwhale.SuccessWhaleProvider; import com.vaguehope.onosendai.provider.twitter.TwitterFeed; import com.vaguehope.onosendai.provider.twitter.TwitterFeeds; import com.vaguehope.onosendai.provider.twitter.TwitterProvider; import com.vaguehope.onosendai.storage.DbClient; import com.vaguehope.onosendai.util.LogWrapper; public class UpdateService extends IntentService { protected final LogWrapper log = new LogWrapper("US"); protected final CountDownLatch dbReadyLatch = new CountDownLatch(1); private DbClient bndDb; public UpdateService () { super("OnosendaiUpdateService"); } @Override public void onCreate () { super.onCreate(); connectDb(); } @Override public void onDestroy () { disconnectDb(); super.onDestroy(); } @Override protected void onHandleIntent (final Intent i) { this.log.i("UpdateService invoked."); PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, C.TAG); wl.acquire(); try { doWork(); } finally { wl.release(); } } private void connectDb () { this.log.d("Binding DB service..."); this.bndDb = new DbClient(getApplicationContext(), this.log.getPrefix(), new Runnable() { @Override public void run () { UpdateService.this.dbReadyLatch.countDown(); UpdateService.this.log.d("DB service bound."); } }); } private void disconnectDb () { this.bndDb.dispose(); this.log.d("DB service rebound."); } private boolean waitForDbReady() { boolean dbReady = false; try { dbReady = this.dbReadyLatch.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) {} if (!dbReady) { this.log.e("Not updateing: Time out waiting for DB service to connect."); } return dbReady; } private void doWork () { if (connectionPresent()) { fetchColumns(); } else { this.log.i("No connection, all updating aborted."); } } private void fetchColumns () { Config conf; try { conf = new Config(); } catch (IOException e) { this.log.w("Can not update: %s", e.toString()); return; } catch (JSONException e) { this.log.w("Can not update: %s", e.toString()); return; } final ProviderMgr providerMgr = new ProviderMgr(); try { fetchColumns(conf, providerMgr); } finally { providerMgr.shutdown(); } } private void fetchColumns (final Config conf, final ProviderMgr providerMgr) { final long startTime = System.nanoTime(); Collection<Column> columns = remoteNonFetchable(conf.getColumns()); if (columns.size() >= C.MIN_COLUMS_TO_USE_THREADPOOL) { fetchColumnsMultiThread(conf, providerMgr, columns); } else { fetchColumnsSingleThread(conf, providerMgr, columns); } final long durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); this.log.i("Fetched %d columns in %d millis.", columns.size(), durationMillis); } private static Collection<Column> remoteNonFetchable (final Collection<Column> columns) { List<Column> ret = new ArrayList<Column>(); for (Column column : columns) { if (column.accountId != null) ret.add(column); } return ret; } private void fetchColumnsSingleThread (final Config conf, final ProviderMgr providerMgr, final Collection<Column> columns) { for (Column column : columns) { fetchColumn(conf, column, providerMgr); } } private void fetchColumnsMultiThread (final Config conf, final ProviderMgr providerMgr, final Collection<Column> columns) { int poolSize = Math.min(columns.size(), C.MAX_THREAD_POOL_SIZE); this.log.i("Using thread pool size %d for %d columns.", poolSize, columns.size()); ExecutorService ex = Executors.newFixedThreadPool(poolSize); try { Map<Column, Future<Void>> jobs = new LinkedHashMap<Column, Future<Void>>(); for (Column column : columns) { jobs.put(column, ex.submit(new FetchColumn(conf, column, providerMgr, this))); } for (Entry<Column, Future<Void>> job : jobs.entrySet()) { try { job.getValue().get(); } catch (InterruptedException e) { this.log.w("Error fetching column '%s': %s %s", job.getKey().title, e.getClass().getName(), e.toString()); } catch (ExecutionException e) { this.log.w("Error fetching column '%s': %s %s", job.getKey().title, e.getClass().getName(), e.toString()); } } } finally { ex.shutdownNow(); } } private static class FetchColumn implements Callable<Void> { private final Config conf; private final Column column; private final ProviderMgr providerMgr; private final UpdateService updateService; public FetchColumn (final Config conf, final Column column, final ProviderMgr providerMgr, final UpdateService updateService) { this.conf = conf; this.column = column; this.providerMgr = providerMgr; this.updateService = updateService; } @Override public Void call () { this.updateService.fetchColumn(this.conf, this.column, this.providerMgr); return null; } } public void fetchColumn (final Config conf, final Column column, final ProviderMgr providerMgr) { final long startTime = System.nanoTime(); final Account account = conf.getAccount(column.accountId); if (account == null) { this.log.e("Unknown acountId: '%s'.", column.accountId); return; } switch (account.provider) { case TWITTER: try { final TwitterProvider twitterProvider = providerMgr.getTwitterProvider(); twitterProvider.addAccount(account); TwitterFeed feed = TwitterFeeds.parse(column.resource); if (!waitForDbReady()) return; long sinceId = -1; List<Tweet> existingTweets = this.bndDb.getDb().getTweets(column.id, 1); if (existingTweets.size() > 0) sinceId = existingTweets.get(existingTweets.size() - 1).getId(); TweetList tweets = twitterProvider.getTweets(feed, account, sinceId); this.bndDb.getDb().storeTweets(column, tweets.getTweets()); long durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); this.log.i("Fetched %d items for '%s' in %d millis.", tweets.count(), column.title, durationMillis); } catch (TwitterException e) { this.log.w("Failed to fetch from Twitter: %s", e.toString()); } break; case SUCCESSWHALE: try { final SuccessWhaleProvider successWhaleProvider = providerMgr.getSuccessWhaleProvider(); successWhaleProvider.addAccount(account); SuccessWhaleFeed feed = new SuccessWhaleFeed(column); if (!waitForDbReady()) return; TweetList tweets = successWhaleProvider.getTweets(feed, account); this.bndDb.getDb().storeTweets(column, tweets.getTweets()); long durationMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); this.log.i("Fetched %d items for '%s' in %d millis.", tweets.count(), column.title, durationMillis); } catch (SuccessWhaleException e) { this.log.w("Failed to fetch from SuccessWhale: %s", e.toString()); } break; default: this.log.e("Unknown account type: %s", account.provider); } } private boolean connectionPresent () { ConnectivityManager cMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cMgr.getActiveNetworkInfo(); if ((netInfo != null) && (netInfo.getState() != null)) { return netInfo.getState().equals(State.CONNECTED); } return false; } }
package de.nava.demo.repository; import com.mongodb.MongoClient; import org.bson.Document; import org.springframework.stereotype.Repository; import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; /** * Simplest possible implementation for accessing the MongoDB * to persist job history documents. * * @author Niko Schmuck */ @Repository public class JobHistoryRepository { @Autowired private MongoClient mongo; public void add(Map<String, Object> keys) { // TODO: make configurable / use repository ? // TODO: set expire TTL based on 'ts' field (ie. 7 days) mongo.getDatabase("jobs-demo").getCollection("job_history") .insertOne(new Document(keys)); } }
package li.vin.net; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import com.squareup.okhttp.HttpUrl; public class SignInActivity extends Activity { private static final String TAG = SignInActivity.class.getSimpleName(); private static final String CLIENT_ID = "li.vin.net.SignInActivity#CLIENT_ID"; private static final String REDIRECT_URI = "li.vin.net.SignInActivity#REDIRECT_URI"; private static final String PENDING_INTENT = "li.vin.net.SignInActivity#PENDING_INTENT"; private static final String ACTION_ERROR = "li.vin.net.signIn.ERROR"; private static final String ACTION_APPROVED = "li.vin.net.signIn.APPROVED"; private static final HttpUrl OAUTH_ENPOINT = new HttpUrl.Builder() .scheme("https") .host("auth" + Endpoint.domain()) .addPathSegment("oauth") .addPathSegment("authorization") .addPathSegment("new") .addQueryParameter("response_type", "token") .build(); /*protected*/ static final Intent newIntent(@NonNull Context context, @NonNull String clientId, @NonNull String redirectUri, @NonNull PendingIntent pendingIntent) { final Intent signInIntent = new Intent(context, SignInActivity.class); signInIntent.putExtra(CLIENT_ID, clientId); signInIntent.putExtra(REDIRECT_URI, redirectUri); signInIntent.putExtra(PENDING_INTENT, pendingIntent); return signInIntent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Bundle extras = getIntent().getExtras(); if (extras == null) { throw new AssertionError("missing app info extras"); } final String clientId = extras.getString(CLIENT_ID); if (clientId == null) { throw new AssertionError("missing client ID"); } final String redirectUri = extras.getString(REDIRECT_URI); if (redirectUri == null) { throw new AssertionError("missing redirect URI"); } final PendingIntent pendingIntent = extras.getParcelable(PENDING_INTENT); if (pendingIntent == null) { throw new AssertionError("missing pending intent"); } setContentView(R.layout.activity_vinli_sign_in); final WebView wv = (WebView) this.findViewById(li.vin.net.R.id.sign_in); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.d(TAG, "shouldOverrideUrlLoading: " + url); if (url.startsWith(redirectUri)) { String error = null; String accessToken = null; try { final HttpUrl uri = HttpUrl.parse(url); final String[] fragmentPieces = uri.fragment().split("&"); for (String piece : fragmentPieces) { if (piece.startsWith("access_token=")) { accessToken = piece.substring("access_token=".length()); break; } else if (piece.startsWith("error=")) { error = piece.substring("error=".length()); break; } } } catch (Exception e) { error = "redirect parse error: " + e; } Intent resultIntent; if (error == null) { if (accessToken == null) { resultIntent = new Intent(ACTION_ERROR); resultIntent.putExtra(Vinli.SIGN_IN_ERROR, "missing access_token"); } else { Log.d(TAG, "oauth accessToken: " + accessToken); resultIntent = new Intent(ACTION_APPROVED); resultIntent.putExtra(Vinli.ACCESS_TOKEN, accessToken); } } else { Log.d(TAG, "oauth error: " + error); resultIntent = new Intent(ACTION_ERROR); resultIntent.putExtra(Vinli.SIGN_IN_ERROR, error); } try { pendingIntent.send(SignInActivity.this, 0, resultIntent); } catch (Exception e) { Log.d(TAG, "pending intent send error: " + e); } return true; } return false; } }); final String url = OAUTH_ENPOINT.newBuilder() .host("auth" + Endpoint.domain()) .setQueryParameter("client_id", clientId) .setQueryParameter("redirect_uri", redirectUri) .toString(); Log.d("SignInActivity", "loading url: " + url); wv.loadUrl(url); } }
package main.java.de.nullpointer.zauberei.team; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.craftbukkit.v1_10_R1.CraftServer; import org.bukkit.craftbukkit.v1_10_R1.entity.CraftPlayer; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class QuidditchPlayer { public enum Playertype { BEATER, CHASER, SEEKER, KEEPER }; protected static Material[] items = new Material[]{ Material.COMPASS, Material.STICK }; private Player player; private Playertype type; private QuidditchTeam team; public QuidditchPlayer(Player player, Playertype type, QuidditchTeam team) { this.player = player; this.type = type; this.team = team; } public void fillInventory() { Inventory inv = player.getInventory(); inv.clear(); for (Material m : items) { inv.addItem(new ItemStack(m)); } } public Playertype getQuidditchType() { return type; } public QuidditchTeam getTeam() { return team; } }
package li.vin.net; import android.app.Activity; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import com.squareup.okhttp.HttpUrl; public class SignInActivity extends Activity { private static final String TAG = SignInActivity.class.getSimpleName(); private static final String CLIENT_ID = "li.vin.net.SignInActivity#CLIENT_ID"; private static final String REDIRECT_URI = "li.vin.net.SignInActivity#REDIRECT_URI"; private static final String PENDING_INTENT = "li.vin.net.SignInActivity#PENDING_INTENT"; private static final String ACTION_ERROR = "li.vin.net.signIn.ERROR"; private static final String ACTION_APPROVED = "li.vin.net.signIn.APPROVED"; private static final HttpUrl.Builder OAUTH_ENPOINT = new HttpUrl.Builder() .scheme("https") .addPathSegment("oauth") .addPathSegment("authorization") .addPathSegment("new") .addQueryParameter("response_type", "token"); /*protected*/ static final Intent newIntent(@NonNull Context context, @NonNull String clientId, @NonNull String redirectUri, @NonNull PendingIntent pendingIntent) { final Intent signInIntent = new Intent(context, SignInActivity.class); signInIntent.putExtra(CLIENT_ID, clientId); signInIntent.putExtra(REDIRECT_URI, redirectUri); signInIntent.putExtra(PENDING_INTENT, pendingIntent); return signInIntent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Bundle extras = getIntent().getExtras(); if (extras == null) { throw new AssertionError("missing app info extras"); } final String clientId = extras.getString(CLIENT_ID); if (clientId == null) { throw new AssertionError("missing client ID"); } final String redirectUri = extras.getString(REDIRECT_URI); if (redirectUri == null) { throw new AssertionError("missing redirect URI"); } final PendingIntent pendingIntent = extras.getParcelable(PENDING_INTENT); if (pendingIntent == null) { throw new AssertionError("missing pending intent"); } setContentView(R.layout.activity_vinli_sign_in); final WebView wv = (WebView) this.findViewById(li.vin.net.R.id.sign_in); wv.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.d(TAG, "shouldOverrideUrlLoading: " + url); if (url.startsWith(redirectUri)) { String error = null; String accessToken = null; try { final HttpUrl uri = HttpUrl.parse(url); final String[] fragmentPieces = uri.fragment().split("&"); for (String piece : fragmentPieces) { if (piece.startsWith("access_token=")) { accessToken = piece.substring("access_token=".length()); break; } else if (piece.startsWith("error=")) { error = piece.substring("error=".length()); break; } } } catch (Exception e) { error = "redirect parse error: " + e; Log.e(TAG, error); } Intent resultIntent; if (error == null) { if (accessToken == null) { resultIntent = new Intent(ACTION_ERROR); resultIntent.putExtra(Vinli.SIGN_IN_ERROR, "missing access_token"); } else { Log.d(TAG, "oauth accessToken: " + accessToken); resultIntent = new Intent(ACTION_APPROVED); resultIntent.putExtra(Vinli.ACCESS_TOKEN, accessToken); } } else { Log.d(TAG, "oauth error: " + error); resultIntent = new Intent(ACTION_ERROR); resultIntent.putExtra(Vinli.SIGN_IN_ERROR, error); } try { pendingIntent.send(SignInActivity.this, 0, resultIntent); } catch (Exception e) { Log.d(TAG, "pending intent send error: " + e); } return true; } return false; } }); final String url = OAUTH_ENPOINT .host("auth" + Endpoint.domain()) .addQueryParameter("client_id", clientId) .addQueryParameter("redirect_uri", redirectUri) .toString(); Log.d("SignInActivity", "loading url: " + url); wv.loadUrl(url); } }
package de.tourenplaner.algorithms.bbbundle; import com.carrotsearch.hppc.IntArrayDeque; import com.carrotsearch.hppc.IntArrayList; import com.carrotsearch.hppc.IntStack; import com.carrotsearch.hppc.cursors.IntCursor; import de.tourenplaner.algorithms.ComputeException; import de.tourenplaner.algorithms.PrioAlgorithm; import de.tourenplaner.algorithms.bbprioclassic.BoundingBox; import de.tourenplaner.computecore.ComputeRequest; import de.tourenplaner.graphrep.GraphRep; import de.tourenplaner.graphrep.PrioDings; import de.tourenplaner.utils.Timing; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.logging.Logger; public class BBBundle extends PrioAlgorithm { private static Logger log = Logger.getLogger("de.tourenplaner.algorithms"); private static final int UNSEEN = 0; private static final int DISCOVERED = 1; private static final int ACTIVE = 2; private static final int COMPLETED = 3; private final int[] dfsState; private final int[] mappedIds; private final IntArrayList needClear; public BBBundle(GraphRep graph, PrioDings prioDings) { super(graph, prioDings); dfsState = new int[graph.getNodeCount()]; mappedIds = new int[graph.getNodeCount()]; needClear = new IntArrayList(); } private IntArrayDeque topoSortNodes(IntArrayList bboxNodes, int P, int coreSize) { IntArrayDeque topSorted = new IntArrayDeque(bboxNodes.size()); for (int i = 0; i < bboxNodes.size(); ++i) { int bboxNodeId = bboxNodes.get(i); // We only want nodes that aren't in the core because we got them already if (bboxNodeId >= coreSize && dfsState[bboxNodeId] == UNSEEN) { dfs(topSorted, bboxNodeId, coreSize); } } int currMapId = coreSize; for (IntCursor ic: topSorted) { assert dfsState[ic.value] == COMPLETED; mappedIds[ic.value] = currMapId++; } for (IntCursor ic : needClear) { dfsState[ic.value] = UNSEEN; } needClear.clear(); return topSorted; } private void dfs(IntArrayDeque topSorted, int bboxNodeId, int coreSize) { IntStack stack = new IntStack(); dfsState[bboxNodeId] = DISCOVERED; needClear.add(bboxNodeId); stack.push(bboxNodeId); while (!stack.isEmpty()) { int nodeId = stack.peek(); switch (dfsState[nodeId]) { case DISCOVERED: { dfsState[nodeId] = ACTIVE; int nodeRank = graph.getRank(nodeId); // Up-Out edges for (int upEdgeNum = graph.getOutEdgeCount(nodeId) - 1; upEdgeNum >= 0; --upEdgeNum) { int edgeId = graph.getOutEdgeId(nodeId, upEdgeNum); int trgtId = graph.getTarget(edgeId); int trgtRank = graph.getRank(trgtId); // Out edges are sorted by target rank ascending, mind we're going down if (trgtRank <= nodeRank) { break; } assert dfsState[trgtId] != ACTIVE; if (dfsState[trgtId] == COMPLETED || trgtId < coreSize) { continue; } assert nodeRank <= trgtRank; // up edge assert nodeId >= trgtId; // up edge + nodes sorted by rank ascending dfsState[trgtId] = DISCOVERED; needClear.add(trgtId); stack.push(trgtId); } // Down-In edges for (int downEdgeNum = 0; downEdgeNum < graph.getInEdgeCount(nodeId); ++downEdgeNum) { int edgeId = graph.getInEdgeId(nodeId, downEdgeNum); int srcId = graph.getSource(edgeId); int srcRank = graph.getRank(srcId); // In edges are sorted by source rank descending if (srcRank <= nodeRank) { break; } assert dfsState[srcId] != ACTIVE; if (dfsState[srcId] == COMPLETED || srcId < coreSize) { continue; } assert nodeRank <= srcRank; // down edge assert nodeId >= srcId; // down edge + nodes sorted by rank ascending dfsState[srcId] = DISCOVERED; needClear.add(srcId); stack.push(srcId); } break; } case ACTIVE: { dfsState[nodeId] = COMPLETED; topSorted.addFirst(stack.pop()); break; } case COMPLETED: // Stale stack entry, ignore stack.pop(); break; default: throw new RuntimeException("Crazy dfsState "+dfsState[nodeId]); } } } public void unpack(int index, IntArrayList unpackIds, double minLen, double maxLen, double maxRatio) { /*if (drawn.get(index)) { return; }*/ double edgeLen = ((double) graph.getEuclidianDist(index)); int skipA = graph.getFirstShortcuttedEdge(index); if (skipA == -1 || edgeLen <= minLen) { unpackIds.add(index); return; } int skipB = graph.getSecondShortcuttedEdge(index); /* * |x1 y1 1| * A = abs(1/2* |x2 y2 1|)= 1/2*Baseline*Height * |x3 y3 1| * = 1/2*((x1*y2+y1*x3+x2*y3) - (y2*x3 + y1*x2 + x1*y3)) * Height = 2*A/Baseline * ratio = Height/Baseline * */ if (edgeLen <= maxLen) { int middle = graph.getTarget(skipA); int srcId = graph.getSource(index); double x1 = graph.getXPos(srcId); double y1 = graph.getYPos(srcId); double x2 = graph.getXPos(middle); double y2 = graph.getYPos(middle); int trgtId = graph.getTarget(index); double x3 = graph.getXPos(trgtId); double y3 = graph.getYPos(trgtId); double A = Math.abs(0.5 * ((x1 * y2 + y1 * x3 + x2 * y3) - (y2 * x3 + y1 * x2 + x1 * y3))); double ratio = 2.0 * A / (edgeLen * edgeLen); if (ratio <= maxRatio) { unpackIds.add(index); return; } } unpack(skipA, unpackIds, minLen, maxLen, maxRatio); unpack(skipB, unpackIds, minLen, maxLen, maxRatio); } private void extractEdges(IntArrayDeque nodes, ArrayList<BBBundleEdge> upEdges, ArrayList<BBBundleEdge> downEdges, int coreSize, double minLen, double maxLen, double maxRatio) { int edgeCount = 0; for (IntCursor ic : nodes) { int nodeId = ic.value; int nodeRank = graph.getRank(nodeId); // Up-Out edges for (int upEdgeNum = graph.getOutEdgeCount(nodeId) - 1; upEdgeNum >= 0; --upEdgeNum) { int edgeId = graph.getOutEdgeId(nodeId, upEdgeNum); int trgtId = graph.getTarget(edgeId); int trgtRank = graph.getRank(trgtId); // Out edges are sorted by target rank ascending, mind we're going down if (trgtRank <= nodeRank) { break; } assert nodeRank <= trgtRank; // up edge assert nodeId >= trgtId; // up edge + nodes sorted by rank ascending assert (trgtId < coreSize) || mappedIds[nodeId] < mappedIds[trgtId]; int srcIdMapped = mappedIds[nodeId]; int trgtIdMapped = (trgtId >= coreSize) ? mappedIds[trgtId] : trgtId; BBBundleEdge e = new BBBundleEdge(edgeId, srcIdMapped, trgtIdMapped, graph.getDist(edgeId)); unpack(edgeId, e.unpacked, minLen, maxLen, maxRatio); upEdges.add(e); edgeCount++; } // Down-In edges for (int downEdgeNum = 0; downEdgeNum < graph.getInEdgeCount(nodeId); ++downEdgeNum) { int edgeId = graph.getInEdgeId(nodeId, downEdgeNum); int srcId = graph.getSource(edgeId); int srcRank = graph.getRank(srcId); // In edges are sorted by source rank descending if (srcRank <= nodeRank) { break; } assert nodeRank <= srcRank; // down edge assert nodeId >= srcId; // down edge + nodes sorted by rank ascending //assert (srcId < coreSize) || mappedIds[nodeId] < mappedIds[srcId]; // topological order, trgt -> src int srcIdMapped = (srcId >= coreSize) ? mappedIds[srcId] : srcId; int trgtIdMapped = mappedIds[nodeId]; BBBundleEdge e = new BBBundleEdge(edgeId, srcIdMapped, trgtIdMapped, graph.getDist(edgeId)); unpack(edgeId, e.unpacked, minLen, maxLen, maxRatio); downEdges.add(e); edgeCount++; } } log.info(edgeCount + " edges"); } private IntArrayList findBBoxNodes(BBBundleRequestData req) { BoundingBox bbox = req.getBbox(); long start = System.nanoTime(); IntArrayList bboxNodes = new IntArrayList(); int currNodeCount; int level; if (req.getMode() == BBBundleRequestData.LevelMode.AUTO) { level = graph.getMaxRank(); do { level = level - 10; req.setLevel(level); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); currNodeCount = bboxNodes.size(); } while (level > 0 && currNodeCount < req.getNodeCount()); } else if (req.getMode() == BBBundleRequestData.LevelMode.HINTED) { level = graph.getMaxRank(); do { level = level - 10; bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); currNodeCount = bboxNodes.size(); } while (level > 0 && currNodeCount < req.getNodeCount()); log.info("AutoLevel was: " + level); level = (req.getLevel() + level) / 2; req.setLevel(level); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); } else { // else if (req.mode == BBPrioLimitedRequestData.LevelMode.EXACT){ level = req.getLevel(); bboxNodes = prioDings.getNodeSelection(new Rectangle2D.Double(bbox.x, bbox.y, bbox.width, bbox.height), level); } log.info(Timing.took("ExtractBBox", start)); log.info("Level was: " + req.getLevel()); log.info("Nodes extracted: " + bboxNodes.size() + " of " + graph.getNodeCount()); return bboxNodes; } @Override public void compute(ComputeRequest request) throws ComputeException { BBBundleRequestData req = (BBBundleRequestData) request.getRequestData(); IntArrayList bboxNodes = findBBoxNodes(req); long start; start = System.nanoTime(); IntArrayDeque nodes = topoSortNodes(bboxNodes, req.getLevel(), req.getCoreSize()); log.info(Timing.took("TopSort", start)); log.info("Nodes after TopSort: (with coreSize = " + req.getCoreSize() + ") " + nodes.size()); start = System.nanoTime(); ArrayList<BBBundleEdge> upEdges = new ArrayList<>(); ArrayList<BBBundleEdge> downEdges = new ArrayList<>(); extractEdges(nodes, upEdges, downEdges, req.getCoreSize(), req.getMinLen(), req.getMaxLen(), req.getMaxRatio()); log.info(Timing.took("Extracting edges", start)); log.info("UpEdges: " + upEdges.size() + ", downEdges: " + downEdges.size()); request.setResultObject(new BBBundleResult(graph, nodes.size(), upEdges, downEdges, req)); } }
package de.tum.in.www1.artemis.service; import static de.tum.in.www1.artemis.domain.enumeration.AssessmentType.AUTOMATIC; import java.time.ZonedDateTime; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import javax.validation.constraints.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import de.tum.in.www1.artemis.domain.*; import de.tum.in.www1.artemis.domain.exam.Exam; import de.tum.in.www1.artemis.domain.exam.ExerciseGroup; import de.tum.in.www1.artemis.domain.modeling.ModelingExercise; import de.tum.in.www1.artemis.domain.notification.GroupNotification; import de.tum.in.www1.artemis.repository.CourseRepository; import de.tum.in.www1.artemis.repository.UserRepository; import de.tum.in.www1.artemis.security.ArtemisAuthenticationProvider; import de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException; import de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException; /** * Service Implementation for managing Course. */ @Service public class CourseService { private final Logger log = LoggerFactory.getLogger(CourseService.class); private final CourseRepository courseRepository; private final ExerciseService exerciseService; private final AuthorizationCheckService authCheckService; private final ArtemisAuthenticationProvider artemisAuthenticationProvider; private final UserRepository userRepository; private final LectureService lectureService; private final NotificationService notificationService; private ExamService examService; private final ExerciseGroupService exerciseGroupService; public CourseService(CourseRepository courseRepository, ExerciseService exerciseService, AuthorizationCheckService authCheckService, ArtemisAuthenticationProvider artemisAuthenticationProvider, UserRepository userRepository, LectureService lectureService, NotificationService notificationService, ExerciseGroupService exerciseGroupService) { this.courseRepository = courseRepository; this.exerciseService = exerciseService; this.authCheckService = authCheckService; this.artemisAuthenticationProvider = artemisAuthenticationProvider; this.userRepository = userRepository; this.lectureService = lectureService; this.notificationService = notificationService; this.exerciseGroupService = exerciseGroupService; } @Autowired // break the dependency cycle public void setExamService(ExamService examService) { this.examService = examService; } /** * Save a course. * * @param course the entity to save * @return the persisted entity */ public Course save(Course course) { log.debug("Request to save Course : {}", course); return courseRepository.save(course); } /** * Get all the courses. * * @return the list of entities */ public List<Course> findAll() { log.debug("Request to get all courses"); return courseRepository.findAll(); } /** * Get all the courses. * * @return the list of entities */ public List<Course> findAllActiveWithLecturesAndExams() { log.debug("Request to get all active courses"); return courseRepository.findAllActiveWithLecturesAndExams(ZonedDateTime.now()); } /** * Get all the courses. * * @return the list of entities */ public List<Course> findAllCurrentlyActiveNotOnlineAndRegistrationEnabled() { log.debug("Request to get all active courses which are not online and enabled"); return courseRepository.findAllCurrentlyActiveNotOnlineAndRegistrationEnabled(ZonedDateTime.now()); } /** * Get one course with exercises and lectures (filtered for given user) * * @param courseId the course to fetch * @param user the user entity * @return the course including exercises and lectures for the user */ public Course findOneWithExercisesAndLecturesForUser(Long courseId, User user) { Course course = findOneWithLecturesAndExams(courseId); if (!authCheckService.isAtLeastStudentInCourse(course, user)) { throw new AccessForbiddenException("You are not allowed to access this resource"); } course.setExercises(exerciseService.findAllForCourse(course, user)); course.setLectures(lectureService.filterActiveAttachments(course.getLectures(), user)); if (authCheckService.isOnlyStudentInCourse(course, user)) { course.setExams(examService.filterVisibleExams(course.getExams())); } return course; } /** * Get all courses with exercises and lectures (filtered for given user) * * @param user the user entity * @return the list of all courses including exercises and lectures for the user */ public List<Course> findAllActiveWithExercisesAndLecturesForUser(User user) { return findAllActiveWithLecturesAndExams().stream() // filter old courses and courses the user should not be able to see // skip old courses that have already finished .filter(course -> course.getEndDate() == null || course.getEndDate().isAfter(ZonedDateTime.now())).filter(course -> isActiveCourseVisibleForUser(user, course)) .peek(course -> { course.setExercises(exerciseService.findAllForCourse(course, user)); course.setLectures(lectureService.filterActiveAttachments(course.getLectures(), user)); if (authCheckService.isOnlyStudentInCourse(course, user)) { course.setExams(examService.filterVisibleExams(course.getExams())); } }).collect(Collectors.toList()); } private boolean isActiveCourseVisibleForUser(User user, Course course) { // Instructors and TAs see all courses that have not yet finished if (authCheckService.isAtLeastTeachingAssistantInCourse(course, user)) { return true; } // Students see all courses that have already started (and not yet finished) if (user.getGroups().contains(course.getStudentGroupName())) { return course.getStartDate() == null || course.getStartDate().isBefore(ZonedDateTime.now()); } return false; } /** * Get one course by id. * * @param courseId the id of the entity * @return the entity */ @NotNull public Course findOne(Long courseId) { log.debug("Request to get Course : {}", courseId); return courseRepository.findById(courseId).orElseThrow(() -> new EntityNotFoundException("Course with id: \"" + courseId + "\" does not exist")); } /** * Get one course by id. * * @param courseId the id of the entity * @return the entity */ @NotNull public Course findOneWithLecturesAndExams(Long courseId) { log.debug("Request to get Course : {}", courseId); return courseRepository.findWithEagerLecturesAndExamsById(courseId).orElseThrow(() -> new EntityNotFoundException("Course with id: \"" + courseId + "\" does not exist")); } /** * Get one course by id with all its exercises. * * @param courseId the id of the entity * @return the entity */ public Course findOneWithExercises(long courseId) { log.debug("Request to get Course : {}", courseId); return courseRepository.findWithEagerExercisesById(courseId); } public Course findOneWithExercisesAndLectures(long courseId) { log.debug("Request to get Course : {}", courseId); return courseRepository.findWithEagerExercisesAndLecturesById(courseId); } public void delete(Course course) { log.debug("Request to delete Course : {}", course.getTitle()); for (Exercise exercise : course.getExercises()) { exerciseService.delete(exercise.getId(), true, true); } for (Lecture lecture : course.getLectures()) { lectureService.delete(lecture); } List<GroupNotification> notifications = notificationService.findAllGroupNotificationsForCourse(course); for (GroupNotification notification : notifications) { notificationService.deleteGroupNotification(notification); } if (course.getStudentGroupName().equals(course.getDefaultStudentGroupName())) { artemisAuthenticationProvider.deleteGroup(course.getStudentGroupName()); } if (course.getTeachingAssistantGroupName().equals(course.getDefaultTeachingAssistantGroupName())) { artemisAuthenticationProvider.deleteGroup(course.getTeachingAssistantGroupName()); } if (course.getInstructorGroupName().equals(course.getDefaultInstructorGroupName())) { artemisAuthenticationProvider.deleteGroup(course.getInstructorGroupName()); } // delete the Exams List<Exam> exams = examService.findAllByCourseId(course.getId()); for (Exam exam : exams) { examService.deleteById(exam.getId()); } courseRepository.deleteById(course.getId()); } /** * Given a Course object, it returns the number of users enrolled in the course * * @param course - the course object we are interested in * @return the number of students for that course */ public long countNumberOfStudentsForCourse(Course course) { String groupName = course.getStudentGroupName(); return userRepository.countByGroupsIsContaining(groupName); } /** * If the exercise is part of an exam, retrieve the course through ExerciseGroup -> Exam -> Course. * Otherwise the course is already set and the id can be used to retrieve the course from the database. * * @param exercise the Exercise for which the course is retrieved * @return the Course of the Exercise */ public Course retrieveCourseOverExerciseGroupOrCourseId(Exercise exercise) { if (exercise.hasExerciseGroup()) { ExerciseGroup exerciseGroup = exerciseGroupService.findOneWithExam(exercise.getExerciseGroup().getId()); exercise.setExerciseGroup(exerciseGroup); return exerciseGroup.getExam().getCourse(); } else { Course course = findOne(exercise.getCourseViaExerciseGroupOrCourseMember().getId()); exercise.setCourse(course); return course; } } /** * filters the passed exercises for the relevant ones that need to be manually assessed. This excludes quizzes and automatic programming exercises * @param exercises all exercises (e.g. of a course or exercise group) that should be filtered * @return the filtered and relevant exercises for manual assessment */ public Set<Exercise> getInterestingExercisesForAssessmentDashboards(Set<Exercise> exercises) { return exercises.stream().filter(exercise -> exercise instanceof TextExercise || exercise instanceof ModelingExercise || exercise instanceof FileUploadExercise || (exercise instanceof ProgrammingExercise && exercise.getAssessmentType() != AUTOMATIC)).collect(Collectors.toSet()); } }
package de.tum.in.www1.artemis.service; import de.tum.in.www1.artemis.domain.*; import de.tum.in.www1.artemis.repository.CourseRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.security.Principal; import java.time.ZonedDateTime; import java.util.*; import java.util.stream.Collectors; /** * Service Implementation for managing Course. */ @Service @Transactional public class CourseService { private final Logger log = LoggerFactory.getLogger(CourseService.class); private final CourseRepository courseRepository; private final UserService userService; private final ExerciseService exerciseService; private final AuthorizationCheckService authCheckService; public CourseService(CourseRepository courseRepository, UserService userService, ExerciseService exerciseService, AuthorizationCheckService authCheckService) { this.courseRepository = courseRepository; this.userService = userService; this.exerciseService = exerciseService; this.authCheckService = authCheckService; } /** * Save a course. * * @param course the entity to save * @return the persisted entity */ public Course save(Course course) { log.debug("Request to save Course : {}", course); return courseRepository.save(course); } /** * Get all the courses. * * @return the list of entities */ @Transactional(readOnly = true) public List<Course> findAll() { log.debug("Request to get all Courses"); return courseRepository.findAll(); } public boolean userHasAtLeastStudentPermissions(Course course) { User user = userService.getUserWithGroupsAndAuthorities(); return authCheckService.isStudentInCourse(course, user) || authCheckService.isTeachingAssistantInCourse(course, user) || authCheckService.isInstructorInCourse(course, user) || authCheckService.isAdmin(); } public boolean userHasAtLeastTAPermissions(Course course) { User user = userService.getUserWithGroupsAndAuthorities(); return authCheckService.isTeachingAssistantInCourse(course, user) || authCheckService.isInstructorInCourse(course, user) || authCheckService.isAdmin(); } public boolean userHasAtLeastInstructorPermissions(Course course) { User user = userService.getUserWithGroupsAndAuthorities(); return authCheckService.isInstructorInCourse(course, user) || authCheckService.isAdmin(); } /** * Get all the courses with exercises. * * @return the list of entities */ @Transactional(readOnly = true) public List<Course> findAllWithExercises() { log.debug("Request to get all Courses with Exercises"); return courseRepository.findAllWithEagerExercises(); } /** * Get all courses with exercises (filtered for given user) * * @param principal the user principal * @param user the user entity * @return the list of all courses including exercises for the user */ @Transactional(readOnly = true) public List<Course> findAllWithExercisesForUser(Principal principal, User user) { if (authCheckService.isAdmin()) { // admin => fetch all courses with all exercises immediately List<Course> allCourses = findAllWithExercises(); Set<Course> userCourses = new HashSet<>(); // filter old courses and unnecessary information anyway for (Course course : allCourses) { if (course.getEndDate() != null && course.getEndDate().isBefore(ZonedDateTime.now())) { //skip old courses that have already finished continue; } userCourses.add(course); } return new ArrayList<>(userCourses); } else { // not admin => fetch visible courses first List<Course> allCourses = findAll(); Set<Course> userCourses = new HashSet<>(); // filter old courses and courses the user should not be able to see for (Course course : allCourses) { if (course.getEndDate() != null && course.getEndDate().isBefore(ZonedDateTime.now())) { //skip old courses that have already finished continue; } //Instructors and TAs see all courses that have not yet finished if (user.getGroups().contains(course.getTeachingAssistantGroupName()) || user.getGroups().contains(course.getInstructorGroupName())) { userCourses.add(course); } //Students see all courses that have already started (and not yet finished) else if (user.getGroups().contains(course.getStudentGroupName())) { if (course.getStartDate() == null || course.getStartDate().isBefore(ZonedDateTime.now())) { userCourses.add(course); } } } for (Course course : userCourses) { // fetch visible exercises for each course after filtering List<Exercise> exercises = exerciseService.findAllForCourse(course, true, principal, user); course.setExercises(new HashSet<>(exercises)); } return new ArrayList<>(userCourses); } } /** * Get one course by id. * * @param id the id of the entity * @return the entity */ @Transactional(readOnly = true) public Course findOne(Long id) { log.debug("Request to get Course : {}", id); return courseRepository.findById(id).get(); } /** * Delete the course by id. * * @param id the id of the entity */ public void delete(Long id) { log.debug("Request to delete Course : {}", id); courseRepository.deleteById(id); } public List<String> getAllTeachingAssistantGroupNames() { List<Course> courses = courseRepository.findAll(); return courses.stream().map(Course::getTeachingAssistantGroupName).collect(Collectors.toList()); } public List<String> getAllInstructorGroupNames() { List<Course> courses = courseRepository.findAll(); return courses.stream().map(Course::getInstructorGroupName).collect(Collectors.toList()); } /** * Getting a Collection of Results in which the average Score of a course is returned as a result * * @param courseId the courseId * @return the collection of results in the result score the average score is saved, which contains the participation and the user */ @Transactional(readOnly = true) public Collection<Result> getAllOverallScoresOfCourse(Long courseId) { Course course = findOne(courseId); Set<Exercise> exercisesOfCourse = course.getExercises(); //key stores the userId to identify if he already got a score, value contains the Result itself with the score of the user HashMap<Long, Result> allOverallSummedScoresOfCourse = new HashMap<>(); for (Exercise exercise : exercisesOfCourse) { Set<Participation> participations = exercise.getParticipations(); boolean exerciseHasDueDate = exercise.getDueDate() != null; for (Participation participation : participations) { //id of user in the database to reference to the user long userID = participation.getStudent().getId(); Result bestResult = choseResultInParticipation(participation, exerciseHasDueDate); //TODO: it might happen that there are two participations for one student and one exercise, e.g. a FINISHED one and an INITIALIZED one. // Make sure to use only one of them //if student already appeared, once add the new score to the old one if (allOverallSummedScoresOfCourse.containsKey(userID)) { long currentScore = allOverallSummedScoresOfCourse.get(userID).getScore(); bestResult.setScore(currentScore + bestResult.getScore()); } allOverallSummedScoresOfCourse.put(userID, bestResult); } } //divide the scores by the amount of exercises to get the average Score of all Exercises Collection<Result> allOverallScores = allOverallSummedScoresOfCourse.values(); int numberOfExercises = exercisesOfCourse.size(); for (Result result : allOverallScores) { result.setScore(result.getScore() / (long) numberOfExercises); } return allOverallScores; } /** * Find the best Result in a Participation * * @param participation the participation you want the best result from * @param hasDueDate if the participation has a duedate take last result before the due date if not take the overall last result * @return the best result a student had within the time of the exercise */ @Transactional(readOnly = true) public Result choseResultInParticipation(Participation participation, boolean hasDueDate) { List<Result> results = new ArrayList<>(participation.getResults()); //TODO take the field result.isRated into account Result chosenResult; //edge case of no result submitted to a participation if (results.size() <= 0) { chosenResult = new Result(); chosenResult.setScore((long) 0); chosenResult.setParticipation(participation); return chosenResult; } //sorting in descending order to have the last result at the beginning results.sort(Comparator.comparing(Result::getCompletionDate).reversed()); if (hasDueDate) { //find the first result that is before the due date otherwise handles the case where all results were submitted after the due date, chosenResult = results.stream() .filter(x -> x.getCompletionDate().isBefore(participation.getExercise().getDueDate())) .findFirst() .orElse(new Result()); } else { chosenResult = results.remove(0); //no due date use last result } //edge case where the db has stored null for score if (chosenResult.getScore() == null) { chosenResult.setScore((long) 0); } //setting participation in result to have student id later chosenResult.setParticipation(participation); return chosenResult; } }
package edu.cmu.sv.ws.ssnoc.rest; import java.sql.SQLException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import edu.cmu.sv.ws.ssnoc.common.logging.Log; import edu.cmu.sv.ws.ssnoc.common.utils.MeasurementUtils; import edu.cmu.sv.ws.ssnoc.data.util.DBUtils; public class SSNoCAppInitializer extends HttpServlet { private static final long serialVersionUID = 5446123041570390878L; public void init(ServletConfig config) throws ServletException { // Perform any steps needed during server startup as part // of this method. This includes initializing database etc. try { DBUtils.initializeDatabase(); //MeasurementUtils.measure(); } catch (SQLException e) { Log.error("Oops :( We ran into an error when trying to intialize " + "database. Please check the trace for more details.", e); } } }
package edu.wright.hendrix11.svg.transform; /** * @author Joe Hendrix */ public class Translate extends XyTransform { public Translate(Number x, Number y) { super(x,y); } public Translate(Number x) { super(x); } public String toString() { StringBuilder sb = new StringBuilder("translate(").append(x); if(y != null) sb.append(",").append(y); return .append(")").toString(); } }
package ee.tuleva.onboarding.config; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Slf4j @Component public class SimpleCORSFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "https://pension.tuleva.ee"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "Authorization"); response.setHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, res); } }
package erogenousbeef.bigreactors.common; import java.util.Calendar; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.client.event.TextureStitchEvent; import cofh.api.modhelpers.ThermalExpansionHelper; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import erogenousbeef.bigreactors.api.registry.Reactants; import erogenousbeef.bigreactors.common.data.StandardReactants; import erogenousbeef.bigreactors.common.item.ItemIngot; import erogenousbeef.bigreactors.gui.BigReactorsGUIHandler; import erogenousbeef.bigreactors.net.CommonPacketHandler; import erogenousbeef.bigreactors.utils.intermod.IMCHelper; import erogenousbeef.bigreactors.utils.intermod.ModHelperBase; import erogenousbeef.bigreactors.utils.intermod.ModHelperComputerCraft; import erogenousbeef.bigreactors.utils.intermod.ModHelperMekanism; import erogenousbeef.core.multiblock.MultiblockServerTickHandler; public class CommonProxy { public void preInit() { } public void init() { BigReactors.registerTileEntities(); CommonPacketHandler.init(); NetworkRegistry.INSTANCE.registerGuiHandler(BRLoader.instance, new BigReactorsGUIHandler()); BigReactors.tickHandler = new BigReactorsTickHandler(); FMLCommonHandler.instance().bus().register(BigReactors.tickHandler); FMLCommonHandler.instance().bus().register(new MultiblockServerTickHandler()); sendInterModAPIMessages(); if(Loader.isModLoaded("VersionChecker")) { FMLInterModComms.sendRuntimeMessage(BRLoader.MOD_ID, "VersionChecker", "addVersionCheck", "http://big-reactors.com/version.json"); } } private void sendInterModAPIMessages() { ItemIngot ingotGeneric = BigReactors.ingotGeneric; ItemStack yelloriteOre = new ItemStack(BigReactors.blockYelloriteOre, 1); final int YELLORIUM = 0; String[] names = ItemIngot.MATERIALS; ItemStack[] ingots = new ItemStack[names.length]; ItemStack[] dusts = new ItemStack[names.length]; for(int i = 0; i < names.length; i++) { ingots[i] = ingotGeneric.getIngotItem(names[i]); dusts[i] = ingotGeneric.getDustItem(names[i]); } ItemStack doubledYelloriumDust = null; if(dusts[YELLORIUM] != null) { doubledYelloriumDust = dusts[YELLORIUM].copy(); doubledYelloriumDust.stackSize = 2; } if(Loader.isModLoaded("ThermalExpansion")) { ItemStack sandStack = new ItemStack(Blocks.sand, 1); ItemStack doubleYellorium = ingots[YELLORIUM].copy(); doubleYellorium.stackSize = 2; // TODO: Remove ThermalExpansionHelper once addSmelterRecipe and addPulverizerRecipe aren't broken if(ingots[YELLORIUM] != null) { ThermalExpansionHelper.addFurnaceRecipe(400, yelloriteOre, ingots[YELLORIUM]); ThermalExpansionHelper.addSmelterRecipe(1600, yelloriteOre, sandStack, doubleYellorium); } if(doubledYelloriumDust != null) { ThermalExpansionHelper.addPulverizerRecipe(4000, yelloriteOre, doubledYelloriumDust); ThermalExpansionHelper.addSmelterRecipe(200, doubledYelloriumDust, sandStack, doubleYellorium); } for(int i = 0; i < ingots.length; i++) { if(ingots[i] == null || dusts[i] == null) { continue; } ThermalExpansionHelper.addPulverizerRecipe(2400, ingots[i], dusts[i]); ThermalExpansionHelper.addSmelterRecipe(200, doubledYelloriumDust, sandStack, doubleYellorium); ItemStack doubleDust = dusts[i].copy(); doubleDust.stackSize = 2; ItemStack doubleIngot = ingots[i].copy(); doubleIngot.stackSize = 2; ThermalExpansionHelper.addSmelterRecipe(200, doubleDust, sandStack, doubleIngot); } } // END: IsModLoaded - ThermalExpansion if(Loader.isModLoaded("MineFactoryReloaded")) { // Add yellorite to yellow focus list. IMCHelper.MFR.addOreToMiningLaserFocus(yelloriteOre, 2); // Make Yellorite the 'preferred' ore for lime focus IMCHelper.MFR.setMiningLaserFocusPreferredOre(yelloriteOre, 9); } // END: IsModLoaded - MineFactoryReloaded if(Loader.isModLoaded("appliedenergistics2")) { if(doubledYelloriumDust != null) { IMCHelper.AE2.addGrinderRecipe(yelloriteOre, doubledYelloriumDust, 4); } for(int i = 0; i < ingots.length; i++) { if(ingots[i] == null || dusts[i] == null) { continue; } IMCHelper.AE2.addGrinderRecipe(ingots[i], dusts[i], 2); } } // END: IsModLoaded - AE2 } public void postInit() { BRConfig.CONFIGURATION.load(); boolean autoAddUranium = BRConfig.CONFIGURATION.get("Compatibility", "autoAddUranium", true, "If true, automatically adds all " +"unregistered ingots found as clones" +"of standard yellorium fuel").getBoolean(true); if(autoAddUranium) { Reactants.registerSolid("ingotUranium", StandardReactants.yellorium); } BRConfig.CONFIGURATION.save(); registerWithOtherMods(); // Easter Egg - Check if today is valentine's day. If so, change all particles to hearts. Calendar calendar = Calendar.getInstance(); BigReactors.isValentinesDay = (calendar.get(Calendar.MONTH) == 1 && calendar.get(Calendar.DAY_OF_MONTH) == 14); } @SideOnly(Side.CLIENT) @SubscribeEvent public void registerIcons(TextureStitchEvent.Pre event) { } @SideOnly(Side.CLIENT) @SubscribeEvent public void setIcons(TextureStitchEvent.Post event) { } /// Mod Interoperability /// void registerWithOtherMods() { ModHelperBase modHelper; ModHelperBase.detectMods(); modHelper = new ModHelperComputerCraft(); modHelper.register(); modHelper = new ModHelperMekanism(); modHelper.register(); } }
package eu.hansolo.steelseries.gauges; import eu.hansolo.steelseries.tools.ColorDef; import eu.hansolo.steelseries.tools.ConicalGradientPaint; import eu.hansolo.steelseries.tools.CustomColorDef; import eu.hansolo.steelseries.tools.Direction; import eu.hansolo.steelseries.tools.ForegroundType; import eu.hansolo.steelseries.tools.FrameType; import eu.hansolo.steelseries.tools.GaugeType; import eu.hansolo.steelseries.tools.KnobStyle; import eu.hansolo.steelseries.tools.KnobType; import eu.hansolo.steelseries.tools.LcdColor; import eu.hansolo.steelseries.tools.NumberSystem; import eu.hansolo.steelseries.tools.Orientation; import eu.hansolo.steelseries.tools.PointerType; import eu.hansolo.steelseries.tools.PostPosition; import eu.hansolo.steelseries.tools.TicklabelOrientation; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.LinearGradientPaint; import java.awt.Paint; import java.awt.RadialGradientPaint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.event.ActionEvent; import java.awt.event.ComponentEvent; import java.awt.font.FontRenderContext; import java.awt.font.TextLayout; import java.awt.geom.AffineTransform; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import java.awt.geom.Line2D; import java.awt.geom.Path2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.List; import javax.swing.SwingConstants; import javax.swing.Timer; import javax.swing.border.Border; import org.pushingpixels.trident.Timeline; import org.pushingpixels.trident.TimelineScenario; import org.pushingpixels.trident.callback.TimelineCallback; import org.pushingpixels.trident.ease.Sine; import org.pushingpixels.trident.ease.Spline; import org.pushingpixels.trident.ease.TimelineEase; /** * * @author hansolo */ public abstract class AbstractRadial extends AbstractGauge implements Lcd { // <editor-fold defaultstate="collapsed" desc="Variable declarations"> protected static final float ANGLE_CONST = 1f / 360f; private final Rectangle INNER_BOUNDS; private final Rectangle GAUGE_BOUNDS; private final Rectangle FRAMELESS_BOUNDS; private final Point2D FRAMELESS_OFFSET; // Sections related private boolean transparentSectionsEnabled; private boolean transparentAreasEnabled; private boolean expandedSectionsEnabled; // Frame type related private Direction tickmarkDirection; // LED related variables private Point2D ledPosition; // User LED related variables private Point2D userLedPosition; // LCD related variables private String lcdUnitString; private double lcdValue; private String lcdInfoString = ""; private Timeline lcdTimeline; private boolean lcdTextVisible; private Timer LCD_BLINKING_TIMER; // Animation related variables private Timeline timeline; private final TimelineEase STANDARD_EASING; private final TimelineEase RETURN_TO_ZERO_EASING; private TimelineCallback timelineCallback; // Alignment related private int horizontalAlignment; private int verticalAlignment; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Constructor"> public AbstractRadial() { super(); lcdTimeline = new Timeline(this); lcdValue = 0; lcdUnitString = getUnitString(); ledPosition = new Point2D.Double(0.6, 0.4); userLedPosition = new Point2D.Double(0.3, 0.4); INNER_BOUNDS = new Rectangle(200, 200); GAUGE_BOUNDS = new Rectangle(200, 200); FRAMELESS_BOUNDS = new Rectangle(200, 200); FRAMELESS_OFFSET = new Point2D.Double(0, 0); transparentSectionsEnabled = false; transparentAreasEnabled = false; expandedSectionsEnabled = false; tickmarkDirection = Direction.CLOCKWISE; timeline = new Timeline(this); STANDARD_EASING = new Spline(0.5f); RETURN_TO_ZERO_EASING = new Sine(); horizontalAlignment = SwingConstants.CENTER; verticalAlignment = SwingConstants.CENTER; lcdTextVisible = true; LCD_BLINKING_TIMER = new Timer(500, this); addComponentListener(this); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Getters and Setters"> /** * Returns the enum that defines the type of the gauge * FG_TYPE1 a quarter gauge (90 deg) * FG_TYPE2 a two quarter gauge (180 deg) * FG_TYPE3 a three quarter gauge (270 deg) * TYPE4 a four quarter gauge (300 deg) * @return the type of the gauge (90, 180, 270 or 300 deg) */ public GaugeType getGaugeType() { return getModel().getGaugeType(); } /** * Sets the type of the gauge * FG_TYPE1 a quarter gauge (90 deg) * FG_TYPE2 a two quarter gauge (180 deg) * FG_TYPE3 a three quarter gauge (270 deg) * TYPE4 a four quarter gauge (300 deg) * @param GAUGE_TYPE */ public void setGaugeType(final GaugeType GAUGE_TYPE) { getModel().setGaugeType(GAUGE_TYPE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the type of frame that is used for the radial gauge. * It could be round our square. * @return the type of frame that will be used for the radial gauge. */ public FrameType getFrameType() { return getModel().getFrameType(); } /** * Defines the type of frame that will be used for the radial gauge. * It could be round our square. * @param FRAME_TYPE */ public void setFrameType(final FrameType FRAME_TYPE) { getModel().setFrameType(FRAME_TYPE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the type of foreground that is used for the radial gauge. * There are three types available. * @return the type of foreground that is will be used for the radial gauge */ public ForegroundType getForegroundType() { return getModel().getForegroundType(); } /** * Defines the type of foreground that will be used for the radial gauge. * There area three types available. * @param FOREGROUND_TYPE */ public void setForegroundType(final ForegroundType FOREGROUND_TYPE) { getModel().setForegroundType(FOREGROUND_TYPE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Uses trident animation library to animate * the setting of the value. * The method plays a defined trident timeline * that calls the setValue(double value) method * with a given easing behaviour and duration. * You should always use this method to set the * gauge to a given value. * @param VALUE */ public void setValueAnimated(final double VALUE) { if (isEnabled()) { if (timeline.getState() != Timeline.TimelineState.IDLE) { timeline.abort(); } final double TARGET_VALUE = VALUE < getMinValue() ? getMinValue() : (VALUE > getMaxValue() ? getMaxValue() : VALUE); if (!isAutoResetToZero()) { timeline.removeCallback(timelineCallback); timeline = new Timeline(this); timeline.addPropertyToInterpolate("value", getValue(), TARGET_VALUE); timeline.setEase(STANDARD_EASING); //TIMELINE.setDuration((long) (getStdTimeToValue() * fraction)); timeline.setDuration(getStdTimeToValue()); timelineCallback = new TimelineCallback() { @Override public void onTimelineStateChanged(final Timeline.TimelineState OLD_STATE, final Timeline.TimelineState NEW_STATE, final float OLD_VALUE, final float NEW_VALUE) { if (NEW_STATE == Timeline.TimelineState.IDLE) { repaint(getInnerBounds()); } // Check if current value exceeds maxMeasuredValue if (getValue() > getMaxMeasuredValue()) { setMaxMeasuredValue(getValue()); } } @Override public void onTimelinePulse(final float OLD_VALUE, final float NEW_VALUE) { // Check if current value exceeds maxMeasuredValue if (getValue() > getMaxMeasuredValue()) { setMaxMeasuredValue(getValue()); } // Check if current value exceeds minMeasuredValue if (getValue() < getMinMeasuredValue()) { setMinMeasuredValue(getValue()); } } }; timeline.addCallback(timelineCallback); timeline.play(); } else { final TimelineScenario AUTOZERO_SCENARIO = new TimelineScenario.Sequence(); final Timeline TIMELINE_TO_VALUE = new Timeline(this); TIMELINE_TO_VALUE.addPropertyToInterpolate("value", getValue(), TARGET_VALUE); TIMELINE_TO_VALUE.setEase(RETURN_TO_ZERO_EASING); //TIMELINE_TO_VALUE.setDuration((long) (getRtzTimeToValue() * fraction)); TIMELINE_TO_VALUE.setDuration(getRtzTimeToValue()); TIMELINE_TO_VALUE.addCallback(new TimelineCallback() { @Override public void onTimelineStateChanged(Timeline.TimelineState oldState, Timeline.TimelineState newState, float oldValue, float newValue) { if (oldState == Timeline.TimelineState.PLAYING_FORWARD && newState == Timeline.TimelineState.DONE) { // Set the peak value and start the timer getModel().setPeakValue(getValue()); getModel().setPeakValueVisible(true); if (getPeakTimer().isRunning()) { stopPeakTimer(); } startPeakTimer(); // Check if current value exceeds maxMeasuredValue if (getValue() > getMaxMeasuredValue()) { setMaxMeasuredValue(getValue()); } } } @Override public void onTimelinePulse(float oldValue, float newValue) { // Check if current value exceeds maxMeasuredValue if (getValue() > getMaxMeasuredValue()) { setMaxMeasuredValue(getValue()); } // Check if current value exceeds minMeasuredValue if (getValue() < getMinMeasuredValue()) { setMinMeasuredValue(getValue()); } } }); final Timeline TIMELINE_TO_ZERO = new Timeline(this); TIMELINE_TO_ZERO.addPropertyToInterpolate("value", TARGET_VALUE, 0.0); TIMELINE_TO_ZERO.setEase(RETURN_TO_ZERO_EASING); //TIMELINE_TO_ZERO.setDuration((long) (getRtzTimeBackToZero() * fraction)); TIMELINE_TO_ZERO.setDuration(getRtzTimeBackToZero()); AUTOZERO_SCENARIO.addScenarioActor(TIMELINE_TO_VALUE); AUTOZERO_SCENARIO.addScenarioActor(TIMELINE_TO_ZERO); // AUTOZERO_SCENARIO.addCallback(new org.pushingpixels.trident.callback.TimelineScenarioCallback() // @Override // public void onTimelineScenarioDone() AUTOZERO_SCENARIO.play(); } } } /** * Returns the step between the tickmarks * @return returns double value that represents the stepsize between the tickmarks */ public double getAngleStep() { return getModel().getAngleStep(); } /** * Returns the step between the tickmarks for log scaling * @return returns double value that represents the stepsize between the tickmarks for log scaling */ public double getLogAngleStep() { return getModel().getLogAngleStep(); } /** * Returns the angle area where no tickmarks will be drawn * @return the angle area where no tickmarks will be drawn */ public double getFreeAreaAngle() { return getModel().getFreeAreaAngle(); } public double getRotationOffset() { return getModel().getRotationOffset(); } public double getTickmarkOffset() { return getModel().getTickmarkOffset(); } public int getMaxNoOfMinorTicks() { return getModel().getMaxNoOfMinorTicks(); } public void setMaxNoOfMinorTicks(final int MAX_NO_OF_MINOR_TICKS) { getModel().setMaxNoOfMinorTicks(MAX_NO_OF_MINOR_TICKS); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } public int getMaxNoOfMajorTicks() { return getModel().getMaxNoOfMajorTicks(); } public void setMaxNoOfMajorTicks(final int MAX_NO_OF_MAJOR_TICKS) { getModel().setMaxNoOfMajorTicks(MAX_NO_OF_MAJOR_TICKS); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the current position of the gauge threshold led * @return the current position of the gauge threshold led */ @Override public Point2D getLedPosition() { return ledPosition; } /** * Sets the position of the gauge threshold led to the given values * @param X * @param Y */ @Override public void setLedPosition(final double X, final double Y) { ledPosition.setLocation(X, Y); repaint(getInnerBounds()); } /** * Sets the position of the gauge threshold led to the given values * @param LED_POSITION */ public void setLedPosition(final Point2D LED_POSITION) { ledPosition.setLocation(LED_POSITION); repaint(getInnerBounds()); } /** * Returns the current position of the gauge user led * @return the current position of the gauge user led */ @Override public Point2D getUserLedPosition() { return userLedPosition; } /** * Sets the position of the gauge user led to the given values * @param X * @param Y */ @Override public void setUserLedPosition(final double X, final double Y) { userLedPosition.setLocation(X, Y); repaint(getInnerBounds()); } /** * Sets the position of the gauge threshold led to the given values * @param USER_LED_POSITION */ public void setUserLedPosition(final Point2D USER_LED_POSITION) { userLedPosition.setLocation(USER_LED_POSITION); repaint(getInnerBounds()); } /** * Returns the direction of the tickmark labels. * CLOCKWISE is the standard and counts the labels like on a analog clock * COUNTER_CLOCKWISE could be useful for gauges like Radial1Square in SOUTH_EAST orientation * @return the direction of the tickmark counting */ public Direction getTickmarkDirection() { return tickmarkDirection; } /** * Sets the direction of the tickmark label counting. * CLOCKWISE will count in clockwise direction * COUNTER_CLOCKWISE will count the opposite way * @param DIRECTION */ public void setTickmarkDirection(final Direction DIRECTION) { this.tickmarkDirection = DIRECTION; init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the type of the pointer * FG_TYPE1 (standard version) or FG_TYPE2 * @return the type of the pointer */ public PointerType getPointerType() { return getModel().getPointerType(); } /** * Sets the type of the pointer * @param POINTER_TYPE type of the pointer * PointerType.TYPE1 (default) * PointerType.TYPE2 * PointerType.TYPE3 * PointerType.TYPE4 */ public void setPointerType(final PointerType POINTER_TYPE) { getModel().setPointerType(POINTER_TYPE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the color of the pointer * @return the selected color of the pointer */ public ColorDef getPointerColor() { return getModel().getPointerColor(); } /** * Sets the color of the pointer * @param POINTER_COLOR */ public void setPointerColor(final ColorDef POINTER_COLOR) { getModel().setPointerColor(POINTER_COLOR); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns true if the pointer shadow is visible * @return true if the pointer shadow is visible */ public boolean isPointerShadowVisible() { return getModel().isPointerShadowVisible(); } /** * Enables/disables the pointer shadow * @param POINTER_SHADOW_VISIBLE */ public void setPointerShadowVisible(final boolean POINTER_SHADOW_VISIBLE) { getModel().setPointerShadowVisible(POINTER_SHADOW_VISIBLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the color from which the custom pointer color will be calculated * @return the color from which the custom pointer color will be calculated */ public Color getCustomPointerColor() { return getModel().getCustomPointerColor(); } /** * Sets the color from which the custom pointer color is calculated * @param COLOR */ public void setCustomPointerColor(final Color COLOR) { getModel().setCustomPointerColorObject(new CustomColorDef(COLOR)); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the object that represents the custom pointer color * @return the object that represents the custom pointer color */ public CustomColorDef getCustomPointerColorObject() { return getModel().getCustomPointerColorObject(); } /** * Returns the type of the knob * @return the type of the knob */ public KnobType getKnobType() { return getModel().getKnobType(); } /** * Sets the type of the knob * @param KNOB_TYPE */ public void setKnobType(final KnobType KNOB_TYPE) { getModel().setKnobType(KNOB_TYPE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the style of the center knob of a radial gauge * @return the style of the center knob of a radial gauge */ public KnobStyle getKnobStyle() { return getModel().getKnobStyle(); } /** * Sets the the style of the center knob of a radial gauge * @param KNOB_STYLE */ public void setKnobStyle(final KnobStyle KNOB_STYLE) { getModel().setKnobStyle(KNOB_STYLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the visibility of the lcd display * @return true if the lcd display is visible */ public boolean isLcdVisible() { return getModel().isLcdVisible(); } /** * Enables or disables the visibility of the lcd display * @param LCD_VISIBLE */ public void setLcdVisible(final boolean LCD_VISIBLE) { getModel().setLcdVisible(LCD_VISIBLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns true if the lcd text is visible which is needed for lcd blinking * @return true if the lcd text is visible which is needed for lcd blinking */ public boolean isLcdTextVisible() { return lcdTextVisible; } /** * Returns true if the arc that represents the range of measured values is visible * @return true if the arc that represents the range of measured values is visible */ public boolean isRangeOfMeasuredValuesVisible() { return getModel().isRangeOfMeasuredValuesVisible(); } /** * Enables / disables the visibility of the arc that represents the range of measured values * @param RANGE_OF_MEASURED_VALUES_VISIBLE */ public void setRangeOfMeasuredValuesVisible(final boolean RANGE_OF_MEASURED_VALUES_VISIBLE) { getModel().setRangeOfMeasuredValuesVisible(RANGE_OF_MEASURED_VALUES_VISIBLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public boolean isValueCoupled() { return getModel().isValueCoupled(); } @Override public void setValueCoupled(final boolean VALUE_COUPLED) { getModel().setValueCoupled(VALUE_COUPLED); repaint(getInnerBounds()); } @Override public double getLcdValue() { return getModel().getLcdValue(); } @Override public void setLcdValue(final double LCD_VALUE) { if (getLcdNumberSystem() != NumberSystem.DEC) { if (LCD_VALUE < 0) { setLcdNumberSystem(NumberSystem.DEC); } } if (!isLogScale()) { lcdValue = LCD_VALUE; } else { if (LCD_VALUE > 1) { lcdValue = LCD_VALUE; } else { lcdValue = 1; } } getModel().setLcdValue(lcdValue); repaint(getLcdBounds()); } @Override public void setLcdValueAnimated(final double LCD_VALUE) { if (lcdTimeline.getState() == Timeline.TimelineState.PLAYING_FORWARD || lcdTimeline.getState() == Timeline.TimelineState.PLAYING_REVERSE) { lcdTimeline.abort(); } lcdTimeline = new Timeline(this); lcdTimeline.addPropertyToInterpolate("lcdValue", this.lcdValue, LCD_VALUE); lcdTimeline.setEase(new Spline(0.5f)); lcdTimeline.play(); } @Override public double getLcdThreshold() { return getModel().getLcdThreshold(); } @Override public void setLcdThreshold(final double LCD_THRESHOLD) { getModel().setLcdThreshold(LCD_THRESHOLD); if (getModel().isLcdThresholdVisible()) { repaint(getInnerBounds()); } } @Override public boolean isLcdThresholdVisible() { return getModel().isLcdThresholdVisible(); } @Override public void setLcdThresholdVisible(final boolean LCD_THRESHOLD_VISIBLE) { getModel().setLcdThresholdVisible(LCD_THRESHOLD_VISIBLE); repaint(getInnerBounds()); } @Override public boolean isLcdThresholdBehaviourInverted() { return getModel().isLcdThresholdBehaviourInverted(); } @Override public void setLcdThresholdBehaviourInverted(final boolean LCD_THRESHOLD_BEHAVIOUR_INVERTED) { getModel().setLcdThresholdBehaviourInverted(LCD_THRESHOLD_BEHAVIOUR_INVERTED); repaint(getInnerBounds()); } @Override public boolean isLcdBlinking() { return getModel().isLcdBlinking(); } @Override public void setLcdBlinking(final boolean LCD_BLINKING) { if (LCD_BLINKING) { LCD_BLINKING_TIMER.start(); } else { LCD_BLINKING_TIMER.stop(); lcdTextVisible = true; } getModel().setLcdBlinking(LCD_BLINKING); } @Override public String getLcdUnitString() { return lcdUnitString; } @Override public void setLcdUnitString(final String UNIT_STRING) { this.lcdUnitString = UNIT_STRING; init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public boolean isLcdUnitStringVisible() { return getModel().isLcdUnitStringVisible(); } @Override public void setLcdUnitStringVisible(final boolean UNIT_STRING_VISIBLE) { getModel().setLcdUnitStringVisible(UNIT_STRING_VISIBLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public boolean isDigitalFont() { return getModel().isDigitalFontEnabled(); } @Override public void setDigitalFont(final boolean DIGITAL_FONT) { getModel().setDigitalFontEnabled(DIGITAL_FONT); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public boolean isCustomLcdUnitFontEnabled() { return getModel().isCustomLcdUnitFontEnabled(); } @Override public void setCustomLcdUnitFontEnabled(final boolean USE_CUSTOM_LCD_UNIT_FONT) { getModel().setCustomLcdUnitFontEnabled(USE_CUSTOM_LCD_UNIT_FONT); repaint(getInnerBounds()); } @Override public Font getCustomLcdUnitFont() { return getModel().getCustomLcdUnitFont(); } @Override public void setCustomLcdUnitFont(final Font CUSTOM_LCD_UNIT_FONT) { getModel().setCustomLcdUnitFont(CUSTOM_LCD_UNIT_FONT); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public int getLcdDecimals() { return getModel().getLcdDecimals(); } @Override public void setLcdDecimals(final int DECIMALS) { getModel().setLcdDecimals(DECIMALS); repaint(getInnerBounds()); } @Override public LcdColor getLcdColor() { return getModel().getLcdColor(); } @Override public void setLcdColor(final LcdColor LCD_COLOR) { getModel().setLcdColor(LCD_COLOR); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public Paint getCustomLcdBackground() { return getModel().getCustomLcdBackground(); } @Override public void setCustomLcdBackground(final Paint CUSTOM_LCD_BACKGROUND) { getModel().setCustomLcdBackground(CUSTOM_LCD_BACKGROUND); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public Paint createCustomLcdBackgroundPaint(final Color[] LCD_COLORS) { return null; } @Override public boolean isLcdBackgroundVisible() { return getModel().isLcdBackgroundVisible(); } @Override public void setLcdBackgroundVisible(final boolean LCD_BACKGROUND_VISIBLE) { getModel().setLcdBackgroundVisible(LCD_BACKGROUND_VISIBLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public Color getCustomLcdForeground() { return getModel().getCustomLcdForeground(); } @Override public void setCustomLcdForeground(final Color CUSTOM_LCD_FOREGROUND) { getModel().setCustomLcdForeground(CUSTOM_LCD_FOREGROUND); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } @Override public String formatLcdValue(final double VALUE) { final StringBuilder DEC_BUFFER = new StringBuilder(16); DEC_BUFFER.append("0"); if (getModel().getLcdDecimals() > 0) { DEC_BUFFER.append("."); } for (int i = 0; i < getModel().getLcdDecimals(); i++) { DEC_BUFFER.append("0"); } if (getModel().isLcdScientificFormatEnabled()) { DEC_BUFFER.append("E0"); } DEC_BUFFER.trimToSize(); final java.text.DecimalFormat DEC_FORMAT = new java.text.DecimalFormat(DEC_BUFFER.toString(), new java.text.DecimalFormatSymbols(java.util.Locale.US)); return DEC_FORMAT.format(VALUE); } @Override public boolean isLcdScientificFormat() { return getModel().isLcdScientificFormatEnabled(); } @Override public void setLcdScientificFormat(boolean LCD_SCIENTIFIC_FORMAT) { getModel().setLcdScientificFormatEnabled(LCD_SCIENTIFIC_FORMAT); repaint(getInnerBounds()); } @Override public Font getLcdValueFont() { return getModel().getLcdValueFont(); } @Override public void setLcdValueFont(final Font LCD_VALUE_FONT) { getModel().setLcdValueFont(LCD_VALUE_FONT); repaint(getInnerBounds()); } @Override public Font getLcdUnitFont() { return getModel().getLcdUnitFont(); } @Override public void setLcdUnitFont(final Font LCD_UNIT_FONT) { getModel().setLcdUnitFont(LCD_UNIT_FONT); repaint(getInnerBounds()); } @Override public Font getLcdInfoFont() { return getModel().getLcdInfoFont(); } @Override public void setLcdInfoFont(final Font LCD_INFO_FONT) { getModel().setLcdInfoFont(LCD_INFO_FONT); repaint(getInnerBounds()); } @Override public String getLcdInfoString() { return lcdInfoString; } @Override public void setLcdInfoString(final String LCD_INFO_STRING) { lcdInfoString = LCD_INFO_STRING; repaint(getInnerBounds()); } @Override public NumberSystem getLcdNumberSystem() { return getModel().getNumberSystem(); } @Override public void setLcdNumberSystem(final NumberSystem NUMBER_SYSTEM) { getModel().setNumberSystem(NUMBER_SYSTEM); switch (NUMBER_SYSTEM) { case HEX: lcdInfoString = "hex"; break; case OCT: lcdInfoString = "oct"; break; case DEC: default: lcdInfoString = ""; break; } repaint(getInnerBounds()); } /* @Override public abstract Rectangle getLcdBounds(); */ @Override public void toggleDesign() { if (getActiveDesign().equals(getDesign1())) { setActiveDesign(getDesign2()); } else { setActiveDesign(getDesign1()); } } /** * Returns true if the glow indicator is visible * @return true if the glow indicator is visible */ @Override public boolean isGlowVisible() { return getModel().isGlowVisible(); } /** * Enables / disables the glow indicator * @param GLOW_VISIBLE */ public void setGlowVisible(final boolean GLOW_VISIBLE) { getModel().setGlowVisible(GLOW_VISIBLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the color that will be used for the glow indicator * @return the color that will be used for the glow indicator */ public Color getGlowColor() { return getModel().getGlowColor(); } /** * Sets the color that will be used for the glow indicator * @param GLOW_COLOR */ public void setGlowColor(final Color GLOW_COLOR) { getModel().setGlowColor(GLOW_COLOR); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns true if the glow indicator is glowing * @return true if the glow indicator is glowing */ public boolean isGlowing() { return getModel().isGlowing(); } /** * Enables / disables the glowing of the glow indicator * @param GLOWING */ public void setGlowing(final boolean GLOWING) { getModel().setGlowing(GLOWING); repaint(getInnerBounds()); } /** * Returns the color of the small outer frame of the gauge * @return the color of the small outer frame of the gauge */ public Paint getOuterFrameColor() { return FRAME_FACTORY.getOuterFrameColor(); } /** * Sets the color of the small outer frame of the gauge * @param OUTER_FRAME_COLOR */ public void setOuterFrameColor(final Paint OUTER_FRAME_COLOR) { FRAME_FACTORY.setOuterFrameColor(OUTER_FRAME_COLOR); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the color of the small inner frame of the gauge * @return the color of the small inner frame of the gauge */ public Paint getInnerFrameColor() { return FRAME_FACTORY.getInnerFrameColor(); } /** * Sets the color of the small inner frame of the gauge * @param INNER_FRAME_COLOR */ public void setInnerFrameColor(final Paint INNER_FRAME_COLOR) { FRAME_FACTORY.setInnerFrameColor(INNER_FRAME_COLOR); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns true if the posts of the radial gauges are visible * @return true if the posts of the radial gauges are visible */ public boolean getPostsVisible() { return getModel().getPostsVisible(); } /** * Enables/disables the visibility of the posts of the radial gauges * @param POSTS_VISIBLE */ public void setPostsVisible(final boolean POSTS_VISIBLE) { getModel().setPostsVisible(POSTS_VISIBLE); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns the orientation of the tickmark labels * @return the orientation of the tickmark labels */ public TicklabelOrientation getTicklabelOrientation() { return getModel().getTicklabelOrientation(); } /** * Sets the orientation of the tickmark labels * @param TICKLABEL_ORIENTATION */ public void setTicklabelOrientation(final TicklabelOrientation TICKLABEL_ORIENTATION) { getModel().setTicklabelOrienatation(TICKLABEL_ORIENTATION); init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns true if the sections will be filled with a transparent color * @return true if the sections will be filled with a transparent color */ public boolean isTransparentSectionsEnabled() { return transparentSectionsEnabled; } /** * Enables / disables the usage of a transparent color for filling sections * @param TRANSPARENT_SECTIONS_ENABLED */ public void setTransparentSectionsEnabled(final boolean TRANSPARENT_SECTIONS_ENABLED) { transparentSectionsEnabled = TRANSPARENT_SECTIONS_ENABLED; init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns true if the areas will be filled with a transparent color * @return true if the areas will be filled with a transparent color */ public boolean isTransparentAreasEnabled() { return transparentAreasEnabled; } /** * Enables / disables the usage of a transparent color for filling areas * @param TRANSPARENT_AREAS_ENABLED */ public void setTransparentAreasEnabled(final boolean TRANSPARENT_AREAS_ENABLED) { transparentAreasEnabled = TRANSPARENT_AREAS_ENABLED; init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } /** * Returns true if the sections are wider * @return true if the sections are wider */ public boolean isExpandedSectionsEnabled() { return expandedSectionsEnabled; } /** * Enables / disables the use of wider sections * @param EXPANDED_SECTIONS_ENABLED */ public void setExpandedSectionsEnabled(final boolean EXPANDED_SECTIONS_ENABLED) { expandedSectionsEnabled = EXPANDED_SECTIONS_ENABLED; init(getInnerBounds().width, getInnerBounds().height); repaint(getInnerBounds()); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Image related"> /** * Returns a radial gradient paint that will be used as overlay for the track or section image * to achieve some kind of a 3d effect. * @param WIDTH * @param RADIUS_FACTOR : 0.38f for the standard radial gauge * @return a radial gradient paint that will be used as overlay for the track or section image */ protected RadialGradientPaint createSection3DEffectGradient(final int WIDTH, final float RADIUS_FACTOR) { final float[] FRACTIONS; final Color[] COLORS; if (isExpandedSectionsEnabled()) { FRACTIONS = new float[]{ 0.0f, 0.7f, 0.75f, 0.96f, 1.0f }; COLORS = new Color[]{ new Color(0.0f, 0.0f, 0.0f, 1.0f), new Color(0.9f, 0.9f, 0.9f, 0.2f), new Color(1.0f, 1.0f, 1.0f, 0.5f), new Color(0.1843137255f, 0.1843137255f, 0.1843137255f, 0.3f), new Color(0.0f, 0.0f, 0.0f, 0.2f) }; } else { FRACTIONS = new float[]{ 0.0f, 0.89f, 0.955f, 1.0f }; COLORS = new Color[]{ new Color(0.0f, 0.0f, 0.0f, 0.0f), new Color(0.0f, 0.0f, 0.0f, 0.3f), new Color(1.0f, 1.0f, 1.0f, 0.6f), new Color(0.0f, 0.0f, 0.0f, 0.4f) }; } final Point2D GRADIENT_CENTER = new Point2D.Double(WIDTH / 2.0, WIDTH / 2.0); return new RadialGradientPaint(GRADIENT_CENTER, WIDTH * RADIUS_FACTOR, FRACTIONS, COLORS); } /** * Returns a radial gradient paint that will be used as overlay for the track or area image * to achieve some kind of a 3d effect. * @param WIDTH * @param RADIUS_FACTOR * @return a radial gradient paint that will be used as overlay for the track or area image */ protected RadialGradientPaint createArea3DEffectGradient(final int WIDTH, final float RADIUS_FACTOR) { final float[] FRACTIONS; final Color[] COLORS; FRACTIONS = new float[]{ 0.0f, 0.6f, 1.0f }; COLORS = new Color[]{ new Color(1.0f, 1.0f, 1.0f, 0.75f), new Color(1.0f, 1.0f, 1.0f, 0.0f), new Color(0.0f, 0.0f, 0.0f, 0.3f) }; final Point2D GRADIENT_CENTER = new Point2D.Double(WIDTH / 2.0, WIDTH / 2.0); return new RadialGradientPaint(GRADIENT_CENTER, WIDTH * RADIUS_FACTOR, FRACTIONS, COLORS); } /** * Returns the frame image with the currently active framedesign * with the given width and the current frame type. * @param WIDTH * @return buffered image containing the frame in the active frame design */ protected BufferedImage create_FRAME_Image(final int WIDTH) { switch (getFrameType()) { case ROUND: return FRAME_FACTORY.createRadialFrame(WIDTH, getFrameDesign(), getCustomFrameDesign(), getFrameBaseColor(), isFrameBaseColorEnabled(), getFrameEffect()); case SQUARE: return FRAME_FACTORY.createLinearFrame(WIDTH, getFrameDesign(), getCustomFrameDesign(), getFrameBaseColor(), isFrameBaseColorEnabled(), getFrameEffect()); default: return FRAME_FACTORY.createRadialFrame(WIDTH, getFrameDesign(), getCustomFrameDesign(), getFrameBaseColor(), isFrameBaseColorEnabled(), getFrameEffect()); } } /** * Returns the background image with the currently active backgroundcolor * with the given width without a title and a unit string. * @param WIDTH * @return the background image that is used */ protected BufferedImage create_BACKGROUND_Image(final int WIDTH) { return create_BACKGROUND_Image(WIDTH, "", ""); } /** * Returns the background image with the currently active backgroundcolor * with the given width, title and unitstring. * @param WIDTH * @param TITLE * @param UNIT_STRING * @return buffered image containing the background with the selected background design */ protected BufferedImage create_BACKGROUND_Image(final int WIDTH, final String TITLE, final String UNIT_STRING) { return create_BACKGROUND_Image(WIDTH, TITLE, UNIT_STRING, null); } /** * Returns the background image with the currently active backgroundcolor * with the given width, title and unitstring. * @param WIDTH * @param TITLE * @param UNIT_STRING * @param image * @return buffered image containing the background with the selected background design */ protected BufferedImage create_BACKGROUND_Image(final int WIDTH, final String TITLE, final String UNIT_STRING, BufferedImage image) { if (WIDTH <= 0) { return null; } if (image == null) { image = UTIL.createImage(WIDTH, WIDTH, Transparency.TRANSLUCENT); } final Graphics2D G2 = image.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final int IMAGE_WIDTH = image.getWidth(); final int IMAGE_HEIGHT = image.getHeight(); switch (getFrameType()) { case SQUARE: BACKGROUND_FACTORY.createLinearBackground(WIDTH, WIDTH, getBackgroundColor(), getModel().getCustomBackground(), getModel().getTextureColor(), image); break; case ROUND: default: BACKGROUND_FACTORY.createRadialBackground(WIDTH, getBackgroundColor(), getModel().getCustomBackground(), getModel().getTextureColor(), image); break; } // Draw the custom layer if selected if (isCustomLayerVisible()) { G2.drawImage(UTIL.getScaledInstance(getCustomLayer(), IMAGE_WIDTH, IMAGE_HEIGHT, RenderingHints.VALUE_INTERPOLATION_BICUBIC), 0, 0, null); } final FontRenderContext RENDER_CONTEXT = new FontRenderContext(null, true, true); if (!TITLE.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getModel().getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getModel().getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout TITLE_LAYOUT = new TextLayout(TITLE, G2.getFont(), RENDER_CONTEXT); final Rectangle2D TITLE_BOUNDARY = TITLE_LAYOUT.getBounds(); G2.drawString(TITLE, (float) ((IMAGE_WIDTH - TITLE_BOUNDARY.getWidth()) / 2.0), 0.3f * IMAGE_HEIGHT + TITLE_LAYOUT.getAscent() - TITLE_LAYOUT.getDescent()); } if (!UNIT_STRING.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getModel().getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getModel().getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout UNIT_LAYOUT = new TextLayout(UNIT_STRING, G2.getFont(), RENDER_CONTEXT); final Rectangle2D UNIT_BOUNDARY = UNIT_LAYOUT.getBounds(); G2.drawString(UNIT_STRING, (float) ((IMAGE_WIDTH - UNIT_BOUNDARY.getWidth()) / 2.0), 0.38f * IMAGE_HEIGHT + UNIT_LAYOUT.getAscent() - UNIT_LAYOUT.getDescent()); } G2.dispose(); return image; } /** * Returns an image that simulates a glowing ring which could be used to visualize * a state of the gauge by a color. The LED might be too small if you are not in front * of the screen and so one could see the current state more easy. * @param WIDTH * @param GLOW_COLOR * @param ON * @param GAUGE_TYPE * @param KNOBS * @param ORIENTATION * @return an image that simulates a glowing ring */ protected BufferedImage create_GLOW_Image(final int WIDTH, final Color GLOW_COLOR, final boolean ON, final GaugeType GAUGE_TYPE, final boolean KNOBS, final Orientation ORIENTATION) { switch (getFrameType()) { case ROUND: return GLOW_FACTORY.createRadialGlow(WIDTH, GLOW_COLOR, ON, GAUGE_TYPE, KNOBS, ORIENTATION); case SQUARE: return GLOW_FACTORY.createLinearGlow(WIDTH, WIDTH, GLOW_COLOR, ON); default: return GLOW_FACTORY.createRadialGlow(WIDTH, GLOW_COLOR, ON, GAUGE_TYPE, KNOBS, ORIENTATION); } } /** * Returns the image with the given title and unitstring. * @param WIDTH * @param TITLE * @param UNIT_STRING * @return the image with the given title and unitstring. */ protected BufferedImage create_TITLE_Image(final int WIDTH, final String TITLE, final String UNIT_STRING) { return create_TITLE_Image(WIDTH, TITLE, UNIT_STRING, null); } /** * Returns the image with the given title and unitstring. * @param WIDTH * @param TITLE * @param UNIT_STRING * @param image * @return the image with the given title and unitstring. */ protected BufferedImage create_TITLE_Image(final int WIDTH, final String TITLE, final String UNIT_STRING, BufferedImage image) { if (WIDTH <= 0) { return UTIL.createImage(1, 1, Transparency.TRANSLUCENT); } if (image == null) { image = UTIL.createImage(WIDTH, WIDTH, Transparency.TRANSLUCENT); } final Graphics2D G2 = image.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final int IMAGE_WIDTH = image.getWidth(); final int IMAGE_HEIGHT = image.getHeight(); final FontRenderContext RENDER_CONTEXT = new FontRenderContext(null, true, true); if (!TITLE.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), getTitleAndUnitFont().getStyle(), getTitleAndUnitFont().getSize())); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout TITLE_LAYOUT = new TextLayout(TITLE, G2.getFont(), RENDER_CONTEXT); final Rectangle2D TITLE_BOUNDARY = TITLE_LAYOUT.getBounds(); G2.drawString(TITLE, (float) ((IMAGE_WIDTH - TITLE_BOUNDARY.getWidth()) / 2.0), 0.3f * IMAGE_HEIGHT + TITLE_LAYOUT.getAscent() - TITLE_LAYOUT.getDescent()); } if (!UNIT_STRING.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), getTitleAndUnitFont().getStyle(), getTitleAndUnitFont().getSize())); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout UNIT_LAYOUT = new TextLayout(UNIT_STRING, G2.getFont(), RENDER_CONTEXT); final Rectangle2D UNIT_BOUNDARY = UNIT_LAYOUT.getBounds(); G2.drawString(UNIT_STRING, (float) ((IMAGE_WIDTH - UNIT_BOUNDARY.getWidth()) / 2.0), 0.37f * IMAGE_HEIGHT + UNIT_LAYOUT.getAscent() - UNIT_LAYOUT.getDescent()); } G2.dispose(); return image; } /** * Returns the image with the given lcd color. * @param WIDTH * @param HEIGHT * @param LCD_COLOR * @param CUSTOM_LCD_BACKGROUND * @return buffered image containing the lcd with the selected lcd color */ protected BufferedImage create_LCD_Image(final int WIDTH, final int HEIGHT, final LcdColor LCD_COLOR, final Paint CUSTOM_LCD_BACKGROUND) { return createLcdImage(new Rectangle2D.Double(0, 0, WIDTH, HEIGHT), LCD_COLOR, CUSTOM_LCD_BACKGROUND, null); } /** * Returns the image with the given lcd color. * @param BOUNDS * @param LCD_COLOR * @param CUSTOM_LCD_BACKGROUND * @param IMAGE * @return buffered image containing the lcd with the selected lcd color */ protected BufferedImage createLcdImage(final Rectangle2D BOUNDS, final LcdColor LCD_COLOR, final Paint CUSTOM_LCD_BACKGROUND, final BufferedImage IMAGE) { return LCD_FACTORY.create_LCD_Image(BOUNDS, LCD_COLOR, CUSTOM_LCD_BACKGROUND, IMAGE); } protected BufferedImage create_TRACK_Image(final int WIDTH, final double FREE_AREA_ANGLE, final double ROTATION_OFFSET, final double MIN_VALUE, final double MAX_VALUE, final double ANGLE_STEP, final double TRACK_START, final double TRACK_SECTION, final double TRACK_STOP, final Color TRACK_START_COLOR, final Color TRACK_SECTION_COLOR, final Color TRACK_STOP_COLOR, final float RADIUS_FACTOR, final Point2D CENTER, final Direction DIRECTION, final Point2D OFFSET) { return create_TRACK_Image(WIDTH, FREE_AREA_ANGLE, ROTATION_OFFSET, MIN_VALUE, MAX_VALUE, ANGLE_STEP, TRACK_START, TRACK_SECTION, TRACK_STOP, TRACK_START_COLOR, TRACK_SECTION_COLOR, TRACK_STOP_COLOR, RADIUS_FACTOR, CENTER, DIRECTION, OFFSET, null); } protected BufferedImage create_TRACK_Image(final int WIDTH, final double FREE_AREA_ANGLE, final double ROTATION_OFFSET, final double MIN_VALUE, final double MAX_VALUE, final double ANGLE_STEP, final double TRACK_START, final double TRACK_SECTION, final double TRACK_STOP, final Color TRACK_START_COLOR, final Color TRACK_SECTION_COLOR, final Color TRACK_STOP_COLOR, final float RADIUS_FACTOR, final Point2D CENTER, final Direction DIRECTION, final Point2D OFFSET, BufferedImage image) { if (WIDTH <= 0) { return UTIL.createImage(1, 1, Transparency.TRANSLUCENT); } if (image == null) { image = UTIL.createImage(WIDTH, WIDTH, Transparency.TRANSLUCENT); } final Graphics2D G2 = image.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); G2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); final int IMAGE_WIDTH = image.getWidth(); //final int IMAGE_HEIGHT = IMAGE.getHeight(); if (OFFSET != null) { G2.translate(OFFSET.getX(), OFFSET.getY()); } // Definitions float lineWidth; switch (getGaugeType()) { case TYPE1: lineWidth = (float) Math.toDegrees(Math.PI / 2.0 - FREE_AREA_ANGLE) * 0.00167f * WIDTH * 0.0067f; break; case TYPE2: lineWidth = (float) Math.toDegrees(Math.PI - FREE_AREA_ANGLE) * 0.00167f * WIDTH * 0.0067f; break; case TYPE3: lineWidth = (float) Math.toDegrees(1.5 * Math.PI - FREE_AREA_ANGLE) * 0.00167f * WIDTH * 0.0067f; break; case TYPE4: lineWidth = (float) Math.toDegrees(2.0 * Math.PI - FREE_AREA_ANGLE) * 0.00167f * WIDTH * 0.0067f; break; default: lineWidth = (float) Math.toDegrees(2.0 * Math.PI - FREE_AREA_ANGLE) * 0.00167f * WIDTH * 0.0067f; break; } if (lineWidth < 0.25f) { lineWidth = 0.25f; } final BasicStroke STD_STROKE = new BasicStroke(lineWidth, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL); final int TRACK_WIDTH = (int) (0.035 * WIDTH); final float RADIUS = IMAGE_WIDTH * RADIUS_FACTOR; // Define the lines final Point2D INNER_POINT = new Point2D.Double(); final Point2D OUTER_POINT = new Point2D.Double(); final Line2D TICK = new Line2D.Double(); double sinValue; double cosValue; // Calculate the start, section and stop values dependend of the ticklabel direction final double TRACK_START_ANGLE; final double TRACK_SECTION_ANGLE; final double TRACK_STOP_ANGLE; final double ALPHA_START; final double ALPHA_SECTION; final double ALPHA_STOP; Color currentColor; switch (DIRECTION) { case COUNTER_CLOCKWISE: TRACK_START_ANGLE = ((MAX_VALUE - TRACK_STOP) * ANGLE_STEP); TRACK_SECTION_ANGLE = ((MAX_VALUE - TRACK_SECTION) * ANGLE_STEP); TRACK_STOP_ANGLE = ((MAX_VALUE - TRACK_START) * ANGLE_STEP); ALPHA_START = -ROTATION_OFFSET - (FREE_AREA_ANGLE / 2.0) - TRACK_START_ANGLE; ALPHA_SECTION = -ROTATION_OFFSET - (FREE_AREA_ANGLE / 2.0) - TRACK_SECTION_ANGLE; ALPHA_STOP = -ROTATION_OFFSET - (FREE_AREA_ANGLE / 2.0) - TRACK_STOP_ANGLE; currentColor = TRACK_STOP_COLOR; break; case CLOCKWISE: default: TRACK_START_ANGLE = (TRACK_START * ANGLE_STEP); TRACK_SECTION_ANGLE = (TRACK_SECTION * ANGLE_STEP); TRACK_STOP_ANGLE = (TRACK_STOP * ANGLE_STEP); ALPHA_START = -ROTATION_OFFSET - (FREE_AREA_ANGLE / 2.0) - TRACK_START_ANGLE + (MIN_VALUE * ANGLE_STEP); ALPHA_SECTION = -ROTATION_OFFSET - (FREE_AREA_ANGLE / 2.0) - TRACK_SECTION_ANGLE + (MIN_VALUE * ANGLE_STEP); ALPHA_STOP = -ROTATION_OFFSET - (FREE_AREA_ANGLE / 2.0) - TRACK_STOP_ANGLE + (MIN_VALUE * ANGLE_STEP); currentColor = TRACK_START_COLOR; break; } // Define the stepsize between each line of the track so that it will work on small ranges like on large ranges final double RANGE_FACTOR = 1000 / (MAX_VALUE - MIN_VALUE) < 10 ? 10 : 1000 / (MAX_VALUE - MIN_VALUE); final double FRACTION_STEP = 1 / RANGE_FACTOR; G2.setStroke(STD_STROKE); float fraction = 0; // Draw track from TRACK_START to TRACK_SECTION for (double alpha = ALPHA_START; Double.compare(alpha, ALPHA_SECTION) >= 0; alpha -= (ANGLE_STEP / RANGE_FACTOR), fraction += FRACTION_STEP) { sinValue = Math.sin(alpha); cosValue = Math.cos(alpha); switch (DIRECTION) { case CLOCKWISE: currentColor = UTIL.getColorFromFraction(TRACK_START_COLOR, TRACK_SECTION_COLOR, (int) (TRACK_SECTION - TRACK_START), (int) (fraction)); break; case COUNTER_CLOCKWISE: currentColor = UTIL.getColorFromFraction(TRACK_STOP_COLOR, TRACK_SECTION_COLOR, (int) (TRACK_STOP - TRACK_SECTION), (int) (fraction)); break; } G2.setColor(currentColor); INNER_POINT.setLocation(CENTER.getX() + (RADIUS - TRACK_WIDTH) * sinValue, CENTER.getY() + (RADIUS - TRACK_WIDTH) * cosValue); OUTER_POINT.setLocation(CENTER.getX() + RADIUS * sinValue, CENTER.getY() + RADIUS * cosValue); TICK.setLine(INNER_POINT, OUTER_POINT); G2.draw(TICK); } // Draw track from TRACK_SECTION to TRACK_STOP fraction = 0; for (double alpha = ALPHA_SECTION; Double.compare(alpha, ALPHA_STOP) >= 0; alpha -= (ANGLE_STEP / RANGE_FACTOR), fraction += FRACTION_STEP) { sinValue = Math.sin(alpha); cosValue = Math.cos(alpha); switch (DIRECTION) { case CLOCKWISE: currentColor = UTIL.getColorFromFraction(TRACK_SECTION_COLOR, TRACK_STOP_COLOR, (int) (TRACK_STOP - TRACK_SECTION), (int) (fraction)); break; case COUNTER_CLOCKWISE: currentColor = UTIL.getColorFromFraction(TRACK_SECTION_COLOR, TRACK_START_COLOR, (int) (TRACK_SECTION - TRACK_START), (int) (fraction)); break; } G2.setColor(currentColor); INNER_POINT.setLocation(CENTER.getX() + (RADIUS - TRACK_WIDTH) * sinValue, CENTER.getY() + (RADIUS - TRACK_WIDTH) * cosValue); OUTER_POINT.setLocation(CENTER.getX() + RADIUS * sinValue, CENTER.getY() + RADIUS * cosValue); TICK.setLine(INNER_POINT, OUTER_POINT); G2.draw(TICK); } G2.dispose(); return image; } /** * Returns the image of the posts for the pointer * @param WIDTH * @param POSITIONS * @return the post image that is used */ protected BufferedImage create_POSTS_Image(final int WIDTH, final PostPosition... POSITIONS) { return createPostsImage(WIDTH, null, POSITIONS); } /** * Returns the image of the posts for the pointer * @param WIDTH * @param POSITIONS * @param image * @return the post image that is used */ protected BufferedImage createPostsImage(final int WIDTH, BufferedImage image, final PostPosition... POSITIONS) { if (WIDTH <= 0) { return UTIL.createImage(1, 1, Transparency.TRANSLUCENT); } if (image == null) { image = UTIL.createImage(WIDTH, WIDTH, Transparency.TRANSLUCENT); } final Graphics2D G2 = image.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final int IMAGE_WIDTH = image.getWidth(); final int IMAGE_HEIGHT = image.getHeight(); //final BufferedImage CENTER_KNOB = create_KNOB_Image((int) (WIDTH * 0.09)); final BufferedImage SINGLE_POST = create_KNOB_Image((int) Math.ceil(WIDTH * 0.03738316893577576), KnobType.SMALL_STD_KNOB, getModel().getKnobStyle()); List<PostPosition> postPositionList = Arrays.asList(POSITIONS); // Draw center knob if (postPositionList.contains(PostPosition.CENTER)) { switch (getKnobType()) { case SMALL_STD_KNOB: //G2.drawImage(KNOB_FACTORY.create_KNOB_Image((int) Math.ceil(IMAGE_WIDTH * 0.08411216735839844), KnobType.SMALL_STD_KNOB), (int) Math.ceil(IMAGE_WIDTH * 0.4579439163208008), (int) Math.ceil(IMAGE_WIDTH * 0.4579439163208008), null); final Ellipse2D CENTER_KNOB_FRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4579439163208008, IMAGE_HEIGHT * 0.4579439163208008, IMAGE_WIDTH * 0.08411216735839844, IMAGE_HEIGHT * 0.08411216735839844); final Point2D CENTER_KNOB_FRAME_START = new Point2D.Double(0, CENTER_KNOB_FRAME.getBounds2D().getMinY()); final Point2D CENTER_KNOB_FRAME_STOP = new Point2D.Double(0, CENTER_KNOB_FRAME.getBounds2D().getMaxY()); final float[] CENTER_KNOB_FRAME_FRACTIONS = { 0.0f, 0.46f, 1.0f }; final Color[] CENTER_KNOB_FRAME_COLORS = { new Color(180, 180, 180, 255), new Color(63, 63, 63, 255), new Color(40, 40, 40, 255) }; final LinearGradientPaint CENTER_KNOB_FRAME_GRADIENT = new LinearGradientPaint(CENTER_KNOB_FRAME_START, CENTER_KNOB_FRAME_STOP, CENTER_KNOB_FRAME_FRACTIONS, CENTER_KNOB_FRAME_COLORS); G2.setPaint(CENTER_KNOB_FRAME_GRADIENT); G2.fill(CENTER_KNOB_FRAME); final Ellipse2D CENTER_KNOB_MAIN = new Ellipse2D.Double(IMAGE_WIDTH * 0.4672897160053253, IMAGE_HEIGHT * 0.4672897160053253, IMAGE_WIDTH * 0.06542053818702698, IMAGE_HEIGHT * 0.06542053818702698); final Point2D CENTER_KNOB_MAIN_START = new Point2D.Double(0, CENTER_KNOB_MAIN.getBounds2D().getMinY()); final Point2D CENTER_KNOB_MAIN_STOP = new Point2D.Double(0, CENTER_KNOB_MAIN.getBounds2D().getMaxY()); final float[] CENTER_KNOB_MAIN_FRACTIONS = { 0.0f, 0.5f, 1.0f }; final Color[] CENTER_KNOB_MAIN_COLORS; switch (getModel().getKnobStyle()) { case BLACK: CENTER_KNOB_MAIN_COLORS = new Color[]{ new Color(0xBFBFBF), new Color(0x2B2A2F), new Color(0x7D7E80) }; break; case BRASS: CENTER_KNOB_MAIN_COLORS = new Color[]{ new Color(0xDFD0AE), new Color(0x7A5E3E), new Color(0xCFBE9D) }; break; case SILVER: default: CENTER_KNOB_MAIN_COLORS = new Color[]{ new Color(0xD7D7D7), new Color(0x747474), new Color(0xD7D7D7) }; break; } final LinearGradientPaint CENTER_KNOB_MAIN_GRADIENT = new LinearGradientPaint(CENTER_KNOB_MAIN_START, CENTER_KNOB_MAIN_STOP, CENTER_KNOB_MAIN_FRACTIONS, CENTER_KNOB_MAIN_COLORS); G2.setPaint(CENTER_KNOB_MAIN_GRADIENT); G2.fill(CENTER_KNOB_MAIN); final Ellipse2D CENTER_KNOB_INNERSHADOW = new Ellipse2D.Double(IMAGE_WIDTH * 0.4672897160053253, IMAGE_HEIGHT * 0.4672897160053253, IMAGE_WIDTH * 0.06542053818702698, IMAGE_HEIGHT * 0.06542053818702698); final Point2D CENTER_KNOB_INNERSHADOW_CENTER = new Point2D.Double((0.4953271028037383 * IMAGE_WIDTH), (0.49065420560747663 * IMAGE_HEIGHT)); final float[] CENTER_KNOB_INNERSHADOW_FRACTIONS = { 0.0f, 0.75f, 0.76f, 1.0f }; final Color[] CENTER_KNOB_INNERSHADOW_COLORS = { new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), new Color(0, 0, 0, 1), new Color(0, 0, 0, 51) }; final RadialGradientPaint CENTER_KNOB_INNERSHADOW_GRADIENT = new RadialGradientPaint(CENTER_KNOB_INNERSHADOW_CENTER, (float) (0.03271028037383177 * IMAGE_WIDTH), CENTER_KNOB_INNERSHADOW_FRACTIONS, CENTER_KNOB_INNERSHADOW_COLORS); G2.setPaint(CENTER_KNOB_INNERSHADOW_GRADIENT); G2.fill(CENTER_KNOB_INNERSHADOW); break; case BIG_STD_KNOB: //G2.drawImage(KNOB_FACTORY.create_KNOB_Image((int) Math.ceil(IMAGE_WIDTH * 0.1214953362941742), KnobType.BIG_STD_KNOB), (int) Math.ceil(IMAGE_WIDTH * 0.4392523467540741), (int) Math.ceil(IMAGE_WIDTH * 0.4392523467540741), null); final Ellipse2D BIGCENTER_BACKGROUNDFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4392523467540741, IMAGE_HEIGHT * 0.4392523467540741, IMAGE_WIDTH * 0.1214953362941742, IMAGE_HEIGHT * 0.1214953362941742); final Point2D BIGCENTER_BACKGROUNDFRAME_START = new Point2D.Double(0, BIGCENTER_BACKGROUNDFRAME.getBounds2D().getMinY()); final Point2D BIGCENTER_BACKGROUNDFRAME_STOP = new Point2D.Double(0, BIGCENTER_BACKGROUNDFRAME.getBounds2D().getMaxY()); final float[] BIGCENTER_BACKGROUNDFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] BIGCENTER_BACKGROUNDFRAME_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGCENTER_BACKGROUNDFRAME_COLORS = new Color[]{ new Color(129, 133, 136, 255), new Color(61, 61, 73, 255) }; break; case BRASS: BIGCENTER_BACKGROUNDFRAME_COLORS = new Color[]{ new Color(143, 117, 80, 255), new Color(100, 76, 49, 255) }; break; case SILVER: default: BIGCENTER_BACKGROUNDFRAME_COLORS = new Color[]{ new Color(152, 152, 152, 255), new Color(118, 121, 126, 255) }; break; } final LinearGradientPaint BIGCENTER_BACKGROUNDFRAME_GRADIENT = new LinearGradientPaint(BIGCENTER_BACKGROUNDFRAME_START, BIGCENTER_BACKGROUNDFRAME_STOP, BIGCENTER_BACKGROUNDFRAME_FRACTIONS, BIGCENTER_BACKGROUNDFRAME_COLORS); G2.setPaint(BIGCENTER_BACKGROUNDFRAME_GRADIENT); G2.fill(BIGCENTER_BACKGROUNDFRAME); final Ellipse2D BIGCENTER_BACKGROUND = new Ellipse2D.Double(IMAGE_WIDTH * 0.44392523169517517, IMAGE_HEIGHT * 0.44392523169517517, IMAGE_WIDTH * 0.11214950680732727, IMAGE_HEIGHT * 0.11214950680732727); final Point2D BIGCENTER_BACKGROUND_START = new Point2D.Double(0, BIGCENTER_BACKGROUND.getBounds2D().getMinY()); final Point2D BIGCENTER_BACKGROUND_STOP = new Point2D.Double(0, BIGCENTER_BACKGROUND.getBounds2D().getMaxY()); final float[] BIGCENTER_BACKGROUND_FRACTIONS = { 0.0f, 1.0f }; final Color[] BIGCENTER_BACKGROUND_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGCENTER_BACKGROUND_COLORS = new Color[]{ new Color(26, 27, 32, 255), new Color(96, 97, 102, 255) }; break; case BRASS: BIGCENTER_BACKGROUND_COLORS = new Color[]{ new Color(98, 75, 49, 255), new Color(149, 109, 54, 255) }; break; case SILVER: default: BIGCENTER_BACKGROUND_COLORS = new Color[]{ new Color(118, 121, 126, 255), new Color(191, 191, 191, 255) }; break; } final LinearGradientPaint BIGCENTER_BACKGROUND_GRADIENT = new LinearGradientPaint(BIGCENTER_BACKGROUND_START, BIGCENTER_BACKGROUND_STOP, BIGCENTER_BACKGROUND_FRACTIONS, BIGCENTER_BACKGROUND_COLORS); G2.setPaint(BIGCENTER_BACKGROUND_GRADIENT); G2.fill(BIGCENTER_BACKGROUND); final Ellipse2D BIGCENTER_FOREGROUNDFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4532710313796997, IMAGE_HEIGHT * 0.4532710313796997, IMAGE_WIDTH * 0.09345793724060059, IMAGE_HEIGHT * 0.09345793724060059); final Point2D BIGCENTER_FOREGROUNDFRAME_START = new Point2D.Double(0, BIGCENTER_FOREGROUNDFRAME.getBounds2D().getMinY()); final Point2D BIGCENTER_FOREGROUNDFRAME_STOP = new Point2D.Double(0, BIGCENTER_FOREGROUNDFRAME.getBounds2D().getMaxY()); final float[] BIGCENTER_FOREGROUNDFRAME_FRACTIONS = { 0.0f, 0.47f, 1.0f }; final Color[] BIGCENTER_FOREGROUNDFRAME_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGCENTER_FOREGROUNDFRAME_COLORS = new Color[]{ new Color(191, 191, 191, 255), new Color(56, 57, 61, 255), new Color(143, 144, 146, 255) }; break; case BRASS: BIGCENTER_FOREGROUNDFRAME_COLORS = new Color[]{ new Color(147, 108, 54, 255), new Color(82, 66, 50, 255), new Color(147, 108, 54, 255) }; break; case SILVER: default: BIGCENTER_FOREGROUNDFRAME_COLORS = new Color[]{ new Color(191, 191, 191, 255), new Color(116, 116, 116, 255), new Color(143, 144, 146, 255) }; break; } final LinearGradientPaint BIGCENTER_FOREGROUNDFRAME_GRADIENT = new LinearGradientPaint(BIGCENTER_FOREGROUNDFRAME_START, BIGCENTER_FOREGROUNDFRAME_STOP, BIGCENTER_FOREGROUNDFRAME_FRACTIONS, BIGCENTER_FOREGROUNDFRAME_COLORS); G2.setPaint(BIGCENTER_FOREGROUNDFRAME_GRADIENT); G2.fill(BIGCENTER_FOREGROUNDFRAME); final Ellipse2D BIGCENTER_FOREGROUND = new Ellipse2D.Double(IMAGE_WIDTH * 0.4579439163208008, IMAGE_HEIGHT * 0.4579439163208008, IMAGE_WIDTH * 0.08411216735839844, IMAGE_HEIGHT * 0.08411216735839844); final Point2D BIGCENTER_FOREGROUND_START = new Point2D.Double(0, BIGCENTER_FOREGROUND.getBounds2D().getMinY()); final Point2D BIGCENTER_FOREGROUND_STOP = new Point2D.Double(0, BIGCENTER_FOREGROUND.getBounds2D().getMaxY()); final float[] BIGCENTER_FOREGROUND_FRACTIONS = { 0.0f, 0.21f, 0.5f, 0.78f, 1.0f }; final Color[] BIGCENTER_FOREGROUND_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGCENTER_FOREGROUND_COLORS = new Color[]{ new Color(191, 191, 191, 255), new Color(94, 93, 99, 255), new Color(43, 42, 47, 255), new Color(78, 79, 81, 255), new Color(143, 144, 146, 255) }; break; case BRASS: BIGCENTER_FOREGROUND_COLORS = new Color[]{ new Color(223, 208, 174, 255), new Color(159, 136, 104, 255), new Color(122, 94, 62, 255), new Color(159, 136, 104, 255), new Color(223, 208, 174, 255) }; break; case SILVER: default: BIGCENTER_FOREGROUND_COLORS = new Color[]{ new Color(215, 215, 215, 255), new Color(139, 142, 145, 255), new Color(100, 100, 100, 255), new Color(139, 142, 145, 255), new Color(215, 215, 215, 255) }; break; } final LinearGradientPaint BIGCENTER_FOREGROUND_GRADIENT = new LinearGradientPaint(BIGCENTER_FOREGROUND_START, BIGCENTER_FOREGROUND_STOP, BIGCENTER_FOREGROUND_FRACTIONS, BIGCENTER_FOREGROUND_COLORS); G2.setPaint(BIGCENTER_FOREGROUND_GRADIENT); G2.fill(BIGCENTER_FOREGROUND); break; case BIG_CHROME_KNOB: //G2.drawImage(KNOB_FACTORY.create_KNOB_Image((int) Math.ceil(IMAGE_WIDTH * 0.14018690586090088), KnobType.BIG_CHROME_KNOB), (int) Math.ceil(IMAGE_WIDTH * 0.42990654706954956), (int) Math.ceil(IMAGE_WIDTH * 0.42990654706954956), null); final Ellipse2D CHROMEKNOB_BACKFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.42990654706954956, IMAGE_HEIGHT * 0.42990654706954956, IMAGE_WIDTH * 0.14018690586090088, IMAGE_HEIGHT * 0.14018690586090088); final Point2D CHROMEKNOB_BACKFRAME_START = new Point2D.Double((0.46261682242990654 * IMAGE_WIDTH), (0.4392523364485981 * IMAGE_HEIGHT)); final Point2D CHROMEKNOB_BACKFRAME_STOP = new Point2D.Double(((0.46261682242990654 + 0.0718114890783315) * IMAGE_WIDTH), ((0.4392523364485981 + 0.1149224055539082) * IMAGE_HEIGHT)); final float[] CHROMEKNOB_BACKFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] CHROMEKNOB_BACKFRAME_COLORS = { new Color(129, 139, 140, 255), new Color(166, 171, 175, 255) }; final LinearGradientPaint CHROMEKNOB_BACKFRAME_GRADIENT = new LinearGradientPaint(CHROMEKNOB_BACKFRAME_START, CHROMEKNOB_BACKFRAME_STOP, CHROMEKNOB_BACKFRAME_FRACTIONS, CHROMEKNOB_BACKFRAME_COLORS); G2.setPaint(CHROMEKNOB_BACKFRAME_GRADIENT); G2.fill(CHROMEKNOB_BACKFRAME); final Ellipse2D CHROMEKNOB_BACK = new Ellipse2D.Double(IMAGE_WIDTH * 0.43457943201065063, IMAGE_HEIGHT * 0.43457943201065063, IMAGE_WIDTH * 0.13084113597869873, IMAGE_HEIGHT * 0.13084113597869873); final Point2D CHROMEKNOB_BACK_CENTER = new Point2D.Double(CHROMEKNOB_BACK.getCenterX(), CHROMEKNOB_BACK.getCenterY()); final float[] CHROMEKNOB_BACK_FRACTIONS = { 0.0f, 0.09f, 0.12f, 0.16f, 0.25f, 0.29f, 0.33f, 0.38f, 0.48f, 0.52f, 0.65f, 0.69f, 0.8f, 0.83f, 0.87f, 0.97f, 1.0f }; final Color[] CHROMEKNOB_BACK_COLORS = { new Color(255, 255, 255, 255), new Color(255, 255, 255, 255), new Color(136, 136, 138, 255), new Color(164, 185, 190, 255), new Color(158, 179, 182, 255), new Color(112, 112, 112, 255), new Color(221, 227, 227, 255), new Color(155, 176, 179, 255), new Color(156, 176, 177, 255), new Color(254, 255, 255, 255), new Color(255, 255, 255, 255), new Color(156, 180, 180, 255), new Color(198, 209, 211, 255), new Color(246, 248, 247, 255), new Color(204, 216, 216, 255), new Color(164, 188, 190, 255), new Color(255, 255, 255, 255) }; final ConicalGradientPaint CHROMEKNOB_BACK_GRADIENT = new ConicalGradientPaint(false, CHROMEKNOB_BACK_CENTER, 0, CHROMEKNOB_BACK_FRACTIONS, CHROMEKNOB_BACK_COLORS); G2.setPaint(CHROMEKNOB_BACK_GRADIENT); G2.fill(CHROMEKNOB_BACK); final Ellipse2D CHROMEKNOB_FOREFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4672897160053253, IMAGE_HEIGHT * 0.4672897160053253, IMAGE_WIDTH * 0.06542053818702698, IMAGE_HEIGHT * 0.06542053818702698); final Point2D CHROMEKNOB_FOREFRAME_START = new Point2D.Double((0.48130841121495327 * IMAGE_WIDTH), (0.4719626168224299 * IMAGE_HEIGHT)); final Point2D CHROMEKNOB_FOREFRAME_STOP = new Point2D.Double(((0.48130841121495327 + 0.033969662360372466) * IMAGE_WIDTH), ((0.4719626168224299 + 0.05036209552904459) * IMAGE_HEIGHT)); final float[] CHROMEKNOB_FOREFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] CHROMEKNOB_FOREFRAME_COLORS = { new Color(225, 235, 232, 255), new Color(196, 207, 207, 255) }; final LinearGradientPaint CHROMEKNOB_FOREFRAME_GRADIENT = new LinearGradientPaint(CHROMEKNOB_FOREFRAME_START, CHROMEKNOB_FOREFRAME_STOP, CHROMEKNOB_FOREFRAME_FRACTIONS, CHROMEKNOB_FOREFRAME_COLORS); G2.setPaint(CHROMEKNOB_FOREFRAME_GRADIENT); G2.fill(CHROMEKNOB_FOREFRAME); final Ellipse2D CHROMEKNOB_FORE = new Ellipse2D.Double(IMAGE_WIDTH * 0.4719626307487488, IMAGE_HEIGHT * 0.4719626307487488, IMAGE_WIDTH * 0.05607473850250244, IMAGE_HEIGHT * 0.05607473850250244); final Point2D CHROMEKNOB_FORE_START = new Point2D.Double((0.48130841121495327 * IMAGE_WIDTH), (0.4766355140186916 * IMAGE_HEIGHT)); final Point2D CHROMEKNOB_FORE_STOP = new Point2D.Double(((0.48130841121495327 + 0.03135661140957459) * IMAGE_WIDTH), ((0.4766355140186916 + 0.04648808818065655) * IMAGE_HEIGHT)); final float[] CHROMEKNOB_FORE_FRACTIONS = { 0.0f, 1.0f }; final Color[] CHROMEKNOB_FORE_COLORS = { new Color(237, 239, 237, 255), new Color(148, 161, 161, 255) }; final LinearGradientPaint CHROMEKNOB_FORE_GRADIENT = new LinearGradientPaint(CHROMEKNOB_FORE_START, CHROMEKNOB_FORE_STOP, CHROMEKNOB_FORE_FRACTIONS, CHROMEKNOB_FORE_COLORS); G2.setPaint(CHROMEKNOB_FORE_GRADIENT); G2.fill(CHROMEKNOB_FORE); break; case METAL_KNOB: final Ellipse2D METALKNOB_FRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4579439163208008, IMAGE_HEIGHT * 0.4579439163208008, IMAGE_WIDTH * 0.08411216735839844, IMAGE_HEIGHT * 0.08411216735839844); final Point2D METALKNOB_FRAME_START = new Point2D.Double(0, METALKNOB_FRAME.getBounds2D().getMinY()); final Point2D METALKNOB_FRAME_STOP = new Point2D.Double(0, METALKNOB_FRAME.getBounds2D().getMaxY()); final float[] METALKNOB_FRAME_FRACTIONS = { 0.0f, 0.47f, 1.0f }; final Color[] METALKNOB_FRAME_COLORS = { new Color(92, 95, 101, 255), new Color(46, 49, 53, 255), new Color(22, 23, 26, 255) }; final LinearGradientPaint METALKNOB_FRAME_GRADIENT = new LinearGradientPaint(METALKNOB_FRAME_START, METALKNOB_FRAME_STOP, METALKNOB_FRAME_FRACTIONS, METALKNOB_FRAME_COLORS); G2.setPaint(METALKNOB_FRAME_GRADIENT); G2.fill(METALKNOB_FRAME); final Ellipse2D METALKNOB_MAIN = new Ellipse2D.Double(IMAGE_WIDTH * 0.46261683106422424, IMAGE_HEIGHT * 0.46261683106422424, IMAGE_WIDTH * 0.0747663676738739, IMAGE_HEIGHT * 0.0747663676738739); final Point2D METALKNOB_MAIN_START = new Point2D.Double(0, METALKNOB_MAIN.getBounds2D().getMinY()); final Point2D METALKNOB_MAIN_STOP = new Point2D.Double(0, METALKNOB_MAIN.getBounds2D().getMaxY()); final float[] METALKNOB_MAIN_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOB_MAIN_COLORS; switch (getModel().getKnobStyle()) { case BLACK: METALKNOB_MAIN_COLORS = new Color[]{ new Color(0x2B2A2F), new Color(0x1A1B20) }; break; case BRASS: METALKNOB_MAIN_COLORS = new Color[]{ new Color(0x966E36), new Color(0x7C5F3D) }; break; case SILVER: default: METALKNOB_MAIN_COLORS = new Color[]{ new Color(204, 204, 204, 255), new Color(87, 92, 98, 255) }; break; } final LinearGradientPaint METALKNOB_MAIN_GRADIENT = new LinearGradientPaint(METALKNOB_MAIN_START, METALKNOB_MAIN_STOP, METALKNOB_MAIN_FRACTIONS, METALKNOB_MAIN_COLORS); G2.setPaint(METALKNOB_MAIN_GRADIENT); G2.fill(METALKNOB_MAIN); final GeneralPath METALKNOB_LOWERHL = new GeneralPath(); METALKNOB_LOWERHL.setWindingRule(Path2D.WIND_EVEN_ODD); METALKNOB_LOWERHL.moveTo(IMAGE_WIDTH * 0.5186915887850467, IMAGE_HEIGHT * 0.5280373831775701); METALKNOB_LOWERHL.curveTo(IMAGE_WIDTH * 0.5186915887850467, IMAGE_HEIGHT * 0.5186915887850467, IMAGE_WIDTH * 0.5093457943925234, IMAGE_HEIGHT * 0.514018691588785, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.514018691588785); METALKNOB_LOWERHL.curveTo(IMAGE_WIDTH * 0.48598130841121495, IMAGE_HEIGHT * 0.514018691588785, IMAGE_WIDTH * 0.4766355140186916, IMAGE_HEIGHT * 0.5186915887850467, IMAGE_WIDTH * 0.4766355140186916, IMAGE_HEIGHT * 0.5280373831775701); METALKNOB_LOWERHL.curveTo(IMAGE_WIDTH * 0.48130841121495327, IMAGE_HEIGHT * 0.5327102803738317, IMAGE_WIDTH * 0.49065420560747663, IMAGE_HEIGHT * 0.5373831775700935, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.5373831775700935); METALKNOB_LOWERHL.curveTo(IMAGE_WIDTH * 0.5046728971962616, IMAGE_HEIGHT * 0.5373831775700935, IMAGE_WIDTH * 0.514018691588785, IMAGE_HEIGHT * 0.5327102803738317, IMAGE_WIDTH * 0.5186915887850467, IMAGE_HEIGHT * 0.5280373831775701); METALKNOB_LOWERHL.closePath(); final Point2D METALKNOB_LOWERHL_CENTER = new Point2D.Double((0.5 * IMAGE_WIDTH), (0.5373831775700935 * IMAGE_HEIGHT)); final float[] METALKNOB_LOWERHL_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOB_LOWERHL_COLORS = { new Color(255, 255, 255, 153), new Color(255, 255, 255, 0) }; final RadialGradientPaint METALKNOB_LOWERHL_GRADIENT = new RadialGradientPaint(METALKNOB_LOWERHL_CENTER, (float) (0.03271028037383177 * IMAGE_WIDTH), METALKNOB_LOWERHL_FRACTIONS, METALKNOB_LOWERHL_COLORS); G2.setPaint(METALKNOB_LOWERHL_GRADIENT); G2.fill(METALKNOB_LOWERHL); final GeneralPath METALKNOB_UPPERHL = new GeneralPath(); METALKNOB_UPPERHL.setWindingRule(Path2D.WIND_EVEN_ODD); METALKNOB_UPPERHL.moveTo(IMAGE_WIDTH * 0.5327102803738317, IMAGE_HEIGHT * 0.48130841121495327); METALKNOB_UPPERHL.curveTo(IMAGE_WIDTH * 0.5280373831775701, IMAGE_HEIGHT * 0.4672897196261682, IMAGE_WIDTH * 0.514018691588785, IMAGE_HEIGHT * 0.45794392523364486, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.45794392523364486); METALKNOB_UPPERHL.curveTo(IMAGE_WIDTH * 0.48130841121495327, IMAGE_HEIGHT * 0.45794392523364486, IMAGE_WIDTH * 0.4672897196261682, IMAGE_HEIGHT * 0.4672897196261682, IMAGE_WIDTH * 0.46261682242990654, IMAGE_HEIGHT * 0.48130841121495327); METALKNOB_UPPERHL.curveTo(IMAGE_WIDTH * 0.4672897196261682, IMAGE_HEIGHT * 0.48598130841121495, IMAGE_WIDTH * 0.48130841121495327, IMAGE_HEIGHT * 0.49065420560747663, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.49065420560747663); METALKNOB_UPPERHL.curveTo(IMAGE_WIDTH * 0.514018691588785, IMAGE_HEIGHT * 0.49065420560747663, IMAGE_WIDTH * 0.5280373831775701, IMAGE_HEIGHT * 0.48598130841121495, IMAGE_WIDTH * 0.5327102803738317, IMAGE_HEIGHT * 0.48130841121495327); METALKNOB_UPPERHL.closePath(); final Point2D METALKNOB_UPPERHL_CENTER = new Point2D.Double((0.4953271028037383 * IMAGE_WIDTH), (0.45794392523364486 * IMAGE_HEIGHT)); final float[] METALKNOB_UPPERHL_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOB_UPPERHL_COLORS = { new Color(255, 255, 255, 191), new Color(255, 255, 255, 0) }; final RadialGradientPaint METALKNOB_UPPERHL_GRADIENT = new RadialGradientPaint(METALKNOB_UPPERHL_CENTER, (float) (0.04906542056074766 * IMAGE_WIDTH), METALKNOB_UPPERHL_FRACTIONS, METALKNOB_UPPERHL_COLORS); G2.setPaint(METALKNOB_UPPERHL_GRADIENT); G2.fill(METALKNOB_UPPERHL); final Ellipse2D METALKNOB_INNERFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.47663551568984985, IMAGE_HEIGHT * 0.4813084006309509, IMAGE_WIDTH * 0.04205608367919922, IMAGE_HEIGHT * 0.04205608367919922); final Point2D METALKNOB_INNERFRAME_START = new Point2D.Double(0, METALKNOB_INNERFRAME.getBounds2D().getMinY()); final Point2D METALKNOB_INNERFRAME_STOP = new Point2D.Double(0, METALKNOB_INNERFRAME.getBounds2D().getMaxY()); final float[] METALKNOB_INNERFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOB_INNERFRAME_COLORS = { new Color(0, 0, 0, 255), new Color(204, 204, 204, 255) }; final LinearGradientPaint METALKNOB_INNERFRAME_GRADIENT = new LinearGradientPaint(METALKNOB_INNERFRAME_START, METALKNOB_INNERFRAME_STOP, METALKNOB_INNERFRAME_FRACTIONS, METALKNOB_INNERFRAME_COLORS); G2.setPaint(METALKNOB_INNERFRAME_GRADIENT); G2.fill(METALKNOB_INNERFRAME); final Ellipse2D METALKNOB_INNERBACKGROUND = new Ellipse2D.Double(IMAGE_WIDTH * 0.4813084006309509, IMAGE_HEIGHT * 0.4859813153743744, IMAGE_WIDTH * 0.03271031379699707, IMAGE_HEIGHT * 0.03271028399467468); final Point2D METALKNOB_INNERBACKGROUND_START = new Point2D.Double(0, METALKNOB_INNERBACKGROUND.getBounds2D().getMinY()); final Point2D METALKNOB_INNERBACKGROUND_STOP = new Point2D.Double(0, METALKNOB_INNERBACKGROUND.getBounds2D().getMaxY()); final float[] METALKNOB_INNERBACKGROUND_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOB_INNERBACKGROUND_COLORS = { new Color(1, 6, 11, 255), new Color(50, 52, 56, 255) }; final LinearGradientPaint METALKNOB_INNERBACKGROUND_GRADIENT = new LinearGradientPaint(METALKNOB_INNERBACKGROUND_START, METALKNOB_INNERBACKGROUND_STOP, METALKNOB_INNERBACKGROUND_FRACTIONS, METALKNOB_INNERBACKGROUND_COLORS); G2.setPaint(METALKNOB_INNERBACKGROUND_GRADIENT); G2.fill(METALKNOB_INNERBACKGROUND); break; } } // Draw min bottom if (postPositionList.contains(PostPosition.MIN_BOTTOM)) { G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.336448609828949), (int) (IMAGE_HEIGHT * 0.8037382960319519), null); } // Draw max bottom post if (postPositionList.contains(PostPosition.MAX_BOTTOM)) { G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.6261682510375977), (int) (IMAGE_HEIGHT * 0.8037382960319519), null); } // Draw min center bottom post if (postPositionList.contains(PostPosition.MAX_CENTER_BOTTOM)) { G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.5233644843101501), (int) (IMAGE_HEIGHT * 0.8317757248878479), null); } // Draw max center top post if (postPositionList.contains(PostPosition.MAX_CENTER_TOP)) { G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.5233644843101501), (int) (IMAGE_HEIGHT * 0.13084112107753754), null); } // Draw max right post if (postPositionList.contains(PostPosition.MAX_RIGHT)) { G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.8317757248878479), (int) (IMAGE_HEIGHT * 0.514018714427948), null); } // Draw min left post if (postPositionList.contains(PostPosition.MIN_LEFT)) { G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.13084112107753754), (int) (IMAGE_HEIGHT * 0.514018714427948), null); } // Draw lower center post final AffineTransform OLD_TRANSFORM = G2.getTransform(); final Point2D KNOB_CENTER = new Point2D.Double(); if (postPositionList.contains(PostPosition.LOWER_CENTER)) { switch (getKnobType()) { case SMALL_STD_KNOB: final Ellipse2D LOWERCENTER_KNOB_FRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4579439163208008, IMAGE_HEIGHT * 0.6915887594223022, IMAGE_WIDTH * 0.08411216735839844, IMAGE_HEIGHT * 0.08411216735839844); switch (getOrientation()) { case WEST: KNOB_CENTER.setLocation(LOWERCENTER_KNOB_FRAME.getCenterX(), LOWERCENTER_KNOB_FRAME.getCenterY()); G2.rotate(Math.PI / 2, KNOB_CENTER.getX(), KNOB_CENTER.getY()); break; } final Point2D LOWERCENTER_KNOB_FRAME_START = new Point2D.Double(0, LOWERCENTER_KNOB_FRAME.getBounds2D().getMinY()); final Point2D LOWERCENTER_KNOB_FRAME_STOP = new Point2D.Double(0, LOWERCENTER_KNOB_FRAME.getBounds2D().getMaxY()); final float[] LOWERCENTER_KNOB_FRAME_FRACTIONS = { 0.0f, 0.46f, 1.0f }; final Color[] LOWERCENTER_KNOB_FRAME_COLORS = { new Color(180, 180, 180, 255), new Color(63, 63, 63, 255), new Color(40, 40, 40, 255) }; final LinearGradientPaint LOWERCENTER_KNOB_FRAME_GRADIENT = new LinearGradientPaint(LOWERCENTER_KNOB_FRAME_START, LOWERCENTER_KNOB_FRAME_STOP, LOWERCENTER_KNOB_FRAME_FRACTIONS, LOWERCENTER_KNOB_FRAME_COLORS); G2.setPaint(LOWERCENTER_KNOB_FRAME_GRADIENT); G2.fill(LOWERCENTER_KNOB_FRAME); final Ellipse2D LOWERCENTER_KNOB_MAIN = new Ellipse2D.Double(IMAGE_WIDTH * 0.4672897160053253, IMAGE_HEIGHT * 0.7009345889091492, IMAGE_WIDTH * 0.06542053818702698, IMAGE_HEIGHT * 0.06542056798934937); final Point2D LOWERCENTER_KNOB_MAIN_START = new Point2D.Double(0, LOWERCENTER_KNOB_MAIN.getBounds2D().getMinY()); final Point2D LOWERCENTER_KNOB_MAIN_STOP = new Point2D.Double(0, LOWERCENTER_KNOB_MAIN.getBounds2D().getMaxY()); final float[] LOWERCENTER_KNOB_MAIN_FRACTIONS = { 0.0f, 0.5f, 1.0f }; final Color[] LOWERCENTER_KNOB_MAIN_COLORS; switch (getModel().getKnobStyle()) { case BLACK: LOWERCENTER_KNOB_MAIN_COLORS = new Color[]{ new Color(0xBFBFBF), new Color(0x2B2A2F), new Color(0x7D7E80) }; break; case BRASS: LOWERCENTER_KNOB_MAIN_COLORS = new Color[]{ new Color(0xDFD0AE), new Color(0x7A5E3E), new Color(0xCFBE9D) }; break; case SILVER: default: LOWERCENTER_KNOB_MAIN_COLORS = new Color[]{ new Color(0xD7D7D7), new Color(0x747474), new Color(0xD7D7D7) }; break; } final LinearGradientPaint LOWERCENTER_KNOB_MAIN_GRADIENT = new LinearGradientPaint(LOWERCENTER_KNOB_MAIN_START, LOWERCENTER_KNOB_MAIN_STOP, LOWERCENTER_KNOB_MAIN_FRACTIONS, LOWERCENTER_KNOB_MAIN_COLORS); G2.setPaint(LOWERCENTER_KNOB_MAIN_GRADIENT); G2.fill(LOWERCENTER_KNOB_MAIN); final Ellipse2D LOWERCENTER_KNOB_INNERSHADOW = new Ellipse2D.Double(IMAGE_WIDTH * 0.4672897160053253, IMAGE_HEIGHT * 0.7009345889091492, IMAGE_WIDTH * 0.06542053818702698, IMAGE_HEIGHT * 0.06542056798934937); final Point2D LOWERCENTER_KNOB_INNERSHADOW_CENTER = new Point2D.Double((0.4953271028037383 * IMAGE_WIDTH), (0.7242990654205608 * IMAGE_HEIGHT)); final float[] LOWERCENTER_KNOB_INNERSHADOW_FRACTIONS = { 0.0f, 0.75f, 0.76f, 1.0f }; final Color[] LOWERCENTER_KNOB_INNERSHADOW_COLORS = { new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), new Color(0, 0, 0, 1), new Color(0, 0, 0, 51) }; final RadialGradientPaint LOWERCENTER_KNOB_INNERSHADOW_GRADIENT = new RadialGradientPaint(LOWERCENTER_KNOB_INNERSHADOW_CENTER, (float) (0.03271028037383177 * IMAGE_WIDTH), LOWERCENTER_KNOB_INNERSHADOW_FRACTIONS, LOWERCENTER_KNOB_INNERSHADOW_COLORS); G2.setPaint(LOWERCENTER_KNOB_INNERSHADOW_GRADIENT); G2.fill(LOWERCENTER_KNOB_INNERSHADOW); break; case BIG_STD_KNOB: final Ellipse2D BIGLOWERCENTER_BACKGROUNDFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4392523467540741, IMAGE_HEIGHT * 0.672897219657898, IMAGE_WIDTH * 0.1214953362941742, IMAGE_HEIGHT * 0.1214953064918518); switch (getOrientation()) { case WEST: KNOB_CENTER.setLocation(BIGLOWERCENTER_BACKGROUNDFRAME.getCenterX(), BIGLOWERCENTER_BACKGROUNDFRAME.getCenterY()); G2.rotate(Math.PI / 2, KNOB_CENTER.getX(), KNOB_CENTER.getY()); break; } final Point2D BIGLOWERCENTER_BACKGROUNDFRAME_START = new Point2D.Double(0, BIGLOWERCENTER_BACKGROUNDFRAME.getBounds2D().getMinY()); final Point2D BIGLOWERCENTER_BACKGROUNDFRAME_STOP = new Point2D.Double(0, BIGLOWERCENTER_BACKGROUNDFRAME.getBounds2D().getMaxY()); final float[] BIGLOWERCENTER_BACKGROUNDFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] BIGLOWERCENTER_BACKGROUNDFRAME_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGLOWERCENTER_BACKGROUNDFRAME_COLORS = new Color[]{ new Color(129, 133, 136, 255), new Color(61, 61, 73, 255) }; break; case BRASS: BIGLOWERCENTER_BACKGROUNDFRAME_COLORS = new Color[]{ new Color(143, 117, 80, 255), new Color(100, 76, 49, 255) }; break; case SILVER: default: BIGLOWERCENTER_BACKGROUNDFRAME_COLORS = new Color[]{ new Color(152, 152, 152, 255), new Color(118, 121, 126, 255) }; break; } final LinearGradientPaint BIGLOWERCENTER_BACKGROUNDFRAME_GRADIENT = new LinearGradientPaint(BIGLOWERCENTER_BACKGROUNDFRAME_START, BIGLOWERCENTER_BACKGROUNDFRAME_STOP, BIGLOWERCENTER_BACKGROUNDFRAME_FRACTIONS, BIGLOWERCENTER_BACKGROUNDFRAME_COLORS); G2.setPaint(BIGLOWERCENTER_BACKGROUNDFRAME_GRADIENT); G2.fill(BIGLOWERCENTER_BACKGROUNDFRAME); final Ellipse2D BIGLOWERCENTER_BACKGROUND = new Ellipse2D.Double(IMAGE_WIDTH * 0.44392523169517517, IMAGE_HEIGHT * 0.677570104598999, IMAGE_WIDTH * 0.11214950680732727, IMAGE_HEIGHT * 0.11214953660964966); final Point2D BIGLOWERCENTER_BACKGROUND_START = new Point2D.Double(0, BIGLOWERCENTER_BACKGROUND.getBounds2D().getMinY()); final Point2D BIGLOWERCENTER_BACKGROUND_STOP = new Point2D.Double(0, BIGLOWERCENTER_BACKGROUND.getBounds2D().getMaxY()); final float[] BIGLOWERCENTER_BACKGROUND_FRACTIONS = { 0.0f, 1.0f }; final Color[] BIGLOWERCENTER_BACKGROUND_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGLOWERCENTER_BACKGROUND_COLORS = new Color[]{ new Color(26, 27, 32, 255), new Color(96, 97, 102, 255) }; break; case BRASS: BIGLOWERCENTER_BACKGROUND_COLORS = new Color[]{ new Color(98, 75, 49, 255), new Color(149, 109, 54, 255) }; break; case SILVER: default: BIGLOWERCENTER_BACKGROUND_COLORS = new Color[]{ new Color(118, 121, 126, 255), new Color(191, 191, 191, 255) }; break; } final LinearGradientPaint BIGLOWERCENTER_BACKGROUND_GRADIENT = new LinearGradientPaint(BIGLOWERCENTER_BACKGROUND_START, BIGLOWERCENTER_BACKGROUND_STOP, BIGLOWERCENTER_BACKGROUND_FRACTIONS, BIGLOWERCENTER_BACKGROUND_COLORS); G2.setPaint(BIGLOWERCENTER_BACKGROUND_GRADIENT); G2.fill(BIGLOWERCENTER_BACKGROUND); final Ellipse2D BIGLOWERCENTER_FOREGROUNDFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4532710313796997, IMAGE_HEIGHT * 0.6869158744812012, IMAGE_WIDTH * 0.09345793724060059, IMAGE_HEIGHT * 0.09345793724060059); final Point2D BIGLOWERCENTER_FOREGROUNDFRAME_START = new Point2D.Double(0, BIGLOWERCENTER_FOREGROUNDFRAME.getBounds2D().getMinY()); final Point2D BIGLOWERCENTER_FOREGROUNDFRAME_STOP = new Point2D.Double(0, BIGLOWERCENTER_FOREGROUNDFRAME.getBounds2D().getMaxY()); final float[] BIGLOWERCENTER_FOREGROUNDFRAME_FRACTIONS = { 0.0f, 0.47f, 1.0f }; final Color[] BIGLOWERCENTER_FOREGROUNDFRAME_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGLOWERCENTER_FOREGROUNDFRAME_COLORS = new Color[]{ new Color(191, 191, 191, 255), new Color(56, 57, 61, 255), new Color(143, 144, 146, 255) }; break; case BRASS: BIGLOWERCENTER_FOREGROUNDFRAME_COLORS = new Color[]{ new Color(147, 108, 54, 255), new Color(82, 66, 50, 255), new Color(147, 108, 54, 255) }; break; case SILVER: default: BIGLOWERCENTER_FOREGROUNDFRAME_COLORS = new Color[]{ new Color(191, 191, 191, 255), new Color(116, 116, 116, 255), new Color(143, 144, 146, 255) }; break; } final LinearGradientPaint BIGLOWERCENTER_FOREGROUNDFRAME_GRADIENT = new LinearGradientPaint(BIGLOWERCENTER_FOREGROUNDFRAME_START, BIGLOWERCENTER_FOREGROUNDFRAME_STOP, BIGLOWERCENTER_FOREGROUNDFRAME_FRACTIONS, BIGLOWERCENTER_FOREGROUNDFRAME_COLORS); G2.setPaint(BIGLOWERCENTER_FOREGROUNDFRAME_GRADIENT); G2.fill(BIGLOWERCENTER_FOREGROUNDFRAME); final Ellipse2D BIGLOWERCENTER_FOREGROUND = new Ellipse2D.Double(IMAGE_WIDTH * 0.4579439163208008, IMAGE_HEIGHT * 0.6915887594223022, IMAGE_WIDTH * 0.08411216735839844, IMAGE_HEIGHT * 0.08411216735839844); final Point2D BIGLOWERCENTER_FOREGROUND_START = new Point2D.Double(0, BIGLOWERCENTER_FOREGROUND.getBounds2D().getMinY()); final Point2D BIGLOWERCENTER_FOREGROUND_STOP = new Point2D.Double(0, BIGLOWERCENTER_FOREGROUND.getBounds2D().getMaxY()); final float[] BIGLOWERCENTER_FOREGROUND_FRACTIONS = { 0.0f, 0.21f, 0.5f, 0.78f, 1.0f }; final Color[] BIGLOWERCENTER_FOREGROUND_COLORS; switch (getModel().getKnobStyle()) { case BLACK: BIGLOWERCENTER_FOREGROUND_COLORS = new Color[]{ new Color(191, 191, 191, 255), new Color(94, 93, 99, 255), new Color(43, 42, 47, 255), new Color(78, 79, 81, 255), new Color(143, 144, 146, 255) }; break; case BRASS: BIGLOWERCENTER_FOREGROUND_COLORS = new Color[]{ new Color(223, 208, 174, 255), new Color(159, 136, 104, 255), new Color(122, 94, 62, 255), new Color(159, 136, 104, 255), new Color(223, 208, 174, 255) }; break; case SILVER: default: BIGLOWERCENTER_FOREGROUND_COLORS = new Color[]{ new Color(215, 215, 215, 255), new Color(139, 142, 145, 255), new Color(100, 100, 100, 255), new Color(139, 142, 145, 255), new Color(215, 215, 215, 255) }; break; } final LinearGradientPaint BIGLOWERCENTER_FOREGROUND_GRADIENT = new LinearGradientPaint(BIGLOWERCENTER_FOREGROUND_START, BIGLOWERCENTER_FOREGROUND_STOP, BIGLOWERCENTER_FOREGROUND_FRACTIONS, BIGLOWERCENTER_FOREGROUND_COLORS); G2.setPaint(BIGLOWERCENTER_FOREGROUND_GRADIENT); G2.fill(BIGLOWERCENTER_FOREGROUND); break; case BIG_CHROME_KNOB: final Ellipse2D CHROMEKNOB_BACKFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4000000059604645, IMAGE_HEIGHT * 0.6333333253860474, IMAGE_WIDTH * 0.20000001788139343, IMAGE_HEIGHT * 0.19999998807907104); switch (getOrientation()) { case WEST: KNOB_CENTER.setLocation(CHROMEKNOB_BACKFRAME.getCenterX(), CHROMEKNOB_BACKFRAME.getCenterY()); G2.rotate(Math.PI / 2, KNOB_CENTER.getX(), KNOB_CENTER.getY()); break; } final Point2D CHROMEKNOB_BACKFRAME_START = new Point2D.Double((0.44666666666666666 * IMAGE_WIDTH), (0.6466666666666666 * IMAGE_HEIGHT)); final Point2D CHROMEKNOB_BACKFRAME_STOP = new Point2D.Double(((0.44666666666666666 + 0.10245105775175295) * IMAGE_WIDTH), ((0.6466666666666666 + 0.16395596525690903) * IMAGE_HEIGHT)); final float[] CHROMEKNOB_BACKFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] CHROMEKNOB_BACKFRAME_COLORS = { new Color(129, 139, 140, 255), new Color(166, 171, 175, 255) }; final LinearGradientPaint CHROMEKNOB_BACKFRAME_GRADIENT = new LinearGradientPaint(CHROMEKNOB_BACKFRAME_START, CHROMEKNOB_BACKFRAME_STOP, CHROMEKNOB_BACKFRAME_FRACTIONS, CHROMEKNOB_BACKFRAME_COLORS); G2.setPaint(CHROMEKNOB_BACKFRAME_GRADIENT); G2.fill(CHROMEKNOB_BACKFRAME); final Ellipse2D CHROMEKNOB_BACK = new Ellipse2D.Double(IMAGE_WIDTH * 0.40666666626930237, IMAGE_HEIGHT * 0.6399999856948853, IMAGE_WIDTH * 0.18666663765907288, IMAGE_HEIGHT * 0.18666666746139526); final Point2D CHROMEKNOB_BACK_CENTER = new Point2D.Double(CHROMEKNOB_BACK.getCenterX(), CHROMEKNOB_BACK.getCenterY()); final float[] CHROMEKNOB_BACK_FRACTIONS = { 0.0f, 0.09f, 0.12f, 0.16f, 0.25f, 0.29f, 0.33f, 0.38f, 0.48f, 0.52f, 0.65f, 0.69f, 0.8f, 0.83f, 0.87f, 0.97f, 1.0f }; final Color[] CHROMEKNOB_BACK_COLORS = { new Color(255, 255, 255, 255), new Color(255, 255, 255, 255), new Color(136, 136, 138, 255), new Color(164, 185, 190, 255), new Color(158, 179, 182, 255), new Color(112, 112, 112, 255), new Color(221, 227, 227, 255), new Color(155, 176, 179, 255), new Color(156, 176, 177, 255), new Color(254, 255, 255, 255), new Color(255, 255, 255, 255), new Color(156, 180, 180, 255), new Color(198, 209, 211, 255), new Color(246, 248, 247, 255), new Color(204, 216, 216, 255), new Color(164, 188, 190, 255), new Color(255, 255, 255, 255) }; final ConicalGradientPaint CHROMEKNOB_BACK_GRADIENT = new ConicalGradientPaint(false, CHROMEKNOB_BACK_CENTER, 0, CHROMEKNOB_BACK_FRACTIONS, CHROMEKNOB_BACK_COLORS); G2.setPaint(CHROMEKNOB_BACK_GRADIENT); G2.fill(CHROMEKNOB_BACK); final Ellipse2D CHROMEKNOB_FOREFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4533333480358124, IMAGE_HEIGHT * 0.6866666674613953, IMAGE_WIDTH * 0.09333333373069763, IMAGE_HEIGHT * 0.09333330392837524); final Point2D CHROMEKNOB_FOREFRAME_START = new Point2D.Double((0.47333333333333333 * IMAGE_WIDTH), (0.6933333333333334 * IMAGE_HEIGHT)); final Point2D CHROMEKNOB_FOREFRAME_STOP = new Point2D.Double(((0.47333333333333333 + 0.04846338496746472) * IMAGE_WIDTH), ((0.6933333333333334 + 0.07184992295477029) * IMAGE_HEIGHT)); final float[] CHROMEKNOB_FOREFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] CHROMEKNOB_FOREFRAME_COLORS = { new Color(225, 235, 232, 255), new Color(196, 207, 207, 255) }; final LinearGradientPaint CHROMEKNOB_FOREFRAME_GRADIENT = new LinearGradientPaint(CHROMEKNOB_FOREFRAME_START, CHROMEKNOB_FOREFRAME_STOP, CHROMEKNOB_FOREFRAME_FRACTIONS, CHROMEKNOB_FOREFRAME_COLORS); G2.setPaint(CHROMEKNOB_FOREFRAME_GRADIENT); G2.fill(CHROMEKNOB_FOREFRAME); final Ellipse2D CHROMEKNOB_FORE = new Ellipse2D.Double(IMAGE_WIDTH * 0.46000000834465027, IMAGE_HEIGHT * 0.6933333277702332, IMAGE_WIDTH * 0.08000001311302185, IMAGE_HEIGHT * 0.07999998331069946); final Point2D CHROMEKNOB_FORE_START = new Point2D.Double((0.47333333333333333 * IMAGE_WIDTH), (0.7 * IMAGE_HEIGHT)); final Point2D CHROMEKNOB_FORE_STOP = new Point2D.Double(((0.47333333333333333 + 0.04473543227765974) * IMAGE_WIDTH), ((0.7 + 0.06632300580440334) * IMAGE_HEIGHT)); final float[] CHROMEKNOB_FORE_FRACTIONS = { 0.0f, 1.0f }; final Color[] CHROMEKNOB_FORE_COLORS = { new Color(237, 239, 237, 255), new Color(148, 161, 161, 255) }; final LinearGradientPaint CHROMEKNOB_FORE_GRADIENT = new LinearGradientPaint(CHROMEKNOB_FORE_START, CHROMEKNOB_FORE_STOP, CHROMEKNOB_FORE_FRACTIONS, CHROMEKNOB_FORE_COLORS); G2.setPaint(CHROMEKNOB_FORE_GRADIENT); G2.fill(CHROMEKNOB_FORE); break; case METAL_KNOB: final Ellipse2D METALKNOBLC_FRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.4579439163208008, IMAGE_HEIGHT * 0.6915887594223022, IMAGE_WIDTH * 0.08411216735839844, IMAGE_HEIGHT * 0.08411216735839844); switch (getOrientation()) { case WEST: KNOB_CENTER.setLocation(METALKNOBLC_FRAME.getCenterX(), METALKNOBLC_FRAME.getCenterY()); G2.rotate(Math.PI / 2, KNOB_CENTER.getX(), KNOB_CENTER.getY()); break; } final Point2D METALKNOBLC_FRAME_START = new Point2D.Double(0, METALKNOBLC_FRAME.getBounds2D().getMinY()); final Point2D METALKNOBLC_FRAME_STOP = new Point2D.Double(0, METALKNOBLC_FRAME.getBounds2D().getMaxY()); final float[] METALKNOBLC_FRAME_FRACTIONS = { 0.0f, 0.47f, 1.0f }; final Color[] METALKNOBLC_FRAME_COLORS = { new Color(92, 95, 101, 255), new Color(46, 49, 53, 255), new Color(22, 23, 26, 255) }; final LinearGradientPaint METALKNOBLC_FRAME_GRADIENT = new LinearGradientPaint(METALKNOBLC_FRAME_START, METALKNOBLC_FRAME_STOP, METALKNOBLC_FRAME_FRACTIONS, METALKNOBLC_FRAME_COLORS); G2.setPaint(METALKNOBLC_FRAME_GRADIENT); G2.fill(METALKNOBLC_FRAME); final Ellipse2D METALKNOBLC_MAIN = new Ellipse2D.Double(IMAGE_WIDTH * 0.46261683106422424, IMAGE_HEIGHT * 0.6962617039680481, IMAGE_WIDTH * 0.0747663676738739, IMAGE_HEIGHT * 0.07476633787155151); final Point2D METALKNOBLC_MAIN_START = new Point2D.Double(0, METALKNOBLC_MAIN.getBounds2D().getMinY()); final Point2D METALKNOBLC_MAIN_STOP = new Point2D.Double(0, METALKNOBLC_MAIN.getBounds2D().getMaxY()); final float[] METALKNOBLC_MAIN_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOBLC_MAIN_COLORS; switch (getModel().getKnobStyle()) { case BLACK: METALKNOBLC_MAIN_COLORS = new Color[]{ new Color(0x2B2A2F), new Color(0x1A1B20) }; break; case BRASS: METALKNOBLC_MAIN_COLORS = new Color[]{ new Color(0x966E36), new Color(0x7C5F3D) }; break; case SILVER: default: METALKNOBLC_MAIN_COLORS = new Color[]{ new Color(204, 204, 204, 255), new Color(87, 92, 98, 255) }; break; } final LinearGradientPaint METALKNOBLC_MAIN_GRADIENT = new LinearGradientPaint(METALKNOBLC_MAIN_START, METALKNOBLC_MAIN_STOP, METALKNOBLC_MAIN_FRACTIONS, METALKNOBLC_MAIN_COLORS); G2.setPaint(METALKNOBLC_MAIN_GRADIENT); G2.fill(METALKNOBLC_MAIN); final GeneralPath METALKNOBLC_LOWERHL = new GeneralPath(); METALKNOBLC_LOWERHL.setWindingRule(Path2D.WIND_EVEN_ODD); METALKNOBLC_LOWERHL.moveTo(IMAGE_WIDTH * 0.5186915887850467, IMAGE_HEIGHT * 0.7616822429906542); METALKNOBLC_LOWERHL.curveTo(IMAGE_WIDTH * 0.5186915887850467, IMAGE_HEIGHT * 0.7523364485981309, IMAGE_WIDTH * 0.5093457943925234, IMAGE_HEIGHT * 0.7476635514018691, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.7476635514018691); METALKNOBLC_LOWERHL.curveTo(IMAGE_WIDTH * 0.48598130841121495, IMAGE_HEIGHT * 0.7476635514018691, IMAGE_WIDTH * 0.4766355140186916, IMAGE_HEIGHT * 0.7523364485981309, IMAGE_WIDTH * 0.4766355140186916, IMAGE_HEIGHT * 0.7616822429906542); METALKNOBLC_LOWERHL.curveTo(IMAGE_WIDTH * 0.48130841121495327, IMAGE_HEIGHT * 0.7663551401869159, IMAGE_WIDTH * 0.49065420560747663, IMAGE_HEIGHT * 0.7710280373831776, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.7710280373831776); METALKNOBLC_LOWERHL.curveTo(IMAGE_WIDTH * 0.5046728971962616, IMAGE_HEIGHT * 0.7710280373831776, IMAGE_WIDTH * 0.514018691588785, IMAGE_HEIGHT * 0.7663551401869159, IMAGE_WIDTH * 0.5186915887850467, IMAGE_HEIGHT * 0.7616822429906542); METALKNOBLC_LOWERHL.closePath(); final Point2D METALKNOBLC_LOWERHL_CENTER = new Point2D.Double((0.5 * IMAGE_WIDTH), (0.7710280373831776 * IMAGE_HEIGHT)); final float[] METALKNOBLC_LOWERHL_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOBLC_LOWERHL_COLORS = { new Color(255, 255, 255, 153), new Color(255, 255, 255, 0) }; final RadialGradientPaint METALKNOBLC_LOWERHL_GRADIENT = new RadialGradientPaint(METALKNOBLC_LOWERHL_CENTER, (float) (0.03271028037383177 * IMAGE_WIDTH), METALKNOBLC_LOWERHL_FRACTIONS, METALKNOBLC_LOWERHL_COLORS); G2.setPaint(METALKNOBLC_LOWERHL_GRADIENT); G2.fill(METALKNOBLC_LOWERHL); final GeneralPath METALKNOBLC_UPPERHL = new GeneralPath(); METALKNOBLC_UPPERHL.setWindingRule(Path2D.WIND_EVEN_ODD); METALKNOBLC_UPPERHL.moveTo(IMAGE_WIDTH * 0.5327102803738317, IMAGE_HEIGHT * 0.7149532710280374); METALKNOBLC_UPPERHL.curveTo(IMAGE_WIDTH * 0.5280373831775701, IMAGE_HEIGHT * 0.7009345794392523, IMAGE_WIDTH * 0.514018691588785, IMAGE_HEIGHT * 0.6915887850467289, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.6915887850467289); METALKNOBLC_UPPERHL.curveTo(IMAGE_WIDTH * 0.48130841121495327, IMAGE_HEIGHT * 0.6915887850467289, IMAGE_WIDTH * 0.4672897196261682, IMAGE_HEIGHT * 0.7009345794392523, IMAGE_WIDTH * 0.46261682242990654, IMAGE_HEIGHT * 0.7149532710280374); METALKNOBLC_UPPERHL.curveTo(IMAGE_WIDTH * 0.4672897196261682, IMAGE_HEIGHT * 0.719626168224299, IMAGE_WIDTH * 0.48130841121495327, IMAGE_HEIGHT * 0.7242990654205608, IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.7242990654205608); METALKNOBLC_UPPERHL.curveTo(IMAGE_WIDTH * 0.514018691588785, IMAGE_HEIGHT * 0.7242990654205608, IMAGE_WIDTH * 0.5280373831775701, IMAGE_HEIGHT * 0.719626168224299, IMAGE_WIDTH * 0.5327102803738317, IMAGE_HEIGHT * 0.7149532710280374); METALKNOBLC_UPPERHL.closePath(); final Point2D METALKNOBLC_UPPERHL_CENTER = new Point2D.Double((0.4953271028037383 * IMAGE_WIDTH), (0.6915887850467289 * IMAGE_HEIGHT)); final float[] METALKNOBLC_UPPERHL_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOBLC_UPPERHL_COLORS = { new Color(255, 255, 255, 191), new Color(255, 255, 255, 0) }; final RadialGradientPaint METALKNOBLC_UPPERHL_GRADIENT = new RadialGradientPaint(METALKNOBLC_UPPERHL_CENTER, (float) (0.04906542056074766 * IMAGE_WIDTH), METALKNOBLC_UPPERHL_FRACTIONS, METALKNOBLC_UPPERHL_COLORS); G2.setPaint(METALKNOBLC_UPPERHL_GRADIENT); G2.fill(METALKNOBLC_UPPERHL); final Ellipse2D METALKNOBLC_INNERFRAME = new Ellipse2D.Double(IMAGE_WIDTH * 0.47663551568984985, IMAGE_HEIGHT * 0.7149532437324524, IMAGE_WIDTH * 0.04205608367919922, IMAGE_HEIGHT * 0.04205608367919922); final Point2D METALKNOBLC_INNERFRAME_START = new Point2D.Double(0, METALKNOBLC_INNERFRAME.getBounds2D().getMinY()); final Point2D METALKNOBLC_INNERFRAME_STOP = new Point2D.Double(0, METALKNOBLC_INNERFRAME.getBounds2D().getMaxY()); final float[] METALKNOBLC_INNERFRAME_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOBLC_INNERFRAME_COLORS = { new Color(0, 0, 0, 255), new Color(204, 204, 204, 255) }; final LinearGradientPaint METALKNOBLC_INNERFRAME_GRADIENT = new LinearGradientPaint(METALKNOBLC_INNERFRAME_START, METALKNOBLC_INNERFRAME_STOP, METALKNOBLC_INNERFRAME_FRACTIONS, METALKNOBLC_INNERFRAME_COLORS); G2.setPaint(METALKNOBLC_INNERFRAME_GRADIENT); G2.fill(METALKNOBLC_INNERFRAME); final Ellipse2D METALKNOBLC_INNERBACKGROUND = new Ellipse2D.Double(IMAGE_WIDTH * 0.4813084006309509, IMAGE_HEIGHT * 0.7196261882781982, IMAGE_WIDTH * 0.03271031379699707, IMAGE_HEIGHT * 0.032710254192352295); final Point2D METALKNOBLC_INNERBACKGROUND_START = new Point2D.Double(0, METALKNOBLC_INNERBACKGROUND.getBounds2D().getMinY()); final Point2D METALKNOBLC_INNERBACKGROUND_STOP = new Point2D.Double(0, METALKNOBLC_INNERBACKGROUND.getBounds2D().getMaxY()); final float[] METALKNOBLC_INNERBACKGROUND_FRACTIONS = { 0.0f, 1.0f }; final Color[] METALKNOBLC_INNERBACKGROUND_COLORS = { new Color(1, 6, 11, 255), new Color(50, 52, 56, 255) }; final LinearGradientPaint METALKNOBLC_INNERBACKGROUND_GRADIENT = new LinearGradientPaint(METALKNOBLC_INNERBACKGROUND_START, METALKNOBLC_INNERBACKGROUND_STOP, METALKNOBLC_INNERBACKGROUND_FRACTIONS, METALKNOBLC_INNERBACKGROUND_COLORS); G2.setPaint(METALKNOBLC_INNERBACKGROUND_GRADIENT); G2.fill(METALKNOBLC_INNERBACKGROUND); break; } } // Reset orientation G2.setTransform(OLD_TRANSFORM); // Draw radialvertical gauge right post if (postPositionList.contains(PostPosition.SMALL_GAUGE_MAX_RIGHT)) { switch (getOrientation()) { case WEST: KNOB_CENTER.setLocation(IMAGE_WIDTH * 0.7803738117218018 + SINGLE_POST.getWidth() / 2.0, IMAGE_HEIGHT * 0.44859811663627625 + SINGLE_POST.getHeight() / 2.0); G2.rotate(Math.PI / 2, KNOB_CENTER.getX(), KNOB_CENTER.getY()); break; } G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.7803738117218018), (int) (IMAGE_HEIGHT * 0.44859811663627625), null); G2.setTransform(OLD_TRANSFORM); } // Draw radialvertical gauge left post if (postPositionList.contains(PostPosition.SMALL_GAUGE_MIN_LEFT)) { switch (getOrientation()) { case WEST: KNOB_CENTER.setLocation(IMAGE_WIDTH * 0.1822429895401001 + SINGLE_POST.getWidth() / 2.0, IMAGE_HEIGHT * 0.44859811663627625 + SINGLE_POST.getHeight() / 2.0); G2.rotate(Math.PI / 2, KNOB_CENTER.getX(), KNOB_CENTER.getY()); break; } G2.drawImage(SINGLE_POST, (int) (IMAGE_WIDTH * 0.1822429895401001), (int) (IMAGE_HEIGHT * 0.44859811663627625), null); G2.setTransform(OLD_TRANSFORM); } G2.dispose(); return image; } /** * Creates a single alignment post image that could be placed on all the positions where it is needed * @param WIDTH * @param KNOB_TYPE * @return a buffered image that contains a single alignment post of the given type */ private BufferedImage create_KNOB_Image(final int WIDTH, final KnobType KNOB_TYPE, final KnobStyle KNOB_STYLE) { return KNOB_FACTORY.create_KNOB_Image(WIDTH, KNOB_TYPE, KNOB_STYLE); } /** * Returns the image of the threshold indicator. * @param WIDTH * @return the threshold image that is used */ protected BufferedImage create_THRESHOLD_Image(final int WIDTH) { return create_THRESHOLD_Image(WIDTH, 0); } protected BufferedImage create_THRESHOLD_Image(final int WIDTH, final double ROTATION_OFFSET) { if (WIDTH <= 22) // 22 is needed because otherwise the image size could be smaller than 1 { return UTIL.createImage(1, 1, Transparency.TRANSLUCENT); } final int IMAGE_WIDTH = (int) (WIDTH * 0.0420560748); final int IMAGE_HEIGHT = (int) (WIDTH * 0.0981308411); final BufferedImage IMAGE = UTIL.createImage(IMAGE_WIDTH, IMAGE_HEIGHT, Transparency.TRANSLUCENT); final Graphics2D G2 = IMAGE.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); G2.rotate(ROTATION_OFFSET, IMAGE_WIDTH / 2.0, IMAGE_HEIGHT / 2.0); final Point2D THRESHOLD_START = new Point2D.Double(); final Point2D THRESHOLD_STOP = new Point2D.Double(); final GeneralPath THRESHOLD = new GeneralPath(); switch (getThresholdType()) { case ARROW: THRESHOLD.setWindingRule(Path2D.WIND_EVEN_ODD); THRESHOLD.moveTo(IMAGE_WIDTH * 0.1111111111111111, IMAGE_HEIGHT * 0.047619047619047616); THRESHOLD.lineTo(IMAGE_WIDTH * 0.8888888888888888, IMAGE_HEIGHT * 0.047619047619047616); THRESHOLD.lineTo(IMAGE_WIDTH * 0.8888888888888888, IMAGE_HEIGHT * 0.3333333333333333); THRESHOLD.lineTo(IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.5714285714285714); THRESHOLD.lineTo(IMAGE_WIDTH * 0.1111111111111111, IMAGE_HEIGHT * 0.3333333333333333); THRESHOLD.closePath(); THRESHOLD_START.setLocation(0, THRESHOLD.getBounds2D().getMinY()); THRESHOLD_STOP.setLocation(0, THRESHOLD.getBounds2D().getMaxY()); break; case TRIANGLE: default: THRESHOLD.setWindingRule(Path2D.WIND_EVEN_ODD); THRESHOLD.moveTo(IMAGE_WIDTH * 0.5, IMAGE_HEIGHT * 0.6190476190476191); THRESHOLD.lineTo(IMAGE_WIDTH * 0.1111111111111111, IMAGE_HEIGHT * 0.9523809523809523); THRESHOLD.lineTo(IMAGE_WIDTH * 0.8888888888888888, IMAGE_HEIGHT * 0.9523809523809523); THRESHOLD.closePath(); THRESHOLD_START.setLocation(0, THRESHOLD.getBounds2D().getMaxY()); THRESHOLD_STOP.setLocation(0, THRESHOLD.getBounds2D().getMinY()); break; } final float[] THRESHOLD_FRACTIONS = { 0.0f, 0.3f, 0.59f, 1.0f }; final Color[] THRESHOLD_COLORS = { getThresholdColor().DARK, getThresholdColor().MEDIUM, getThresholdColor().MEDIUM, getThresholdColor().DARK }; final LinearGradientPaint THRESHOLD_GRADIENT = new LinearGradientPaint(THRESHOLD_START, THRESHOLD_STOP, THRESHOLD_FRACTIONS, THRESHOLD_COLORS); G2.setPaint(THRESHOLD_GRADIENT); G2.fill(THRESHOLD); G2.setColor(Color.WHITE); G2.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER)); G2.draw(THRESHOLD); G2.dispose(); return IMAGE; } /** * Returns the image of the MinMeasuredValue and MaxMeasuredValue dependend * @param WIDTH * @param COLOR * @return the image of the min or max measured value */ protected BufferedImage create_MEASURED_VALUE_Image(final int WIDTH, final Color COLOR) { return create_MEASURED_VALUE_Image(WIDTH, COLOR, 0); } /** * Returns the image of the MinMeasuredValue and MaxMeasuredValue dependend * @param WIDTH * @param COLOR * @param ROTATION_OFFSET * @return the image of the min or max measured value */ protected BufferedImage create_MEASURED_VALUE_Image(final int WIDTH, final Color COLOR, final double ROTATION_OFFSET) { if (WIDTH <= 36) // 36 is needed otherwise the image size could be smaller than 1 { return UTIL.createImage(1, 1, Transparency.TRANSLUCENT); } final int IMAGE_HEIGHT = (int) (WIDTH * 0.0280373832); final int IMAGE_WIDTH = IMAGE_HEIGHT; final BufferedImage IMAGE = UTIL.createImage(IMAGE_WIDTH, IMAGE_HEIGHT, Transparency.TRANSLUCENT); final Graphics2D G2 = IMAGE.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); G2.rotate(ROTATION_OFFSET, IMAGE_WIDTH / 2.0, IMAGE_HEIGHT / 2.0); final GeneralPath INDICATOR = new GeneralPath(); INDICATOR.setWindingRule(Path2D.WIND_EVEN_ODD); INDICATOR.moveTo(IMAGE_WIDTH * 0.5, IMAGE_HEIGHT); INDICATOR.lineTo(0.0, 0.0); INDICATOR.lineTo(IMAGE_WIDTH, 0.0); INDICATOR.closePath(); G2.setColor(COLOR); G2.fill(INDICATOR); G2.dispose(); return IMAGE; } /** * Returns the image of the pointer. This pointer is centered in the gauge and of PointerType FG_TYPE1. * @param WIDTH * @return the pointer image that is used in all gauges that have a centered pointer */ protected BufferedImage create_POINTER_Image(final int WIDTH) { return create_POINTER_Image(WIDTH, PointerType.TYPE1); } /** * Returns the image of the pointer. This pointer is centered in the gauge. * @param WIDTH * @param POINTER_TYPE * @return the pointer image that is used in all gauges that have a centered pointer */ protected BufferedImage create_POINTER_Image(final int WIDTH, final PointerType POINTER_TYPE) { if (getPointerColor() != ColorDef.CUSTOM) { return POINTER_FACTORY.createStandardPointer(WIDTH, POINTER_TYPE, getPointerColor(), getBackgroundColor()); } else { return POINTER_FACTORY.createStandardPointer(WIDTH, POINTER_TYPE, getPointerColor(), getModel().getCustomPointerColorObject(), getBackgroundColor()); } } /** * Returns the image of the pointer. This pointer is centered in the gauge. * @param WIDTH * @param POINTER_TYPE * @param POINTER_COLOR * @return the pointer image that is used in all gauges that have a centered pointer */ protected BufferedImage create_POINTER_Image(final int WIDTH, final PointerType POINTER_TYPE, final ColorDef POINTER_COLOR) { return POINTER_FACTORY.createStandardPointer(WIDTH, POINTER_TYPE, POINTER_COLOR, getBackgroundColor()); } /** * Returns the image of the pointer. This pointer is centered in the gauge. * @param WIDTH * @param POINTER_TYPE * @param POINTER_COLOR * @param CUSTOM_POINTER_COLOR * @return the pointer image that is used in all gauges that have a centered pointer */ protected BufferedImage create_POINTER_Image(final int WIDTH, final PointerType POINTER_TYPE, final ColorDef POINTER_COLOR, final CustomColorDef CUSTOM_POINTER_COLOR) { return POINTER_FACTORY.createStandardPointer(WIDTH, POINTER_TYPE, POINTER_COLOR, CUSTOM_POINTER_COLOR, getBackgroundColor()); } /** * Returns the image of the pointer shadow. This shadow is centered in the gauge * @param WIDTH * @return the pointer shadow image that is used in all gauges that have a centered pointer */ protected BufferedImage create_POINTER_SHADOW_Image(final int WIDTH) { return create_POINTER_SHADOW_Image(WIDTH, PointerType.TYPE1); } /** * Returns the image of the pointer shadow. This shadow is centered in the gauge * @param WIDTH * @param POINTER_TYPE * @return the pointer shadow image that is used in all gauges that have a centered pointer */ protected BufferedImage create_POINTER_SHADOW_Image(final int WIDTH, final PointerType POINTER_TYPE) { return POINTER_FACTORY.createStandardPointerShadow(WIDTH, POINTER_TYPE); } /** * Returns the image of the glasseffect with a centered knob * @param WIDTH * @return the foreground image that will be used (in principle only the glass effect) */ protected BufferedImage create_FOREGROUND_Image(final int WIDTH) { switch (getFrameType()) { case ROUND: return FOREGROUND_FACTORY.createRadialForeground(WIDTH); case SQUARE: return FOREGROUND_FACTORY.createLinearForeground(WIDTH, WIDTH); default: return FOREGROUND_FACTORY.createRadialForeground(WIDTH); } } /** * Returns the image of the glasseffect and a centered knob if wanted * @param WIDTH * @param WITH_CENTER_KNOB * @return the foreground image that will be used (in principle only the glass effect) */ protected BufferedImage create_FOREGROUND_Image(final int WIDTH, final boolean WITH_CENTER_KNOB) { switch (getFrameType()) { case ROUND: return FOREGROUND_FACTORY.createRadialForeground(WIDTH, WITH_CENTER_KNOB); case SQUARE: return FOREGROUND_FACTORY.createLinearForeground(WIDTH, WIDTH, WITH_CENTER_KNOB); default: return FOREGROUND_FACTORY.createRadialForeground(WIDTH, WITH_CENTER_KNOB); } } /** * Returns the image of the selected (FG_TYPE1, FG_TYPE2, FG_TYPE3) glasseffect, the centered knob (if wanted) * @param WIDTH * @param WITH_CENTER_KNOB * @param TYPE * @return the foreground image that will be used */ protected BufferedImage create_FOREGROUND_Image(final int WIDTH, final boolean WITH_CENTER_KNOB, final ForegroundType TYPE) { return create_FOREGROUND_Image(WIDTH, WITH_CENTER_KNOB, TYPE, null); } /** * Returns the image of the selected (FG_TYPE1, FG_TYPE2, FG_TYPE3) glasseffect, the centered knob (if wanted) * @param WIDTH * @param WITH_CENTER_KNOB * @param TYPE * @param IMAGE * @return the foreground image that will be used */ protected BufferedImage create_FOREGROUND_Image(final int WIDTH, final boolean WITH_CENTER_KNOB, final ForegroundType TYPE, final BufferedImage IMAGE) { switch (getFrameType()) { case ROUND: return FOREGROUND_FACTORY.createRadialForeground(WIDTH, WITH_CENTER_KNOB, TYPE, IMAGE); case SQUARE: return FOREGROUND_FACTORY.createLinearForeground(WIDTH, WIDTH, WITH_CENTER_KNOB, IMAGE); default: return FOREGROUND_FACTORY.createRadialForeground(WIDTH, WITH_CENTER_KNOB, ForegroundType.FG_TYPE1, IMAGE); } } /** * Returns the image that will be displayed if the gauge is disabled * @param WIDTH * @return the disabled image that will be displayed if the gauge is disabled */ protected BufferedImage create_DISABLED_Image(final int WIDTH) { return DISABLED_FACTORY.createRadialDisabled(WIDTH); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Size related methods"> /** * Calculates the rectangle that specifies the area that is available * for painting the gauge. This means that if the component has insets * that are larger than 0, these will be taken into account. */ @Override public void calcInnerBounds() { calcInnerBounds(getWidth(), getHeight()); } public void calcInnerBounds(final int WIDTH, final int HEIGHT) { final Insets INSETS = getInsets(); final int SIZE = (WIDTH - INSETS.left - INSETS.right) <= (HEIGHT - INSETS.top - INSETS.bottom) ? (WIDTH - INSETS.left - INSETS.right) : (HEIGHT - INSETS.top - INSETS.bottom); INNER_BOUNDS.setBounds(INSETS.left, INSETS.top, WIDTH - INSETS.left - INSETS.right, HEIGHT - INSETS.top - INSETS.bottom); if (!isFrameVisible()) { GAUGE_BOUNDS.setBounds(INSETS.left, INSETS.top, (int)(SIZE * 1.202247191), (int)(SIZE * 1.202247191)); } else { GAUGE_BOUNDS.setBounds(INSETS.left, INSETS.top, SIZE, SIZE); } FRAMELESS_BOUNDS.setBounds(INSETS.left + (int)(SIZE * 0.08411215245723724), INSETS.top + (int)(SIZE * 0.08411215245723724), (int)(SIZE * 0.8317756652832031), (int)(SIZE * 0.8317756652832031)); } /** * Returns the rectangle that specifies the area that is available * for painting the gauge. This means that if the component has insets * that are larger than 0, these will be taken into account. * If you add a border to the component the gauge will be drawn smaller * but within the border. * @return rectangle which describes the area that is available for painting */ @Override public Rectangle getInnerBounds() { return INNER_BOUNDS; } public Rectangle getGaugeBounds() { return GAUGE_BOUNDS; } public Rectangle getFramelessBounds() { return FRAMELESS_BOUNDS; } public Point2D getFramelessOffset() { return FRAMELESS_OFFSET; } public void setFramelessOffset(final double X, final double Y) { FRAMELESS_OFFSET.setLocation(X, Y); } @Override public Dimension getMinimumSize() { Dimension dim = super.getMinimumSize(); if (dim.width < 50 || dim.height < 50) { dim = new Dimension(50, 50); } return dim; } @Override public void setMinimumSize(final Dimension DIM) { int width = DIM.width < 50 ? 50 : DIM.width; int height = DIM.height < 50 ? 50 : DIM.height; final int SIZE = width <= height ? width : height; super.setMinimumSize(new Dimension(SIZE, SIZE)); calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); setInitialized(true); invalidate(); repaint(); } @Override public Dimension getMaximumSize() { Dimension dim = super.getMaximumSize(); if (dim.width > 1080 || dim.height > 1080) { dim = new Dimension(1080, 1080); } return dim; } @Override public void setMaximumSize(final Dimension DIM) { int width = DIM.width > 1080 ? 1080 : DIM.width; int height = DIM.height > 1080 ? 1080 : DIM.height; final int SIZE = width <= height ? width : height; super.setMaximumSize(new Dimension(SIZE, SIZE)); calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); setInitialized(true); invalidate(); repaint(); } @Override public void setPreferredSize(final Dimension DIM) { final int SIZE = DIM.width <= DIM.height ? DIM.width : DIM.height; super.setPreferredSize(new Dimension(SIZE, SIZE)); calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); setInitialized(true); invalidate(); repaint(); } @Override public void setSize(final int WIDTH, final int HEIGHT) { final int SIZE = WIDTH <= HEIGHT ? WIDTH : HEIGHT; super.setSize(SIZE, SIZE); calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); setInitialized(true); } @Override public void setSize(final Dimension DIM) { final int SIZE = DIM.width <= DIM.height ? DIM.width : DIM.height; super.setSize(new Dimension(SIZE, SIZE)); calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); setInitialized(true); } @Override public void setBounds(final Rectangle BOUNDS) { if (BOUNDS.width <= BOUNDS.height) { // vertical int yNew; switch(verticalAlignment) { case SwingConstants.TOP: yNew = BOUNDS.y; break; case SwingConstants.BOTTOM: yNew = BOUNDS.y + (BOUNDS.height - BOUNDS.width); break; case SwingConstants.CENTER: default: yNew = BOUNDS.y + ((BOUNDS.height - BOUNDS.width) / 2); break; } super.setBounds(BOUNDS.x, yNew, BOUNDS.width, BOUNDS.width); } else { // horizontal int xNew; switch(horizontalAlignment) { case SwingConstants.LEFT: xNew = BOUNDS.x; break; case SwingConstants.RIGHT: xNew = BOUNDS.x + (BOUNDS.width - BOUNDS.height); break; case SwingConstants.CENTER: default: xNew = BOUNDS.x + ((BOUNDS.width - BOUNDS.height) / 2); break; } super.setBounds(xNew, BOUNDS.y, BOUNDS.height, BOUNDS.height); } calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); setInitialized(true); } @Override public void setBounds(final int X, final int Y, final int WIDTH, final int HEIGHT) { if (WIDTH <= HEIGHT) { // vertical int yNew; switch(verticalAlignment) { case SwingConstants.TOP: yNew = Y; break; case SwingConstants.BOTTOM: yNew = Y + (HEIGHT - WIDTH); break; case SwingConstants.CENTER: default: yNew = Y + ((HEIGHT - WIDTH) / 2); break; } super.setBounds(X, yNew, WIDTH, WIDTH); } else { // horizontal int xNew; switch(horizontalAlignment) { case SwingConstants.LEFT: xNew = X; break; case SwingConstants.RIGHT: xNew = X + (WIDTH - HEIGHT); break; case SwingConstants.CENTER: default: xNew = X + ((WIDTH - HEIGHT) / 2); break; } super.setBounds(xNew, Y, HEIGHT, HEIGHT); } calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); setInitialized(true); } @Override public void setBorder(Border BORDER) { super.setBorder(BORDER); calcInnerBounds(); init(getGaugeBounds().width, getGaugeBounds().height); } /** * Returns the alignment of the radial gauge along the X axis. * @return the alignment of the radial gauge along the X axis. */ public int getHorizontalAlignment() { return horizontalAlignment; } /** * Sets the alignment of the radial gauge along the X axis. * @param HORIZONTAL_ALIGNMENT (SwingConstants.CENTER is default) */ public void setHorizontalAlignment(final int HORIZONTAL_ALIGNMENT) { horizontalAlignment = HORIZONTAL_ALIGNMENT; } /** * Returns the alignment of the radial gauge along the Y axis. * @return the alignment of the radial gauge along the Y axis. */ public int getVerticalAlignment() { return verticalAlignment; } /** * Sets the alignment of the radial gauge along the Y axis. * @param VERTICAL_ALIGNMENT (SwingConstants.CENTER is default) */ public void setVerticalAlignment(final int VERTICAL_ALIGNMENT) { verticalAlignment = VERTICAL_ALIGNMENT; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="ComponentListener methods"> @Override public void componentResized(final ComponentEvent EVENT) { final int SIZE = getWidth() <= getHeight() ? getWidth() : getHeight(); final Container PARENT = getParent(); if ((PARENT != null) && (PARENT.getLayout() == null)) { if (SIZE < getMinimumSize().width || SIZE < getMinimumSize().height) { setSize(getMinimumSize()); } else { setSize(SIZE, SIZE); } } else { if (SIZE < getMinimumSize().width || SIZE < getMinimumSize().height) { //setSize(getMinimumSize()); setPreferredSize(getMinimumSize()); } else { //setSize(new Dimension(SIZE, SIZE)); setPreferredSize(new Dimension(SIZE, SIZE)); } } calcInnerBounds(); recreateLedImages(); if (isLedOn()) { setCurrentLedImage(getLedImageOn()); } else { setCurrentLedImage(getLedImageOff()); } recreateUserLedImages(); if (isUserLedOn()) { setCurrentUserLedImage(getUserLedImageOn()); } else { setCurrentUserLedImage(getUserLedImageOff()); } getModel().setSize(getLocation().x, getLocation().y, SIZE, SIZE); init(getInnerBounds().width, getInnerBounds().height); //revalidate(); //repaint(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="ActionListener method"> @Override public void actionPerformed(final ActionEvent EVENT) { super.actionPerformed(EVENT); if (EVENT.getSource().equals(LCD_BLINKING_TIMER)) { lcdTextVisible ^= true; repaint(getInnerBounds()); } } // </editor-fold> @Override public String toString() { return "AbstractRadial"; } }
package fi.helsinki.cs.tmc.cli.command; import fi.helsinki.cs.tmc.cli.Application; import fi.helsinki.cs.tmc.cli.command.core.AbstractCommand; import fi.helsinki.cs.tmc.cli.command.core.Command; import fi.helsinki.cs.tmc.cli.io.Color; import fi.helsinki.cs.tmc.cli.io.Io; import fi.helsinki.cs.tmc.cli.io.ResultPrinter; import fi.helsinki.cs.tmc.cli.io.TmcCliProgressObserver; import fi.helsinki.cs.tmc.cli.tmcstuff.CourseInfo; import fi.helsinki.cs.tmc.cli.tmcstuff.CourseInfoIo; import fi.helsinki.cs.tmc.cli.tmcstuff.TmcUtil; import fi.helsinki.cs.tmc.cli.tmcstuff.WorkDir; import fi.helsinki.cs.tmc.core.TmcCore; import fi.helsinki.cs.tmc.core.domain.Course; import fi.helsinki.cs.tmc.core.domain.submission.SubmissionResult; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; @Command(name = "submit", desc = "Submit exercises") public class SubmitCommand extends AbstractCommand { private static final Logger logger = LoggerFactory.getLogger(SubmitCommand.class); private Io io; private boolean showAll; private boolean showDetails; @Override public void getOptions(Options options) { options.addOption("a", "all", false, "Show all test results"); options.addOption("d", "details", false, "Show detailed error message"); } @Override public void run(CommandLine args, Io io) { this.io = io; List<String> exercisesFromArgs = parseArgs(args); if (exercisesFromArgs == null) { return; } TmcCore core = getApp().getTmcCore(); if (core == null) { return; } Application app = getApp(); WorkDir workDir = app.getWorkDir(); for (String exercise : exercisesFromArgs) { if (!workDir.addPath(exercise)) { io.println("Error: '" + exercise + "' is not a valid exercise."); return; } } List<String> exerciseNames = workDir.getExerciseNames(); if (exerciseNames.isEmpty()) { io.println("You have to be in a course directory to" + " submit"); return; } CourseInfo info = CourseInfoIo.load(workDir.getConfigFile()); String courseName = info.getCourseName(); Course course = TmcUtil.findCourse(core, courseName); if (course == null) { io.println("Could not fetch course info from server."); return; } ResultPrinter resultPrinter = new ResultPrinter(io, this.showDetails, this.showAll); int passed = 0; int total = 0; Boolean isOnlyExercise = exerciseNames.size() == 1; for (String exerciseName : exerciseNames) { io.println(Color.colorString("Submitting: " + exerciseName, Color.AnsiColor.ANSI_YELLOW)); SubmissionResult result = TmcUtil.submitExercise(core, course, exerciseName); if (result == null) { io.println("Submission failed."); } else { resultPrinter.printSubmissionResult(result, isOnlyExercise); total += result.getTestCases().size(); passed += ResultPrinter.passedTests(result.getTestCases()); } } if (total > 0 && !isOnlyExercise) { // Print a progress bar showing how the ratio of passed exercises io.println(""); io.println("Total tests passed: " + passed + "/" + total); io.println(TmcCliProgressObserver.getPassedTestsBar(passed, total)); } } private List<String> parseArgs(CommandLine args) { this.showAll = args.hasOption("a"); this.showDetails = args.hasOption("d"); return args.getArgList(); } }
package net.darkhax.bookshelf.handler; import java.util.ArrayList; import java.util.List; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.enchantment.EnchantmentData; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraftforge.common.MinecraftForge; import cpw.mods.fml.common.Loader; import net.darkhax.bookshelf.event.*; import net.darkhax.bookshelf.lib.Tuple; import net.darkhax.bookshelf.lib.util.Utilities; public class BookshelfHooks { /** * A List used to cache information about potions registered with duplicate potion IDs. The * List is storing a Tuple object to keep things simple. The first part of the tuple is a * String of the mod loading the potion, and the second part is the Potion being registered. */ public static List<Tuple> conflictingPotions = new ArrayList<Tuple>(); /** * A hook for triggering the ItemEnchantedEvent. This hook is only triggered from * ContainerEnchantment, however it is possible to integrate this hook into other mods and * enchanting methods. * * @param player: The player that is enchanting the item. * @param stack: The item that is being enchanted. * @param levels: The amount of levels consumed by the enchantment. * @param enchantments: A list of enchantments being added to the ItemStack. * @return List<EnchantmentData>: A list of enchantments to add to the ItemStack. */ public static List<EnchantmentData> onItemEnchanted (EntityPlayer player, ItemStack stack, int levels, List<EnchantmentData> enchantments) { if (enchantments != null) { ItemEnchantedEvent event = new ItemEnchantedEvent(player, stack, levels, enchantments); MinecraftForge.EVENT_BUS.post(event); return event.enchantments; } return enchantments; } /** * A hook for the CreativeTabEvent.pre. This method is called before the tab initializes * its items. * * @param tab: The tab being loaded. * @param itemList: The list of items contained by the tab. * @return boolean: Whether or not the event has been canceled. If it has, prevent further * entries from being added to the tab contents. */ public static boolean onCreativeTabDisplayPre (CreativeTabs tab, List itemList) { return MinecraftForge.EVENT_BUS.post(new CreativeTabEvent.Pre(tab, itemList)); } /** * A hook for the CreativeTabEvent.post. This method is called after the tab has all of its * normal items loaded. * * @param tab: The tab being loaded. * @param itemList: The list of items contained by the tab. */ public static void onCreativeTabDisplayPost (CreativeTabs tab, List itemList) { MinecraftForge.EVENT_BUS.post(new CreativeTabEvent.Post(tab, itemList)); } /** * A hook for when a cure item is applied to an entity. * * @param entity: The Entity being cured. * @param cureItem: The ItemStack being used to cure the entity. * @return boolean: Whether or not the event has been canceled. */ public static boolean onPotionsCured (EntityLivingBase entity, ItemStack cureItem) { return MinecraftForge.EVENT_BUS.post(new PotionCuredEvent(entity, cureItem)); } /** * A hook into the constructor of Potion. This hook is not publicly available, and is only * used to prevent two or more Potions from using the same ID. This should prevent many * unintended issues. * * @param potion: The Potion that is being constructed. */ public static void onPotionConstructed (Potion potion) { if (potion != null && Utilities.getPotion(potion.id) != null && Loader.instance() != null && Loader.instance().activeModContainer() != null) conflictingPotions.add(new Tuple(Loader.instance().activeModContainer().getName(), potion)); } /** * A hook to get data about potion effects on entities. * * @param potion: The potion effect getting used. * @param entity: The entity with the potion effect. */ public static void onNewPotionEffect (PotionEffect potion, EntityLivingBase entity) { MinecraftForge.EVENT_BUS.post(new PotionEffectEvent.PotionEffectStartEvent(potion, entity)); } /** * A hook to get data about potion effects on entities. * * @param potion: The potion effect getting used. * @param entity: The entity with the potion effect. */ public static void onChangedPotionEffect (PotionEffect potion, EntityLivingBase entity) { MinecraftForge.EVENT_BUS.post(new PotionEffectEvent.PotionEffectChangeEvent(potion, entity)); } /** * A hook to get data about potion effects on entities. * * @param potion: The potion effect getting used. * @param entity: The entity with the potion effect. */ public static void onFinishedPotionEffect (PotionEffect potion, EntityLivingBase entity) { MinecraftForge.EVENT_BUS.post(new PotionEffectEvent.PotionEffectFinishEvent(potion, entity)); } }
package ca.ualberta.cs.drivr; import android.location.Location; import android.net.ConnectivityManager; import java.util.ArrayList; public class SearchRequest { private String minPrice; private String maxPrice; private String minPricePer; private String maxPricePer; private ArrayList<Request> requestList; private ConcretePlace location; private String keyword; public SearchRequest(String minPrice, String maxPrice, String minPricePer, String maxPricePer, ConcretePlace location, String keyword) { this.minPrice = minPrice; this.maxPrice = maxPrice; this.minPricePer = minPricePer; this.maxPricePer = maxPricePer; this.location = location; this.keyword = keyword; } public ArrayList<Request> getRequests(){ //TODO make actual array return new ArrayList<>(); // throw new UnsupportedOperationException(); } private void SearchKeyword() { throw new UnsupportedOperationException(); // ElasticSearch elasticSearch = new ElasticSearch(); // ArrayList<Request> requests = elasticSearch.searchRequestByKeyword(keyword); } private void SearchLocation() { throw new UnsupportedOperationException(); } }
package net.imagej.legacy.translate; import ij.CompositeImage; import ij.ImagePlus; import net.imagej.Dataset; import net.imagej.ImgPlus; import net.imagej.axis.Axes; import net.imagej.display.ImageDisplay; import net.imagej.display.ImageDisplayService; import net.imglib2.img.display.imagej.ArrayImgToVirtualStack; import net.imglib2.img.display.imagej.ImgPlusViews; import net.imglib2.img.display.imagej.ImgToVirtualStack; import net.imglib2.img.display.imagej.PlanarImgToVirtualStack; import net.imglib2.type.numeric.RealType; import org.scijava.AbstractContextual; import org.scijava.Context; import org.scijava.log.LogService; import org.scijava.plugin.Parameter; /** * Creates {@link ImagePlus}es from {@link ImageDisplay}. * * @author Barry DeZonia * @author Matthias Arzt */ public class ImagePlusCreator extends AbstractContextual { // -- instance variables -- private final ColorTableHarmonizer colorTableHarmonizer; private final PositionHarmonizer positionHarmonizer; private final NameHarmonizer nameHarmonizer; @Parameter private ImageDisplayService imageDisplayService; @Parameter private LogService log; // -- public interface -- public ImagePlusCreator(final Context context) { setContext(context); colorTableHarmonizer = new ColorTableHarmonizer(imageDisplayService); positionHarmonizer = new PositionHarmonizer(); nameHarmonizer = new NameHarmonizer(); } public ImagePlus createLegacyImage(final ImageDisplay display) { final Dataset dataset = imageDisplayService.getActiveDataset(display); return createLegacyImage(dataset, display); } public ImagePlus createLegacyImage(final Dataset ds) { return createLegacyImage(ds, null); } public ImagePlus createLegacyImage(final Dataset dataset, final ImageDisplay display) { if (dataset == null) return null; ImagePlus imp = createImagePlus( dataset ); ImagePlusCreatorUtils.setMetadata( dataset, imp ); imp = optionalMakeComposite( dataset, imp ); if (display != null) { colorTableHarmonizer.updateLegacyImage(display, imp); positionHarmonizer.updateLegacyImage(display, imp); nameHarmonizer.updateLegacyImage(display, imp); } return imp; } private static ImagePlus createImagePlus( Dataset dataset ) { ImgPlus< ? extends RealType< ? > > imgPlus = dataset.getImgPlus(); if( PlanarImgToVirtualStack.isSupported( imgPlus ) ) return PlanarImgToVirtualStack.wrap( imgPlus ); if( ArrayImgToVirtualStack.isSupported( imgPlus ) ) return ArrayImgToVirtualStack.wrap( imgPlus ); if( dataset.isRGBMerged() && ImgPlusViews.canFuseColor( imgPlus ) ) return ImgToVirtualStack.wrap( ImgPlusViews.fuseColor( imgPlus ) ); return ImgToVirtualStack.wrap( imgPlus ); } // -- private interface -- private static ImagePlus optionalMakeComposite( Dataset ds, ImagePlus imp ) { /* * ImageJ 1.x will use a StackWindow *only* if there is more than one channel. * So unfortunately, we cannot consistently return a composite image here. We * have to continue to deliver different data types that require specific case * logic in any handler. */ // NB: ColorTableHarmonizer crashes, if it gets a CompositeImage but the Dataset has no CHANNEL axis. if ( imp.getType() != ImagePlus.COLOR_RGB && imp.getStackSize() > 1 && ds.axis( Axes.CHANNEL ).isPresent() ) return new CompositeImage(imp, CompositeImage.COMPOSITE); return imp; } }
package com.almoturg.sprog.ui; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; import android.net.Uri; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.ShareActionProvider; import android.support.v7.widget.Toolbar; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.almoturg.sprog.R; import com.almoturg.sprog.SprogApplication; import com.almoturg.sprog.util.Util; import com.almoturg.sprog.model.ParentComment; import com.almoturg.sprog.model.Poem; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; import static com.almoturg.sprog.SprogApplication.filtered_poems; public class PoemActivity extends AppCompatActivity { private Poem poem; // The mainpoem corresponding to the selected one. private Poem selectedPoem; // The selected poem. private Tracker mTracker; private MenuItem favoriteItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_poem); SprogApplication application = (SprogApplication) getApplication(); mTracker = application.getDefaultTracker(); Toolbar myToolbar = (Toolbar) findViewById(R.id.poem_toolbar); setSupportActionBar(myToolbar); getSupportActionBar().setDisplayShowTitleEnabled(false); myToolbar.setTitle(null); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); Intent mIntent = getIntent(); selectedPoem = filtered_poems.get((int) mIntent.getSerializableExtra("POEM_ID")); if (selectedPoem.main_poem != null) { // This poem is in the parents of another one poem = selectedPoem.main_poem; } else { poem = selectedPoem; } ViewGroup mainlist = (ViewGroup) findViewById(R.id.single_poem_main_list); View v; v = LayoutInflater.from(this).inflate(R.layout.post_row, mainlist, false); ((TextView) v.findViewById(R.id.title)) .setText(Util.convertMarkdown(poem.post_title, this)); ((TextView) v.findViewById(R.id.author)).setText(poem.post_author); if (poem.post_content != null && poem.post_content.length() > 0) { ((TextView) v.findViewById(R.id.content)) .setText(Util.convertMarkdown(poem.post_content, this)); ((TextView) v.findViewById(R.id.content)) .setMovementMethod(LinkMovementMethod.getInstance()); v.findViewById(R.id.content).setVisibility(View.VISIBLE); } mainlist.addView(v); for (ParentComment parent : poem.parents) { if (parent.is_poem != null) { v = LayoutInflater.from(this).inflate(R.layout.poem_row, mainlist, false); ((TextView) v.findViewById(R.id.content)) .setMovementMethod(LinkMovementMethod.getInstance()); Util.update_poem_row(parent.is_poem, v, true, false, this); } else { v = LayoutInflater.from(this) .inflate(R.layout.parents_list_row, mainlist, false); ((TextView) v.findViewById(R.id.content)) .setText(Util.convertMarkdown(parent.content, this)); ((TextView) v.findViewById(R.id.content)) .setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) v.findViewById(R.id.author)).setText(parent.author); } mainlist.addView(v); } if (poem.content != null && poem.content.length() > 0) { v = LayoutInflater.from(this).inflate(R.layout.poem_row, mainlist, false); ((TextView) v.findViewById(R.id.content)) .setMovementMethod(LinkMovementMethod.getInstance()); Util.update_poem_row(poem, v, true, false, this); mainlist.addView(v); } } @Override protected void onStart() { super.onStart(); mTracker.setScreenName("Poem"); mTracker.send(new HitBuilders.ScreenViewBuilder().build()); mTracker.send(new HitBuilders.EventBuilder() .setCategory("PoemPage") .setAction(Util.last(poem.link.split("/"))) .build()); } @Override public boolean onOptionsItemSelected(MenuItem item) { // handle arrow click here if (item.getItemId() == android.R.id.home) { finish(); // close this activity and return to preview activity (if there is any) } else if (item.getItemId() == R.id.action_copy) { mTracker.send(new HitBuilders.EventBuilder() .setCategory("copy") .setAction(Util.last(poem.link.split("/"))) .build()); ClipboardManager clipboard = (ClipboardManager) getSystemService(this.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("simple text", Util.convertMarkdown(selectedPoem.content, this).toString()); clipboard.setPrimaryClip(clip); Toast toast = Toast.makeText(this, "Poem copied to clipboard", Toast.LENGTH_SHORT); toast.show(); } else if (item.getItemId() == R.id.action_toReddit) { mTracker.send(new HitBuilders.EventBuilder() .setCategory("toReddit") .setAction(Util.last(poem.link.split("/"))) .build()); startActivity(new Intent(Intent.ACTION_VIEW).setData( Uri.parse(poem.link + "?context=100"))); } else if (item.getItemId() == R.id.action_share) { Toast toast = Toast.makeText(this, "sharing", Toast.LENGTH_SHORT); toast.show(); } else if (item.getItemId() == R.id.action_addToFavorites){ selectedPoem.toggleFavorite(this); if (selectedPoem.favorite){ mTracker.send(new HitBuilders.EventBuilder() .setCategory("favorite") .setAction(Util.last(selectedPoem.link.split("/"))) .build()); Toast toast = Toast.makeText(this, "added to favorites", Toast.LENGTH_SHORT); toast.show(); item.setIcon(R.drawable.ic_star_full); } else { Toast toast = Toast.makeText(this, "removed from favorites", Toast.LENGTH_SHORT); toast.show(); item.setIcon(R.drawable.ic_star_empty); } } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.poem_toolbar, menu); favoriteItem = menu.findItem(R.id.action_addToFavorites); if (selectedPoem.favorite){ favoriteItem.setIcon(R.drawable.ic_star_full); } MenuItem item = menu.findItem(R.id.action_share); ShareActionProvider mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item); Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, Util.convertMarkdown(selectedPoem.content, this)); mShareActionProvider.setShareIntent(shareIntent); return true; } }
package net.minecraftforge.common.util; import java.io.Serializable; import net.minecraft.block.state.IBlockState; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.fml.common.registry.GameRegistry.UniqueIdentifier; /** * Represents a captured snapshot of a block which will not change * automatically. * <p> * Unlike Block, which only one object can exist per coordinate, BlockSnapshot * can exist multiple times for any given Block. */ @SuppressWarnings({"serial", "deprecation"}) public class BlockSnapshot implements Serializable { private static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("forge.debugBlockSnapshot", "false")); public final BlockPos pos; public final int dimId; public transient IBlockState replacedBlock; public int flag; private final NBTTagCompound nbt; public transient World world; public final UniqueIdentifier blockIdentifier; public final int meta; public BlockSnapshot(World world, BlockPos pos, IBlockState state) { this.world = world; this.dimId = world.provider.getDimensionId(); this.pos = pos; this.replacedBlock = state; this.blockIdentifier = GameRegistry.findUniqueIdentifierFor(state.getBlock()); this.meta = state.getBlock().getMetaFromState(state); this.flag = 3; TileEntity te = world.getTileEntity(pos); if (te != null) { nbt = new NBTTagCompound(); te.writeToNBT(nbt); } else nbt = null; if (DEBUG) { System.out.printf("Created BlockSnapshot - [World: %s ][Location: %d,%d,%d ][Block: %s ][Meta: %d ]", world.getWorldInfo().getWorldName(), pos.getX(), pos.getY(), pos.getZ(), blockIdentifier, meta); } } public BlockSnapshot(World world, BlockPos pos, IBlockState state, NBTTagCompound nbt) { this.world = world; this.dimId = world.provider.getDimensionId(); this.pos = pos.getImmutable(); this.replacedBlock = state; this.blockIdentifier = GameRegistry.findUniqueIdentifierFor(state.getBlock()); this.meta = state.getBlock().getMetaFromState(state); this.flag = 3; this.nbt = nbt; if (DEBUG) { System.out.printf("Created BlockSnapshot - [World: %s ][Location: %d,%d,%d ][Block: %s ][Meta: %d ]", world.getWorldInfo().getWorldName(), pos.getX(), pos.getY(), pos.getZ(), blockIdentifier, meta); } } public BlockSnapshot(World world, BlockPos pos, IBlockState state, int flag) { this(world, pos, state); this.flag = flag; } /** * Raw constructor designed for serialization usages. */ public BlockSnapshot(int dimension, BlockPos pos, String modid, String blockName, int meta, int flag, NBTTagCompound nbt) { this.dimId = dimension; this.pos = pos.getImmutable(); this.flag = flag; this.blockIdentifier = new UniqueIdentifier(modid + ":" + blockName); this.meta = meta; this.nbt = nbt; } public static BlockSnapshot getBlockSnapshot(World world, BlockPos pos) { return new BlockSnapshot(world, pos, world.getBlockState(pos)); } public static BlockSnapshot getBlockSnapshot(World world, BlockPos pos, int flag) { return new BlockSnapshot(world, pos, world.getBlockState(pos), flag); } public static BlockSnapshot readFromNBT(NBTTagCompound tag) { NBTTagCompound nbt = tag.getBoolean("hasTE") ? null : tag.getCompoundTag("tileEntity"); return new BlockSnapshot( tag.getInteger("dimension"), new BlockPos(tag.getInteger("posX"), tag.getInteger("posY"), tag.getInteger("posZ")), tag.getString("blockMod"), tag.getString("blockName"), tag.getInteger("metadata"), tag.getInteger("flag"), nbt); } public IBlockState getCurrentBlock() { return world.getBlockState(pos); } public World getWorld() { if (this.world == null) { this.world = DimensionManager.getWorld(dimId); } return this.world; } public IBlockState getReplacedBlock() { if (this.replacedBlock == null) { this.replacedBlock = GameRegistry.findBlock(this.blockIdentifier.modId, this.blockIdentifier.name).getStateFromMeta(meta); } return this.replacedBlock; } public TileEntity getTileEntity() { if (nbt != null) return TileEntity.createAndLoadEntity(nbt); else return null; } public boolean restore() { return restore(false); } public boolean restore(boolean force) { return restore(force, true); } public boolean restore(boolean force, boolean applyPhysics) { IBlockState current = getCurrentBlock(); IBlockState replaced = getReplacedBlock(); if (current.getBlock() != replaced.getBlock() || current.getBlock().getMetaFromState(current) != replaced.getBlock().getMetaFromState(replaced)) { if (force) { world.setBlockState(pos, replaced, applyPhysics ? 3 : 2); } else { return false; } } world.setBlockState(pos, replaced, applyPhysics ? 3 : 2); world.markBlockForUpdate(pos); TileEntity te = null; if (nbt != null) { te = world.getTileEntity(pos); if (te != null) { te.readFromNBT(nbt); te.markDirty(); } } if (DEBUG) { System.out.printf("Restored BlockSnapshot with data [World: %s ][Location: %d,%d,%d ][Meta: %d ][Block: %s ][TileEntity: %s ][force: %s ][applyPhysics: %s]", world.getWorldInfo().getWorldName(), pos.getX(), pos.getY(), pos.getZ(), replaced.getBlock().getMetaFromState(replaced), replaced.getBlock().delegate.name(), te, force, applyPhysics); } return true; } public boolean restoreToLocation(World world, BlockPos pos, boolean force, boolean applyPhysics) { IBlockState current = getCurrentBlock(); IBlockState replaced = getReplacedBlock(); if (current.getBlock() != replaced.getBlock() || current.getBlock().getMetaFromState(current) != replaced.getBlock().getMetaFromState(replaced)) { if (force) { world.setBlockState(pos, replaced, applyPhysics ? 3 : 2); } else { return false; } } world.setBlockState(pos, replaced, applyPhysics ? 3 : 2); world.markBlockForUpdate(pos); TileEntity te = null; if (nbt != null) { te = world.getTileEntity(pos); if (te != null) { te.readFromNBT(nbt); te.markDirty(); } } if (DEBUG) { System.out.printf("Restored BlockSnapshot with data [World: %s ][Location: %d,%d,%d ][Meta: %d ][Block: %s ][TileEntity: %s ][force: %s ][applyPhysics: %s]", world.getWorldInfo().getWorldName(), pos.getX(), pos.getY(), pos.getZ(), replaced.getBlock().getMetaFromState(replaced), replaced.getBlock().delegate.name(), te, force, applyPhysics); } return true; } public void writeToNBT(NBTTagCompound compound) { compound.setString("blockMod", blockIdentifier.modId); compound.setString("blockName", blockIdentifier.name); compound.setInteger("posX", pos.getX()); compound.setInteger("posY", pos.getY()); compound.setInteger("posZ", pos.getZ()); compound.setInteger("flag", flag); compound.setInteger("dimension", dimId); compound.setInteger("metadata", meta); compound.setBoolean("hasTE", nbt != null); if (nbt != null) { compound.setTag("tileEntity", nbt); } } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BlockSnapshot other = (BlockSnapshot) obj; if (!this.pos.equals(other.pos)) { return false; } if (this.meta != other.meta) { return false; } if (this.dimId != other.dimId) { return false; } if (this.nbt != other.nbt && (this.nbt == null || !this.nbt.equals(other.nbt))) { return false; } if (this.world != other.world && (this.world == null || !this.world.equals(other.world))) { return false; } if (this.blockIdentifier != other.blockIdentifier && (this.blockIdentifier == null || !this.blockIdentifier.equals(other.blockIdentifier))) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 73 * hash + this.pos.getX(); hash = 73 * hash + this.pos.getY(); hash = 73 * hash + this.pos.getZ(); hash = 73 * hash + this.meta; hash = 73 * hash + this.dimId; hash = 73 * hash + (this.nbt != null ? this.nbt.hashCode() : 0); hash = 73 * hash + (this.world != null ? this.world.hashCode() : 0); hash = 73 * hash + (this.blockIdentifier != null ? this.blockIdentifier.hashCode() : 0); return hash; } }
package com.alsash.reciper.app; /** * Public keys for all elements in the Application */ public class AppContract { public static final int CACHE_MAX_ENTITIES = 1000; private static final String TAG = AppContract.class.getCanonicalName(); public static final String PAYLOAD_FLIP_BACK_TO_FRONT = TAG + ".payload_flip_back_to_front"; public static final String PAYLOAD_FLIP_FRONT_TO_BACK = TAG + ".payload_flip_front_to_back"; public static final String KEY_RECIPE_ID = TAG + ".key_recipe_id"; }
package com.bdb.bikedeboa.model.model; import com.bdb.bikedeboa.model.network.response.LocalFull; import com.bdb.bikedeboa.model.network.response.LocalLight; import io.realm.RealmList; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; public class Rack extends RealmObject { // Light description @PrimaryKey private int id; private double latitude, longitude; private float averageScore; // Complete description private String text; private String structureType; private String isPublic; // Not using boolean here because this info is not required -- and a null would break the program private String photoUrl; private String description; private String address; // private RealmList<Review> reviewList; private RealmList<Tag> tagList = new RealmList<>(); private int checkIns; private boolean isComplete = false; public Rack() {} public Rack(LocalLight localLight) { this.id = localLight.id; this.latitude = localLight.lat; this.longitude = localLight.lng; this.averageScore = localLight.average != null ? localLight.average : 0; } public void completeRack(LocalFull localFull) { this.text = localFull.text; this.structureType = localFull.structureType; this.isPublic = localFull.isPublic; this.photoUrl = localFull.photo; this.description = localFull.description; this.address = localFull.address; this.checkIns = localFull.checkIns; //this.reviewList this.tagList.clear(); for (LocalFull.Tag tag : localFull.tags) { this.tagList.add(new Tag(tag.name, tag.count)); } this.isComplete = true; // Doesn't consider if reviews were fetched -- second request needed } public int getId() { return id; } public double getLatitude() { return latitude; } public double getLongitude() { return longitude; } public float getAverageScore() { return averageScore; } public String getText() { return text; } public String getStructureType() { return structureType; } public String isPublic() { return isPublic; } public String getPhotoUrl() { return photoUrl; } public String getDescription() { return description; } public String getAddress() { return address; } public int getCheckIns() { return checkIns; } public boolean isComplete() { return isComplete; } }
package net.sf.jabref.model.search.rules; import net.sf.jabref.model.strings.StringUtil; public class SearchRules { /** * Returns the appropriate search rule that fits best to the given parameter. */ public static SearchRule getSearchRuleByQuery(String query, boolean caseSensitive, boolean regex) { if (StringUtil.isBlank(query)) { return new ContainBasedSearchRule(caseSensitive); } // this searches specified fields if specified, // and all fields otherwise SearchRule searchExpression = new GrammarBasedSearchRule(caseSensitive, regex); if (searchExpression.validateSearchStrings(query)) { return searchExpression; } else { return getSearchRule(caseSensitive, regex); } } private static SearchRule getSearchRule(boolean caseSensitive, boolean regex) { if (regex) { return new RegexBasedSearchRule(caseSensitive); } else { return new ContainBasedSearchRule(caseSensitive); } } }
package com.dreamteam.paca; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.TargetApi; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentSender; import android.graphics.Bitmap; import android.location.Location; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.provider.MediaStore; import android.provider.Settings; import android.support.v4.util.LruCache; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.OvershootInterpolator; import android.widget.ImageButton; import android.widget.ListView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationServices; import org.json.JSONArray; import org.json.JSONException; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import butterknife.InjectView; import butterknife.OnClick; public class GalleryActivity extends BaseActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,FeedAdapter.OnFeedItemClickListener, FeedContextMenu.OnFeedContextMenuItemClickListener { public static final String TAG = GalleryActivity.class.getName(); private static final int REQUEST_CAMERA = 0; private static final int REQUEST_TAKE_PHOTO = 1; private static final String GET_PICTURE_ADDRESS_URI = "http://nthai.cs.trincoll.edu/PacaServer/retrieve.php"; private static final String LONGITUDE = "longitude"; private static final String LATITUDE = "latitude"; private static final String RESOLVING_ERROR = "Resolving error"; private static final int REQUEST_RESOLVE_ERROR = 1001; private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private GoogleApiClient mGoogleApiClient; private Location mLocation; private boolean mResolvingError; public static final String ACTION_SHOW_LOADING_ITEM = "action_show_loading_item"; private static final int ANIM_DURATION_TOOLBAR = 300; private static final int ANIM_DURATION_FAB = 400; @InjectView(R.id.rvFeed) RecyclerView rvFeed; @InjectView(R.id.btnCreate) ImageButton btnCreate; private FeedAdapter feedAdapter; private boolean pendingIntroAnimation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery_host); this.getSupportActionBar().setElevation(0); mRequestQueue = getRequestQueue(); mImageLoader = getImageLoader(); mGoogleApiClient = getGoogleApiClient(); setupFeed(); if (savedInstanceState == null) { pendingIntroAnimation = true; } else { feedAdapter.updateItems(false); } } private void setupFeed() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this) { @Override protected int getExtraLayoutSpace(RecyclerView.State state) { return 300; } }; rvFeed.setLayoutManager(linearLayoutManager); feedAdapter = new FeedAdapter(this); feedAdapter.setOnFeedItemClickListener(this); rvFeed.setAdapter(feedAdapter); rvFeed.setOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { FeedContextMenuManager.getInstance().onScrolled(recyclerView, dx, dy); } }); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (ACTION_SHOW_LOADING_ITEM.equals(intent.getAction())) { showFeedLoadingItemDelayed(); } } private void showFeedLoadingItemDelayed() { new Handler().postDelayed(new Runnable() { @Override public void run() { rvFeed.smoothScrollToPosition(0); feedAdapter.showLoadingView(); } }, 500); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(RESOLVING_ERROR, mResolvingError); } @Override public void onConnected(Bundle bundle) { mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, GET_PICTURE_ADDRESS_URI, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { fetchImage(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { new AlertDialog.Builder(GalleryActivity.this) .setMessage(R.string.cant_contact_server) .create() .show(); } }); jsonArrayRequest.setTag(TAG); getRequestQueue().add(jsonArrayRequest); } @Override public void onConnectionFailed(ConnectionResult connectionResult) { if (!mResolvingError) { if (connectionResult.hasResolution()) { try { connectionResult.startResolutionForResult(this, REQUEST_RESOLVE_ERROR); mResolvingError = true; } catch (IntentSender.SendIntentException e) { mGoogleApiClient.connect(); } } else { Dialog dialog = GooglePlayServicesUtil .getErrorDialog(connectionResult.getErrorCode(), this, REQUEST_RESOLVE_ERROR); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { mResolvingError = false; } }); dialog.show(); mResolvingError = true; } } } @Override public void onConnectionSuspended(int i) { showSettingsAlert(); } @Override protected void onStart() { super.onStart(); if (!mResolvingError) { getGoogleApiClient().connect(); } } @Override protected void onStop() { super.onStop(); getGoogleApiClient().disconnect(); if (getRequestQueue() != null) { getRequestQueue().cancelAll(TAG); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (resultCode) { case RESULT_OK: if (!getGoogleApiClient().isConnecting() && !getGoogleApiClient().isConnected()) { getGoogleApiClient().connect(); } break; } switch (requestCode) { case REQUEST_RESOLVE_ERROR: mResolvingError = false; break; case REQUEST_TAKE_PHOTO: sendPhoto(null); /*Bitmap bitmap = (Bitmap) data.getExtras().get("data"); if (bitmap != null) { try { sendPhoto(bitmap); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }*/ break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); if (pendingIntroAnimation) { pendingIntroAnimation = false; startIntroAnimation(); } return true; } @TargetApi(14) private void startIntroAnimation() { btnCreate.setTranslationY(2 * getResources().getDimensionPixelOffset(R.dimen.btn_fab_size)); int actionbarSize = Utils.dpToPx(56); getToolbar().setTranslationY(-actionbarSize); getIvLogo().setTranslationY(-actionbarSize); getInboxMenuItem().getActionView().setTranslationY(-actionbarSize); getToolbar().animate() .translationY(0) .setDuration(ANIM_DURATION_TOOLBAR) .setStartDelay(300); getIvLogo().animate() .translationY(0) .setDuration(ANIM_DURATION_TOOLBAR) .setStartDelay(400); getInboxMenuItem().getActionView().animate() .translationY(0) .setDuration(ANIM_DURATION_TOOLBAR) .setStartDelay(500) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { startContentAnimation(); } }) .start(); } @TargetApi(14) private void startContentAnimation() { btnCreate.animate() .translationY(0) .setInterpolator(new OvershootInterpolator(1.f)) .setStartDelay(300) .setDuration(ANIM_DURATION_FAB) .start(); feedAdapter.updateItems(true); } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(this); } return mRequestQueue; } public GoogleApiClient getGoogleApiClient() { if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } return mGoogleApiClient; } public ImageLoader getImageLoader() { if (mImageLoader == null) { mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<>(20); @Override public Bitmap getBitmap(String url) { return cache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); } return mImageLoader; } private void fetchImage(JSONArray array) { ArrayList<String> initialAddresses = new ArrayList<>(); try { for (int i = 0; i < array.length(); i++) { initialAddresses.add(array.getString(i)); } } catch (JSONException e) { Log.e(TAG, JSONException.class.getName(), e); } //ListView imageStream = (ListView) findViewById(R.id.main_gallery); //imageStream.setAdapter(new ImageAdapter(this, initialAddresses)); } public void showSettingsAlert() { new AlertDialog.Builder(this) .setTitle(R.string.enable_gps) .setMessage(R.string.enable_gps_message) .setPositiveButton(R.string.button_positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }) .setNegativeButton(R.string.button_negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); } private void dispatchTakePictureIntent() { Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Ensure that there's a camera activity to handle the intent if (takePictureIntent.resolveActivity(getPackageManager()) != null) { // Create the File where the photo should go File photoFile = null; try { photoFile = createImageFile(); } catch (IOException ex) { // Error occurred while creating the File } // Continue only if the File was successfully created if (photoFile != null) { takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO); } } } /* This function returns an image file created from the image * in order to upload the image to the server */ private File createImageFile() throws IOException { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; String storageDir = Environment.getExternalStorageDirectory() + "/picupload"; File dir = new File(storageDir); if (!dir.exists()) dir.mkdir(); File image = new File(storageDir + "/" + imageFileName + ".jpg"); return image; } public void sendPhoto(Bitmap bitmap) { new AlertDialog.Builder(this) .setMessage("Uploaded successfully") .create() .show(); } @Override public void onCommentsClick(View v, int position) { } @Override public void onMoreClick(View v, int itemPosition) { FeedContextMenuManager.getInstance().toggleContextMenuFromView(v, itemPosition, this); } @Override public void onProfileClick(View v) { } @Override public void onReportClick(int feedItem) { FeedContextMenuManager.getInstance().hideContextMenu(); } @Override public void onSharePhotoClick(int feedItem) { FeedContextMenuManager.getInstance().hideContextMenu(); } @Override public void onCopyShareUrlClick(int feedItem) { FeedContextMenuManager.getInstance().hideContextMenu(); } @Override public void onCancelClick(int feedItem) { FeedContextMenuManager.getInstance().hideContextMenu(); } @OnClick(R.id.btnCreate) public void onTakePhotoClick() { int[] startingLocation = new int[2]; btnCreate.getLocationOnScreen(startingLocation); startingLocation[0] += btnCreate.getWidth() / 2; Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraIntent.resolveActivity(getPackageManager()) != null) { dispatchTakePictureIntent(); } //TakePhotoActivity.startCameraFromLocation(startingLocation, this); //overridePendingTransition(0, 0); } }
package com.mikepenz.unsplash.models; import android.support.v7.graphics.Palette; import java.io.Serializable; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class Image implements Serializable { private static final DateFormat sdf = SimpleDateFormat.getDateInstance(); private String color; private String image_src; private String author; private Date date; private Date modified_date; private float ratio; private int width; private int height; private int featured; private int category; transient private Palette.Swatch swatch; public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getUrl() { return image_src; } public String getHighResImage(int minWidth, int minHeight) { String url = image_src + "?q=100&fm=jpg"; //minimize processing costs of unsplash image hosting //try to eliminate the white line on top if (minWidth > 0 && minHeight > 0) { float phoneRatio = (1.0f * minWidth) / minHeight; if (phoneRatio < getRatio()) { if (minHeight < 1080) { //url = url + "&h=" + minHeight; url = url + "&h=" + 1080; } } else { if (minWidth < 1920) { //url = url + "&w=" + minWidth; url = url + "&w=" + 1920; } } } return url; } public String getImage_src(int screenWidth) { return image_src + "?q=75&w=720&fit=max&fm=jpg"; /* wait with this one for now. i don't want to bring up the generation quota of unsplash String url = image_src + "?q=75&fit=max&fm=jpg"; if (screenWidth > 0) { //it's enough if we load an image with 2/3 of the size url = url + "&w=" + (screenWidth / 3 * 2); } return url; */ } public void setImage_src(String image_src) { this.image_src = image_src; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public Date getDate() { return date; } public String getReadableDate() { if (date != null) { return sdf.format(date); } else { return ""; } } public void setDate(Date date) { this.date = date; } public Date getModified_date() { return modified_date; } public String getReadableModified_Date() { if (modified_date != null) { return sdf.format(modified_date); } else { return ""; } } public void setModified_date(Date modified_date) { this.modified_date = modified_date; } public float getRatio() { return ratio; } public void setRatio(float ratio) { this.ratio = ratio; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public Palette.Swatch getSwatch() { return swatch; } public void setSwatch(Palette.Swatch swatch) { this.swatch = swatch; } public int getFeatured() { return featured; } public void setFeatured(int featured) { this.featured = featured; } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } }
package org.agmip.translators.dssat; import java.io.BufferedReader; import java.io.CharArrayReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import org.agmip.core.types.AdvancedHashMap; import org.agmip.core.types.TranslatorInput; /** * DSSAT Experiment Data I/O API Class * * @author Meng Zhang * @version 1.0 */ public abstract class DssatCommonInput implements TranslatorInput { protected String[] flg = new String[3]; protected String defValR = "-99.0"; protected String defValC = ""; protected String defValI = "-99"; protected String defValD = "20110101"; protected String jsonKey = "unknown"; /** * DSSAT Data Output method for Controller using * * @param m The holder for BufferReader objects for all files * @return result data holder object */ protected abstract AdvancedHashMap readFile(HashMap m) throws IOException; /** * DSSAT XFile Data input method * * @param arg0 file name * @return result data holder object */ @Override public AdvancedHashMap readFile(String arg0) { AdvancedHashMap ret = new AdvancedHashMap(); String filePath = arg0; try { // read file by file ret = readFile(getBufferReader(filePath)); } catch (Exception e) { //System.out.println(e.getMessage()); e.printStackTrace(); } return ret; } /** * Set reading flgs for reading lines * * @param line the string of reading line */ protected void judgeContentType(String line) { // Section Title line if (line.startsWith("*")) { setTitleFlgs(line); } // Data title line else if (line.startsWith("@")) { flg[1] = line.substring(1).trim().toLowerCase(); flg[2] = "title"; } // Comment line else if (line.startsWith("!")) { flg[2] = "comment"; } // Data line else if (!line.trim().equals("")) { flg[2] = "data"; } // Continued blank line else if (flg[2].equals("blank")) { flg[0] = ""; flg[1] = ""; flg[2] = "blank"; } else { // flg[0] = ""; flg[1] = ""; flg[2] = "blank"; } } /** * Set reading flgs for title lines (the line marked with *) * * @param line the string of reading line */ protected abstract void setTitleFlgs(String line); /** * Translate data str from "yyddd" to "yyyymmdd" * * @param str date string with format of "yyddd" * @return result date string with format of "yyyymmdd" */ protected String translateDateStr(String str) { return translateDateStr(str, "0"); } /** * Translate data str from "yyddd" to "yyyymmdd" plus days you want * * @param startDate date string with format of "yyydd" * @param strDays the number of days need to be added on * @return result date string with format of "yyyymmdd" */ protected String translateDateStr(String startDate, String strDays) { // Initial Calendar object Calendar cal = Calendar.getInstance(); int days; int year; if (startDate == null || startDate.length() > 5 || startDate.length() < 1) { //throw new Exception(""); return "-99"; //defValD; } try { startDate = String.format("%05d", Integer.parseInt(startDate)); days = Double.valueOf(strDays).intValue(); // Set date with input value year = Integer.parseInt(startDate.substring(0, 2)); year += year <= 15 ? 2000 : 1900; // P.S. 2015 is the cross year for the current version cal.set(Calendar.YEAR, year); cal.set(Calendar.DAY_OF_YEAR, Integer.parseInt(startDate.substring(2))); cal.add(Calendar.DATE, days); // translatet to yyddd format return String.format("%1$04d%2$02d%3$02d", cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH)); } catch (Exception e) { // if tranlate failed, then use default value for date // sbError.append("! Waring: There is a invalid date [").append(startDate).append("]"); return "-99"; //formatDateStr(defValD); } } /** * Divide the data in the line into a map * * @param line The string of line read from data file * @param formats The definition of length for each data field (String itemName : Integer length) * @return the map contains divided data with keys from original string */ protected AdvancedHashMap readLine(String line, LinkedHashMap<String, Integer> formats) { AdvancedHashMap ret = new AdvancedHashMap(); int length; String tmp; for (String key : formats.keySet()) { // To avoid to be over limit of string lenght length = Math.min((Integer) formats.get(key), line.length()); if (!((String) key).equals("")) { tmp = line.substring(0, length).trim(); // if the value is in valid keep blank string in it if (checkValidValue(tmp)) { ret.put(key, tmp); } else { ret.put(key, ""); // P.S. "" means missing or invalid value } } line = line.substring(length); } return ret; } /** * Get exname with normal format * * @return exname */ protected String getExName() { // TODO String ret = ""; return ret; } /** * Check if input is a valid value * * @return check result */ protected boolean checkValidValue(String value) { if (value.trim().equals(defValC) || value.equals(defValI) || value.equals(defValR)) { return false; } else { return true; } } /** * Get BufferReader for each type of file * * @param filePath the full path of the input file * @return result the holder of BufferReader for different type of files * @throws FileNotFoundException * @throws IOException */ protected HashMap getBufferReader(String filePath) throws FileNotFoundException, IOException { HashMap result = new HashMap(); InputStream in; LinkedHashMap mapW = new LinkedHashMap(); LinkedHashMap mapS = new LinkedHashMap(); String[] tmp = filePath.split("[\\/]"); // If input File is ZIP file if (filePath.toUpperCase().endsWith(".ZIP")) { ZipEntry entry; in = new ZipInputStream(new FileInputStream(filePath)); while ((entry = ((ZipInputStream) in).getNextEntry()) != null) { if (!entry.isDirectory()) { if (entry.getName().matches(".+\\.\\w{2}[Xx]")) { result.put("X", getBuf(in, (int) entry.getSize())); } else if (entry.getName().toUpperCase().endsWith(".WTH")) { mapW.put(entry.getName().toUpperCase(), getBuf(in, (int) entry.getSize())); } else if (entry.getName().toUpperCase().endsWith(".SOL")) { mapS.put(entry.getName().toUpperCase(), getBuf(in, (int) entry.getSize())); } else if (entry.getName().matches(".+\\.\\w{2}[Aa]")) { result.put("A", getBuf(in, (int) entry.getSize())); } else if (entry.getName().matches(".+\\.\\w{2}[Tt]")) { result.put("T", getBuf(in, (int) entry.getSize())); } } } } // If input File is not ZIP file else { in = new FileInputStream(filePath); if (filePath.matches(".+\\.\\w{2}[Xx]")) { result.put("X", new BufferedReader(new InputStreamReader(in))); } else if (filePath.toUpperCase().endsWith(".WTH")) { mapW.put(filePath, new BufferedReader(new InputStreamReader(in))); } else if (filePath.toUpperCase().endsWith(".SOL")) { mapS.put(filePath, new BufferedReader(new InputStreamReader(in))); } else if (filePath.matches(".+\\.\\w{2}[Aa]")) { result.put("A", new BufferedReader(new InputStreamReader(in))); } else if (filePath.matches(".+\\.\\w{2}[Tt]")) { result.put("T", new BufferedReader(new InputStreamReader(in))); } } result.put("W", mapW); result.put("S", mapS); result.put("Z", tmp[tmp.length - 1]); return result; } /** * Get BufferReader object from Zip entry * * @param in The input stream of zip file * @param size The entry size * @return result The BufferReader object for current entry * @throws IOException */ private BufferedReader getBuf(InputStream in, int size) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(in)); char[] buf = new char[size]; br.read(buf); return new BufferedReader(new CharArrayReader(buf)); } /** * compress the data in a map object * * @param m input map */ protected void compressData(AdvancedHashMap m) { Object[] keys = m.keySet().toArray(); Object key; for (int i = 0; i < keys.length; i++) { key = keys[i]; if (m.get(key).getClass().equals(ArrayList.class)) { if (((ArrayList) m.get(key)).isEmpty()) { // Delete the empty list m.remove(key); } else { // iterate sub array nodes compressData((ArrayList) m.get(key)); } } else if (m.get(key).getClass().equals(AdvancedHashMap.class)) { if (((AdvancedHashMap) m.get(key)).isEmpty()) { // Delete the empty list m.remove(key); } else { // iterate sub data nodes compressData((AdvancedHashMap) m.get(key)); } } else { // ignore other type nodes } } } /** * compress the data in an ArrayList object * * @param arr input ArrayList * */ protected void compressData(ArrayList arr) { AdvancedHashMap fstData = null; // The first data record (Map type) AdvancedHashMap cprData = null; // The following data record which will be compressed for (int i = 0; i < arr.size(); i++) { if (arr.get(i).getClass().equals(ArrayList.class)) { // iterate sub array nodes compressData((ArrayList) arr.get(i)); } else if (arr.get(i).getClass().equals(AdvancedHashMap.class)) { // iterate sub data nodes compressData((AdvancedHashMap) arr.get(i)); // Compress data for current array if (fstData == null) { // Get first data node fstData = (AdvancedHashMap) arr.get(i); } else { cprData = (AdvancedHashMap) arr.get(i); Object[] keys = cprData.keySet().toArray(); // The missing data will be given a "" value; Only data item (String type) will be processed for (Object key : fstData.keySet()) { if (fstData.get(key).getClass().equals(String.class) && !cprData.containsKey(key)) { cprData.put(key, ""); } } // The repeated data will be deleted; Only data item (String type) will be processed for (Object key : keys) { if (cprData.get(key).getClass().equals(String.class) && cprData.get(key).equals(fstData.get(key))) { cprData.remove(key); } } } } else { } } } /** * Add the new item into array by having same key value * * @param arr the target array * @param item the input item which will be added into array * @param key the primary key item's name */ protected void addToArray(ArrayList arr, AdvancedHashMap item, Object key) { AdvancedHashMap elem; boolean unmatchFlg = true; for (int i = 0; i < arr.size(); i++) { elem = (AdvancedHashMap) arr.get(i); if (!key.getClass().isArray()) { if (elem.get(key).equals(item.get(key))) { elem.put(item); unmatchFlg = false; break; } } else { Object[] keys = (Object[]) key; boolean equalFlg = true; for (int j = 0; j < keys.length; j++) { if (!elem.get(keys[j]).equals(item.get(keys[j]))) { equalFlg = false; break; } } if (equalFlg) { elem.put(item); unmatchFlg = false; break; } } } if (unmatchFlg) { arr.add(item); } } }
package com.pixnfit.async; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import android.widget.ImageView; import com.pixnfit.R; import com.pixnfit.utils.LRUCache; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; public class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> { private static final String TAG = BitmapWorkerTask.class.getSimpleName(); private static final Map<URL, Bitmap> BITMAP_CACHE = new LRUCache<>(16); private final WeakReference<ImageView> imageViewReference; private String imageUrl; private int width; private int height; public BitmapWorkerTask(ImageView imageView, int width, int height) { // Use a WeakReference to ensure the ImageView can be garbage collected this.imageViewReference = new WeakReference<ImageView>(imageView); this.width = width; this.height = height; } // Decode image in background. @Override protected Bitmap doInBackground(String... imagesUrls) { try { imageUrl = imagesUrls[0]; URL url = new URL(imageUrl); url = new URL(Uri.parse(url.toString()).buildUpon().clearQuery().appendQueryParameter("width", Integer.toString(width)).appendQueryParameter("height", Integer.toString(height)).build().toString()); if (!BITMAP_CACHE.containsKey(url)) { try { Bitmap bitmap = getBitmapFromUrl(url); BITMAP_CACHE.put(url, bitmap); } catch (IOException e) { Log.e(TAG, "getBitmapFromUrl: failed", e); } } return BITMAP_CACHE.get(url); } catch (IOException e) { Log.e(TAG, "doInBackground: failed", e); return null; } } public static Bitmap getBitmapFromUrl(URL url) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.connect(); InputStream input = connection.getInputStream(); return BitmapFactory.decodeStream(input); } // Once complete, see if ImageView is still around and set bitmap. @Override protected void onPostExecute(Bitmap bitmap) { if (imageViewReference != null && bitmap != null) { final ImageView imageView = imageViewReference.get(); if (imageView != null) { if (imageView.getTag(R.id.tagImageUrl).equals(imageUrl)) { // C'est cette image qu'on souhaite afficher dans cette imageView, // donc on applique le bitmap imageView.setImageBitmap(bitmap); } } } } }
package edu.uci.lighthouse.core; import java.util.Collection; import java.util.LinkedList; import java.util.Properties; import org.apache.log4j.Logger; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.ui.IStartup; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; import edu.uci.lighthouse.core.controller.Controller; import edu.uci.lighthouse.core.controller.SVNRecorder; import edu.uci.lighthouse.core.listeners.IPluginListener; import edu.uci.lighthouse.core.listeners.JavaFileChangedReporter; import edu.uci.lighthouse.core.listeners.SVNEventReporter; import edu.uci.lighthouse.core.preferences.DatabasePreferences; import edu.uci.lighthouse.core.preferences.UserPreferences; import edu.uci.lighthouse.core.util.UserDialog; import edu.uci.lighthouse.core.util.WorkbenchUtility; import edu.uci.lighthouse.model.LighthouseAuthor; import edu.uci.lighthouse.model.LighthouseModel; import edu.uci.lighthouse.model.jpa.JPAException; import edu.uci.lighthouse.model.jpa.JPAUtility; import edu.uci.lighthouse.model.jpa.LHAuthorDAO; /** * The activator class controls the plug-in life cycle */ public class Activator extends AbstractUIPlugin implements IPropertyChangeListener, IStartup { private static Logger logger = Logger.getLogger(Activator.class); // The plug-in ID public static final String PLUGIN_ID = "edu.uci.lighthouse.core"; // The shared instance private static Activator plugin; Collection<IPluginListener> listeners = new LinkedList<IPluginListener>(); private LighthouseAuthor author; // private SSHTunnel sshTunnel; /** * The constructor */ public Activator() { Controller controller = new Controller(); JavaFileChangedReporter jReporter = new JavaFileChangedReporter(); jReporter.addJavaFileStatusListener(controller); SVNEventReporter svnReporter = new SVNEventReporter(); svnReporter.addSVNEventListener(controller); svnReporter.addSVNEventListener(new SVNRecorder()); listeners.add(jReporter); listeners.add(svnReporter); listeners.add(controller); } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) */ public void start(final BundleContext context) throws Exception { super.start(context); plugin = this; logger.debug("Core Started"); //This code exist here just for test purposes. We delete the preferences to simulate the behavior when the user first open lighthouse // UserPreferences.clear(); // DatabasePreferences.clear(); // sshTunnel = new SSHTunnel(DatabasePreferences.getAllSettings()); // if (DatabasePreferences.isConnectingUsingSSH()) { // sshTunnel.start(context); //FIXME: Think about the right place to put this code logger.debug("Starting JPA..."); JPAUtility.initializeEntityManagerFactory(DatabasePreferences.getDatabaseSettings()); Activator.getDefault().getPreferenceStore().addPropertyChangeListener(this); final Job job = new Job("Starting Lighthouse...") { @Override protected IStatus run(IProgressMonitor monitor) { try { monitor.beginTask("", IProgressMonitor.UNKNOWN); for (IPluginListener listener : listeners) { listener.start(context); } } catch (Exception e) { logger.error(e,e); } finally { monitor.done(); } return Status.OK_STATUS; } }; // job.setUser(true); job.schedule(); // Starting listeners // for (IPluginListener listener : listeners) { // logger.debug("Starting "+listener.getClass().getSimpleName()+"..."); // listener.start(context); //NEW } /* * (non-Javadoc) * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) */ public void stop(BundleContext context) throws Exception { Activator.getDefault().getPreferenceStore().removePropertyChangeListener(this); // Stopping listeners for (IPluginListener listener : listeners) { listener.stop(context); } JPAUtility.shutdownEntityManagerFactory(); // sshTunnel.stop(context); plugin = null; super.stop(context); } /** * Returns the shared instance * * @return the shared instance */ public static Activator getDefault() { return plugin; } /** * Returns an image descriptor for the image file at the given * plug-in relative path * * @param path the path * @return the image descriptor */ public static ImageDescriptor getImageDescriptor(String path) { return imageDescriptorFromPlugin(PLUGIN_ID, path); } public LighthouseAuthor getAuthor() { if (author == null){ String userName = getUsername(); if ("".equals(userName)){ WorkbenchUtility.openPreferences(); } else { author = new LighthouseAuthor(userName); } } return author; } @Override public void propertyChange(PropertyChangeEvent event) { // Username has changed try { if (UserPreferences.USERNAME.equals(event.getProperty())) { String userName = getUsername(); if (!"".equals(userName)) { LighthouseAuthor user = new LighthouseAuthor(userName); new LHAuthorDAO().save(user); author = user; } } } catch (JPAException e) { UserDialog.openError(e.getMessage()); } } private String getUsername(){ String result = ""; Properties userSettings = UserPreferences.getUserSettings(); String userName = userSettings.getProperty(UserPreferences.USERNAME); if (userName != null) { result = userName; } return result; } @Override public void earlyStartup() { logger.debug("CoreStartup earlyStartup..."); } }
package com.mapswithme.util.sharing; import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.provider.Telephony; import com.mapswithme.maps.Framework; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.bookmarks.data.MapObject.MapObjectType; import com.mapswithme.util.Utils; import com.mapswithme.util.statistics.Statistics; import java.util.HashMap; import java.util.Map; public abstract class ShareAction { public final static int ID_SMS = 0xfff1; public final static int ID_EMAIL = 0xfff2; public final static int ID_ANY = 0xffff; @SuppressLint("UseSparseArrays") public final static Map<Integer, ShareAction> ACTIONS = new HashMap<>(); /* Actions*/ private final static SmsShareAction SMS_SHARE = new SmsShareAction(); private final static EmailShareAction EMAIL_SHARE = new EmailShareAction(); private final static AnyShareAction ANY_SHARE = new AnyShareAction(); /* Extras*/ private static final String EXTRA_SMS_BODY = "sms_body"; private static final String EXTRA_SMS_TEXT = Intent.EXTRA_TEXT; /* Types*/ private static final String TYPE_MESSAGE_RFC822 = "message/rfc822"; private static final String TYPE_TEXT_PLAIN = "text/plain"; /* URIs*/ private static final String URI_STRING_SMS = "sms:"; protected final int mId; protected final int mNameResId; protected final Intent mBaseIntent; public static SmsShareAction getSmsShare() { return SMS_SHARE; } public static EmailShareAction getEmailShare() { return EMAIL_SHARE; } public static AnyShareAction getAnyShare() { return ANY_SHARE; } protected ShareAction(int id, int nameResId, Intent baseIntent) { mId = id; mNameResId = nameResId; mBaseIntent = baseIntent; } public Intent getIntent() { return new Intent(mBaseIntent); } public int getId() { return mId; } public boolean isSupported(Context context) { return Utils.isIntentSupported(context, getIntent()); } /** * BASE share method */ public void shareMapObject(Activity activity, MapObject mapObject) { SharingHelper.shareOutside(new MapObjectShareable(activity, mapObject) .setBaseIntent(new Intent(mBaseIntent)), mNameResId); } /** * SMS */ public static class SmsShareAction extends ShareAction { protected SmsShareAction() { super(ID_SMS, R.string.share_by_message, new Intent(Intent.ACTION_VIEW).setData(Uri.parse(URI_STRING_SMS))); } public void shareWithText(Activity activity, String body) { Intent smsIntent; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { final String defaultSms = Telephony.Sms.getDefaultSmsPackage(activity); smsIntent = new Intent(Intent.ACTION_SEND); smsIntent.setType("text/plain"); smsIntent.putExtra(EXTRA_SMS_TEXT, body); if (defaultSms != null) smsIntent.setPackage(defaultSms); } else { smsIntent = getIntent(); smsIntent.putExtra(EXTRA_SMS_BODY, body); } activity.startActivity(smsIntent); } @Override public void shareMapObject(Activity activity, MapObject mapObject) { final String ge0Url = Framework.nativeGetGe0Url(mapObject.getLat(), mapObject.getLon(), mapObject.getScale(), ""); final String httpUrl = Framework.getHttpGe0Url(mapObject.getLat(), mapObject.getLon(), mapObject.getScale(), ""); final int bodyId = mapObject.getType() == MapObjectType.MY_POSITION ? R.string.my_position_share_sms : R.string.bookmark_share_sms; final String body = activity.getString(bodyId, ge0Url, httpUrl); shareWithText(activity, body); Statistics.INSTANCE.trackPlaceShared(this.getClass().getSimpleName()); } } /** * EMAIL */ public static class EmailShareAction extends ShareAction { protected EmailShareAction() { super(ID_EMAIL, R.string.share_by_email, new Intent(Intent.ACTION_SEND).setType(TYPE_MESSAGE_RFC822)); } } /** * ANYTHING */ public static class AnyShareAction extends ShareAction { protected AnyShareAction() { super(ID_ANY, R.string.share, new Intent(Intent.ACTION_SEND).setType(TYPE_TEXT_PLAIN)); } public static void share(final Activity activity, final String body) { SharingHelper.shareOutside(new TextShareable(activity, body)); } } static { ACTIONS.put(ID_ANY, getAnyShare()); ACTIONS.put(ID_EMAIL, getEmailShare()); ACTIONS.put(ID_SMS, getSmsShare()); } }
package com.samourai.wallet.send; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.os.Looper; import android.widget.Toast; import android.util.Log; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.api.APIFactory; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.PrivKeyReader; import com.samourai.wallet.R; import org.bitcoinj.core.Coin; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import java.math.BigInteger; import java.util.HashMap; import java.util.List; public class SweepUtil { private static Context context = null; private static SweepUtil instance = null; private static UTXO utxoP2PKH = null; private static UTXO utxoP2SH_P2WPKH = null; private static String addressP2PKH = null; private static String addressP2SH_P2WPKH = null; private SweepUtil() { ; } public static SweepUtil getInstance(Context ctx) { context = ctx; if(instance == null) { instance = new SweepUtil(); } return instance; } public void sweep(final PrivKeyReader privKeyReader, final boolean sweepBIP49) { new Thread(new Runnable() { @Override public void run() { Looper.prepare(); try { if(privKeyReader == null || privKeyReader.getKey() == null || !privKeyReader.getKey().hasPrivKey()) { Toast.makeText(context, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); return; } String address = null; UTXO utxo = null; if(sweepBIP49) { utxo = utxoP2SH_P2WPKH; address = addressP2SH_P2WPKH; } else { addressP2PKH = privKeyReader.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); Log.d("SweepUtil", "address derived P2PKH:" + addressP2PKH); addressP2SH_P2WPKH = addressP2SH_P2WPKH = new SegwitAddress(privKeyReader.getKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()).getAddressAsString(); Log.d("SweepUtil", "address derived P2SH_P2WPKH:" + addressP2SH_P2WPKH); utxoP2PKH = APIFactory.getInstance(context).getUnspentOutputsForSweep(addressP2PKH); utxoP2SH_P2WPKH = APIFactory.getInstance(context).getUnspentOutputsForSweep(addressP2SH_P2WPKH); utxo = utxoP2PKH; address = addressP2PKH; } if(utxo != null) { long total_value = 0L; final List<MyTransactionOutPoint> outpoints = utxo.getOutpoints(); for(MyTransactionOutPoint outpoint : outpoints) { total_value += outpoint.getValue().longValue(); } final BigInteger fee; if(sweepBIP49) { fee = FeeUtil.getInstance().estimatedFeeSegwit(0, outpoints.size(), 1); } else { fee = FeeUtil.getInstance().estimatedFee(outpoints.size(), 1); } final long amount = total_value - fee.longValue(); // Log.d("BalanceActivity", "Total value:" + total_value); // Log.d("BalanceActivity", "Amount:" + amount); // Log.d("BalanceActivity", "Fee:" + fee.toString()); String message = "Sweep " + Coin.valueOf(amount).toPlainString() + " from " + address + " (fee:" + Coin.valueOf(fee.longValue()).toPlainString() + ")?"; AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.app_name); builder.setMessage(message); builder.setCancelable(false); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { final ProgressDialog progress = new ProgressDialog(context); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(context.getString(R.string.please_wait_sending)); progress.show(); String receive_address = null; if(PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_SEGWIT, true) == true) { receive_address = AddressFactory.getInstance(context).getBIP49(AddressFactory.RECEIVE_CHAIN).getAddressAsString(); } else { receive_address = AddressFactory.getInstance(context).get(AddressFactory.RECEIVE_CHAIN).getAddressString(); } final HashMap<String, BigInteger> receivers = new HashMap<String, BigInteger>(); receivers.put(receive_address, BigInteger.valueOf(amount)); org.bitcoinj.core.Transaction tx = SendFactory.getInstance(context).makeTransaction(0, outpoints, receivers); tx = SendFactory.getInstance(context).signTransactionForSweep(tx, privKeyReader); final String hexTx = new String(Hex.encode(tx.bitcoinSerialize())); // Log.d("BalanceActivity", hexTx); String response = null; try { if(PrefsUtil.getInstance(context).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true) { if(TrustedNodeUtil.getInstance().isSet()) { response = PushTx.getInstance(context).trustedNode(hexTx); JSONObject jsonObject = new org.json.JSONObject(response); if(jsonObject.has("result")) { if(jsonObject.getString("result").matches("^[A-Za-z0-9]{64}$")) { Toast.makeText(context, R.string.tx_sent, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, R.string.trusted_node_tx_error, Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(context, R.string.trusted_node_not_valid, Toast.LENGTH_SHORT).show(); } } else { response = PushTx.getInstance(context).samourai(hexTx); if(response != null) { JSONObject jsonObject = new org.json.JSONObject(response); if(jsonObject.has("status")) { if(jsonObject.getString("status").equals("ok")) { Toast.makeText(context, R.string.tx_sent, Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(context, R.string.pushtx_returns_null, Toast.LENGTH_SHORT).show(); } } } catch(JSONException je) { Toast.makeText(context, "pushTx:" + je.getMessage(), Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.dismiss(); } } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, int whichButton) { ; } }); AlertDialog alert = builder.create(); alert.show(); } else { // Toast.makeText(context, R.string.cannot_find_unspents, Toast.LENGTH_SHORT).show(); sweep(privKeyReader, true); } } catch(Exception e) { Toast.makeText(context, R.string.cannot_sweep_privkey, Toast.LENGTH_SHORT).show(); } Looper.loop(); } }).start(); } }
package com.mapzen.tangram; import android.content.Context; import android.os.SystemClock; import android.view.GestureDetector; import android.view.GestureDetector.OnDoubleTapListener; import android.view.GestureDetector.OnGestureListener; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.View; import android.view.View.OnTouchListener; import com.almeros.android.multitouch.RotateGestureDetector; import com.almeros.android.multitouch.RotateGestureDetector.OnRotateGestureListener; import com.almeros.android.multitouch.ShoveGestureDetector; import com.almeros.android.multitouch.ShoveGestureDetector.OnShoveGestureListener; import java.util.EnumMap; import java.util.EnumSet; /** * Collects touch data, applies gesture detectors, resolves simultaneous detection, and calls the * appropriate input responders */ public class TouchManager implements OnTouchListener, OnScaleGestureListener, OnRotateGestureListener, OnGestureListener, OnDoubleTapListener, OnShoveGestureListener { public enum Gestures { TAP, DOUBLE_TAP, LONG_PRESS, PAN, ROTATE, SCALE, SHOVE, ; public boolean isMultiTouch() { switch(this) { case ROTATE: case SCALE: case SHOVE: return true; default: return false; } } } public interface TapResponder { boolean onSingleTapUp(float x, float y); boolean onSingleTapConfirmed(float x, float y); } public interface DoubleTapResponder { boolean onDoubleTap(float x, float y); } public interface LongPressResponder { void onLongPress(float x, float y); } public interface PanResponder { boolean onPan(float startX, float startY, float endX, float endY); } public interface ScaleResponder { boolean onScale(float x, float y, float scale, float velocity); } public interface RotateResponder { boolean onRotate(float x, float y, float rotation); } public interface ShoveResponder { boolean onShove(float distance); } private static final long MULTITOUCH_BUFFER_TIME = 256; // milliseconds private GestureDetector panTapGestureDetector; private ScaleGestureDetector scaleGestureDetector; private RotateGestureDetector rotateGestureDetector; private ShoveGestureDetector shoveGestureDetector; private TapResponder tapResponder; private DoubleTapResponder doubleTapResponder; private LongPressResponder longPressResponder; private PanResponder panResponder; private ScaleResponder scaleResponder; private RotateResponder rotateResponder; private ShoveResponder shoveResponder; private EnumSet<Gestures> detectedGestures; private EnumMap<Gestures, EnumSet<Gestures>> allowedSimultaneousGestures; private long lastMultiTouchEndTime = -MULTITOUCH_BUFFER_TIME; public TouchManager(Context context) { this.panTapGestureDetector = new GestureDetector(context, this); this.scaleGestureDetector = new ScaleGestureDetector(context, this); this.rotateGestureDetector = new RotateGestureDetector(context, this); this.shoveGestureDetector = new ShoveGestureDetector(context, this); this.detectedGestures = EnumSet.noneOf(Gestures.class); this.allowedSimultaneousGestures = new EnumMap<Gestures, EnumSet<Gestures>>(Gestures.class); // By default, all gestures are allowed to detect simultaneously for (Gestures g : Gestures.values()) { allowedSimultaneousGestures.put(g, EnumSet.allOf(Gestures.class)); } } public void setTapResponder(TapResponder responder) { this.tapResponder = responder; } public void setDoubleTapResponder(DoubleTapResponder responder) { this.doubleTapResponder = responder; } public void setLongPressResponder(LongPressResponder responder) { this.longPressResponder = responder; } public void setPanResponder(PanResponder responder) { this.panResponder = responder; } public void setScaleResponder(ScaleResponder responder) { this.scaleResponder = responder; } public void setRotateResponder(RotateResponder responder) { this.rotateResponder = responder; } public void setShoveResponder(ShoveResponder responder) { this.shoveResponder = responder; } // Set whether 'second' can detect while 'first' is in progress public void setSimultaneousDetectionAllowed(Gestures first, Gestures second, boolean allowed) { if (first != second) { if (allowed) { allowedSimultaneousGestures.get(second).add(first); } else { allowedSimultaneousGestures.get(second).remove(first); } } } public boolean isSimultaneousDetectionAllowed(Gestures first, Gestures second) { return allowedSimultaneousGestures.get(second).contains(first); } private boolean isDetectionAllowed(Gestures g) { if (!allowedSimultaneousGestures.get(g).containsAll(detectedGestures)) { return false; } if (!g.isMultiTouch()) { // Return false if a multitouch gesture has finished within a time threshold long t = SystemClock.uptimeMillis() - lastMultiTouchEndTime; if (t < MULTITOUCH_BUFFER_TIME) { return false; } } return true; } private void setGestureDetected(Gestures g, boolean detected) { if (detected) { detectedGestures.add(g); } else { detectedGestures.remove(g); } if (!detected && g.isMultiTouch()) { lastMultiTouchEndTime = SystemClock.uptimeMillis(); } } // View.OnTouchListener implementation public boolean onTouch(View v, MotionEvent event) { panTapGestureDetector.onTouchEvent(event); scaleGestureDetector.onTouchEvent(event); shoveGestureDetector.onTouchEvent(event); rotateGestureDetector.onTouchEvent(event); return true; } // GestureDetector.OnDoubleTapListener implementation @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (isDetectionAllowed(Gestures.TAP) && tapResponder != null) { return tapResponder.onSingleTapConfirmed(e.getX(), e.getY()); } return false; } @Override public boolean onDoubleTap(MotionEvent e) { if (isDetectionAllowed(Gestures.DOUBLE_TAP) && doubleTapResponder != null) { return doubleTapResponder.onDoubleTap(e.getX(), e.getY()); } return false; } @Override public boolean onDoubleTapEvent(MotionEvent e) { return false; } // GestureDetector.OnGestureListener implementation @Override public boolean onDown(MotionEvent e) { // When new touch is placed, dispatch a zero-distance pan; // this provides an opportunity to halt any current motion. if (isDetectionAllowed(Gestures.PAN) && panResponder != null) { final float x = e.getX(); final float y = e.getY(); return panResponder.onPan(x, y, x, y); } return false; } @Override public void onShowPress(MotionEvent e) { // Ignored } @Override public boolean onSingleTapUp(MotionEvent e) { if (isDetectionAllowed(Gestures.TAP) && tapResponder != null) { return tapResponder.onSingleTapUp(e.getX(), e.getY()); } return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (isDetectionAllowed(Gestures.PAN)) { int action = e2.getAction(); boolean detected = !(action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP); setGestureDetected(Gestures.PAN, detected); if (panResponder == null) { return false; } // TODO: Predictive panning // Use estimated velocity to counteract input->render lag float x = 0, y = 0; int n = e2.getPointerCount(); for (int i = 0; i < n; i++) { x += e2.getX(i) / n; y += e2.getY(i) / n; } return panResponder.onPan(x + distanceX, y + distanceY, x, y); } return false; } @Override public void onLongPress(MotionEvent e) { if (isDetectionAllowed(Gestures.LONG_PRESS) && longPressResponder != null) { longPressResponder.onLongPress(e.getX(), e.getY()); } } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } // RotateGestureDetector.OnRotateGestureListener implementation @Override public boolean onRotate(RotateGestureDetector detector) { if (isDetectionAllowed(Gestures.ROTATE) && rotateResponder != null) { float rotation = -detector.getRotationRadiansDelta(); float x = detector.getFocusX(); float y = detector.getFocusY(); return rotateResponder.onRotate(x, y, rotation); } return false; } @Override public boolean onRotateBegin(RotateGestureDetector detector) { if (isDetectionAllowed(Gestures.ROTATE)) { setGestureDetected(Gestures.ROTATE, true); } return true; } @Override public void onRotateEnd(RotateGestureDetector detector) { setGestureDetected(Gestures.ROTATE, false); } // ScaleGestureDetector.OnScaleGestureListener implementation @Override public boolean onScale(ScaleGestureDetector detector) { if (isDetectionAllowed(Gestures.SCALE) && scaleResponder != null) { long ms = detector.getTimeDelta(); float dt = ms > 0 ? ms / 1000.f : 1.f; float scale = detector.getScaleFactor(); float velocity = (scale - 1.f) / dt; float x = detector.getFocusX(); float y = detector.getFocusY(); return scaleResponder.onScale(x, y, scale, velocity); } return false; } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { if (isDetectionAllowed(Gestures.SCALE)) { setGestureDetected(Gestures.SCALE, true); } return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { setGestureDetected(Gestures.SCALE, false); } // ShoveGestureDetector.OnShoveGestureListener implementation @Override public boolean onShove(ShoveGestureDetector detector) { if (isDetectionAllowed(Gestures.SHOVE) && shoveResponder != null) { return shoveResponder.onShove(detector.getShovePixelsDelta()); } return false; } @Override public boolean onShoveBegin(ShoveGestureDetector detector) { if (isDetectionAllowed(Gestures.SHOVE)) { setGestureDetected(Gestures.SHOVE, true); } return true; } @Override public void onShoveEnd(ShoveGestureDetector detector) { setGestureDetected(Gestures.SHOVE, false); } }
package com.sanchez.fmf; import android.content.Context; import android.graphics.Color; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; import android.os.Build; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import com.sanchez.fmf.event.GetMarketListFailEvent; import com.sanchez.fmf.event.GetMarketListSuccessEvent; import com.sanchez.fmf.event.MapFABClickEvent; import com.sanchez.fmf.event.MarketsDetailsRetrievedEvent; import com.sanchez.fmf.event.PlaceTitleResolvedEvent; import com.sanchez.fmf.event.RetryGetMarketListEvent; import com.sanchez.fmf.fragment.MarketListFragment; import com.sanchez.fmf.fragment.MarketMapFragment; import com.sanchez.fmf.model.MarketDetailModel; import com.sanchez.fmf.model.MarketDetailResponseModel; import com.sanchez.fmf.model.MarketListItemModel; import com.sanchez.fmf.model.MarketListResponseModel; import com.sanchez.fmf.service.MarketService; import com.sanchez.fmf.service.RestClient; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Locale; import butterknife.ButterKnife; import de.greenrobot.event.EventBus; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; public class MarketListActivity extends AppCompatActivity { public static final String TAG = MarketListActivity.class.getSimpleName(); public static final String EXTRA_COORDINATES = "com.sanchez.extra_coordinates"; public static final String EXTRA_PLACE_TITLE = "com.sanchez.extra_place_title"; public static final String EXTRA_PLACE_ID = "com.sanchez.extra_place_id"; public static final String EXTRA_USED_DEVICE_COORDINATES = "com.sanchez.extra_used_device_coordinates"; // service for USDA API private MarketService mMarketService; private volatile HashMap<MarketListItemModel, MarketDetailModel> mMarketDetailResponses = new HashMap<>(); private volatile int mDetailResponses; private double[] mCoordinates; private String mPlaceTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_market_list); ButterKnife.bind(this); // get coordinates from MainFragment intent to pass to MarketListFragment mCoordinates = getIntent().getDoubleArrayExtra(EXTRA_COORDINATES); String placeId = getIntent().getStringExtra(EXTRA_PLACE_ID); String placeTitle = getIntent().getStringExtra(EXTRA_PLACE_TITLE); boolean usedDeviceCoordinates = getIntent().getBooleanExtra(EXTRA_USED_DEVICE_COORDINATES, false); // color nav bar with app color Window w = getWindow(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { w.setNavigationBarColor(getResources().getColor(R.color.primary_dark)); } if (usedDeviceCoordinates) { // user clicked "use current location button", meaning we need to reverse geocode getLocationName(mCoordinates, this); } if (null != placeTitle) { mPlaceTitle = placeTitle; } RestClient client = new RestClient(); mMarketService = client.getMarketService(); getMarkets(); FragmentManager fm = getSupportFragmentManager(); Fragment listFragment = fm.findFragmentById(R.id.container_market_list_activity); if (listFragment == null) { listFragment = MarketListFragment.newInstance(mCoordinates, placeTitle, placeId, usedDeviceCoordinates); fm.beginTransaction() .add(R.id.container_market_list_activity, listFragment) .commit(); } } @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } // TODO: Stuff this in a worker fragment with setRetainInstance(true) private void getMarkets() { /** * get markets from USDA API * coordinates[0] is latitude * coordinates[1] is longitude */ mMarketService.getMarkets(mCoordinates[0], mCoordinates[1], new Callback<MarketListResponseModel>() { @Override public void success(MarketListResponseModel marketListModel, Response response) { EventBus.getDefault().postSticky(new GetMarketListSuccessEvent(marketListModel)); getMarketsDetails(marketListModel); } @Override public void failure(RetrofitError error) { EventBus.getDefault().postSticky(new GetMarketListFailEvent()); Log.e(TAG, error.toString()); } }); } private void getMarketsDetails(MarketListResponseModel marketList) { for (int i = 0; i < marketList.getMarkets().size(); i++) { getMarketDetails(marketList.getMarkets().get(i), marketList.getMarkets().size()); } } private void getMarketDetails(MarketListItemModel market, int marketListSize) { mMarketService.getMarket(market.getId(), new Callback<MarketDetailResponseModel>() { @Override public void success(MarketDetailResponseModel marketDetailResponseModel, Response response) { MarketDetailModel details = marketDetailResponseModel.getMarketdetails(); mMarketDetailResponses.put(market, details); mDetailResponses++; if(mDetailResponses == marketListSize) { EventBus.getDefault().postSticky(new MarketsDetailsRetrievedEvent(mMarketDetailResponses)); } } @Override public void failure(RetrofitError error) { Log.e(TAG, error.toString()); } }); } private void showMap() { MarketMapFragment frag = MarketMapFragment.newInstance(mCoordinates, mPlaceTitle); FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction() .add(R.id.container_market_list_activity, frag) .addToBackStack("") .commit(); // color nav bar with app color Window w = getWindow(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // give primary_dark a little transparency int color = getResources().getColor(R.color.primary_dark); w.setNavigationBarColor(Color.argb(144, Color.red(color), Color.green(color), Color.blue(color))); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_market_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } // get a location name based on latitude and longitude (reverse geocoding) public void getLocationName(final double[] coords, Context c) { new AsyncTask<Void, Integer, String>() { @Override protected String doInBackground(Void... arg0) { Geocoder coder = new Geocoder(c, Locale.ENGLISH); List<Address> results = null; try { results = coder.getFromLocation(coords[0], coords[1], 1); } catch (IOException e) { Log.e(TAG, "Error getting location from coordinates"); } if(results == null || results.size() < 1) { return getResources().getString(R.string.markets); } String result; if (null != results.get(0).getLocality()) { result = results.get(0).getLocality(); } else if (null != results.get(0).getSubLocality()) { result = results.get(0).getSubLocality(); } else { result = getResources().getString(R.string.markets); } return result; } @Override protected void onPostExecute(String result) { if (result != null) { mPlaceTitle = result; EventBus.getDefault().postSticky(new PlaceTitleResolvedEvent(result)); } } }.execute(); } @Override public void onBackPressed() { FragmentManager fm = getSupportFragmentManager(); if (fm.getBackStackEntryCount() == 1) { // Map fragment is on the stack right now, pop it off fm.popBackStackImmediate(); // color nav bar with app color Window w = getWindow(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { w.setNavigationBarColor(getResources().getColor(R.color.primary_dark)); } } else { super.onBackPressed(); } } public void onEvent(RetryGetMarketListEvent event) { getMarkets(); } public void onEvent(MapFABClickEvent event) { showMap(); } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.util.Optional; import javax.swing.*; import javax.swing.table.DefaultTableModel; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); String[] columnNames = {"String", "Integer", "Boolean"}; Object[][] data = { {"aaa", 12, true}, {"bbb", 5, false}, {"CCC", 92, true}, {"DDD", 0, false} }; DefaultTableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; JTable table = new JTable(model) { private int prevHeight = -1; private int prevCount = -1; private void updateRowsHeight(JViewport vport) { int height = vport.getExtentSize().height; int rowCount = getModel().getRowCount(); int defaultRowHeight = height / rowCount; if ((height != prevHeight || rowCount != prevCount) && defaultRowHeight > 0) { // int remainder = height - rowCount * defaultRowHeight; int remainder = height % rowCount; for (int i = 0; i < rowCount; i++) { int a = remainder > 0 ? i == rowCount - 1 ? remainder : 1 : 0; setRowHeight(i, defaultRowHeight + a); remainder } } prevHeight = height; prevCount = rowCount; } @Override public void doLayout() { super.doLayout(); Class<JViewport> clz = JViewport.class; Optional.ofNullable(SwingUtilities.getAncestorOfClass(clz, this)) .filter(clz::isInstance).map(clz::cast) .ifPresent(this::updateRowsHeight); } }; JScrollPane scroll = new JScrollPane(table); scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // TEST: scroll.addComponentListener(new TableRowHeightAdjuster()); scroll.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { Component c = e.getComponent(); if (c instanceof JScrollPane) { ((JScrollPane) c).getViewport().getView().revalidate(); } } }); JButton button = new JButton("add"); button.addActionListener(e -> model.addRow(new Object[] {"", 0, false})); add(scroll); add(button, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } public static void main(String[] args) { EventQueue.invokeLater(MainPanel::createAndShowGui); } private static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } // // TEST when not considering adding rows // class TableRowHeightAdjuster extends ComponentAdapter { // private int prevHeight = -1; // @Override public void componentResized(ComponentEvent e) { // Component c = e.getComponent(); // if (c instanceof JScrollPane) { // JScrollPane scroll = (JScrollPane) c; // JTable table = (JTable) scroll.getViewport().getView(); // int height = scroll.getViewportBorderBounds().height; // int rowCount = table.getModel().getRowCount(); // int rowHeight = height / rowCount; // if (height != prevHeight && rowHeight > 0) { // int remainder = height % rowCount; // for (int i = 0; i < rowCount; i++) { // int a = remainder > 0 ? i == rowCount - 1 ? remainder : 1 : 0; // table.setRowHeight(i, rowHeight + a); // remainder--; // prevHeight = height;
package org.asciidoctor.maven; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Scanner; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.NameFileFilter; import org.apache.commons.io.filefilter.RegexFileFilter; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.io.monitor.FileAlterationListener; import org.apache.commons.io.monitor.FileAlterationListenerAdaptor; import org.apache.commons.io.monitor.FileAlterationMonitor; import org.apache.commons.io.monitor.FileAlterationObserver; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.asciidoctor.Asciidoctor; @Mojo(name = "auto-refresh") public class AsciidoctorRefreshMojo extends AsciidoctorMojo { public static final String PREFIX = AsciidoctorMaven.PREFIX + "refresher."; @Parameter(property = PREFIX + "port", required = false) protected int port = 2000; @Parameter(property = PREFIX + "interval", required = false) protected int interval = 2000; private Future<Asciidoctor> asciidoctor = null; private Collection<FileAlterationMonitor> monitors = null; private final AtomicBoolean needsUpdate = new AtomicBoolean(false); private ScheduledExecutorService updaterScheduler = null; @Override public void execute() throws MojoExecutionException, MojoFailureException { // this is long because of JRuby startup createAsciidoctor(); startPolling(); startUpdater(); doWork(); stopUpdater(); stopMonitor(); } private void stopUpdater() { if (updaterScheduler != null) { updaterScheduler.shutdown(); } } private void startUpdater() { updaterScheduler = Executors.newScheduledThreadPool(1); // we prevent refreshing more often than all 200ms and we refresh at least once/s // NOTE1: it is intended to avoid too much time space between file polling and re-rendering // NOTE2: if nothing to refresh it does nothing so all is fine updaterScheduler.scheduleAtFixedRate(new Updater(needsUpdate, this), 0, Math.min(1000, Math.max(200, interval / 2)), TimeUnit.MILLISECONDS); } protected void doWork() throws MojoFailureException, MojoExecutionException { getLog().info("Rendered doc in " + executeAndReturnDuration() + "ms"); doWait(); } protected void doWait() { getLog().info("Type [exit|quit] to exit and [refresh] to force a manual re-rendering."); String line; final Scanner scanner = new Scanner(System.in); while ((line = scanner.nextLine()) != null) { line = line.trim(); if ("exit".equalsIgnoreCase(line) || "quit".equalsIgnoreCase(line)) { break; } if ("refresh".equalsIgnoreCase(line)) { doExecute(); } else { getLog().warn("'" + line + "' not understood, available commands are [quit, exit, refresh]."); } } } private void stopMonitor() throws MojoExecutionException { if (monitors != null) { for (final FileAlterationMonitor monitor : monitors) { try { monitor.stop(); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } } } protected synchronized void doExecute() { ensureOutputExists(); // delete only content files, resources are synchronized so normally up to date for (final File f : FileUtils.listFiles(outputDirectory, new RegexFileFilter(ASCIIDOC_REG_EXP_EXTENSION), TrueFileFilter.INSTANCE)) { FileUtils.deleteQuietly(f); } try { getLog().info("Re-rendered doc in " + executeAndReturnDuration() + "ms"); } catch (final MojoExecutionException e) { getLog().error(e); } catch (final MojoFailureException e) { getLog().error(e); } } protected long executeAndReturnDuration() throws MojoExecutionException, MojoFailureException { final long start = System.nanoTime(); super.execute(); final long end = System.nanoTime(); return TimeUnit.NANOSECONDS.toMillis(end - start); } private void startPolling() throws MojoExecutionException { monitors = new ArrayList<FileAlterationMonitor>(); { // content monitor final FileAlterationObserver observer; if (sourceDocumentName != null) { observer = new FileAlterationObserver(sourceDirectory, new NameFileFilter(sourceDocumentName)); } else if (sourceDirectory != null) { observer = new FileAlterationObserver(sourceDirectory, new RegexFileFilter(ASCIIDOC_REG_EXP_EXTENSION)); } else { monitors = null; // no need to start anything because there is no content return; } final FileAlterationMonitor monitor = new FileAlterationMonitor(interval); final FileAlterationListener listener = new FileAlterationListenerAdaptor() { @Override public void onFileCreate(final File file) { getLog().info("File " + file.getAbsolutePath() + " created."); needsUpdate.set(true); } @Override public void onFileChange(final File file) { getLog().info("File " + file.getAbsolutePath() + " updated."); needsUpdate.set(true); } @Override public void onFileDelete(final File file) { getLog().info("File " + file.getAbsolutePath() + " deleted."); needsUpdate.set(true); } }; observer.addListener(listener); monitor.addObserver(observer); monitors.add(monitor); } { // resources monitors if (synchronizations != null) { for (final Synchronization s : synchronizations) { final FileAlterationMonitor monitor = new FileAlterationMonitor(interval); final FileAlterationListener listener = new FileAlterationListenerAdaptor() { @Override public void onFileCreate(final File file) { getLog().info("File " + file.getAbsolutePath() + " created."); synchronize(s); needsUpdate.set(true); } @Override public void onFileChange(final File file) { getLog().info("File " + file.getAbsolutePath() + " updated."); synchronize(s); needsUpdate.set(true); } @Override public void onFileDelete(final File file) { getLog().info("File " + file.getAbsolutePath() + " deleted."); FileUtils.deleteQuietly(file); needsUpdate.set(true); } }; final File source = s.getSource(); final FileAlterationObserver observer; if (source.isDirectory()) { observer = new FileAlterationObserver(source); } else { observer = new FileAlterationObserver(source.getParentFile(), new NameFileFilter(source.getName())); } observer.addListener(listener); monitor.addObserver(observer); monitors.add(monitor); } } } for (final FileAlterationMonitor monitor : monitors) { try { monitor.start(); } catch (final Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } } private void createAsciidoctor() { final ExecutorService es = Executors.newSingleThreadExecutor(); asciidoctor = es.submit(new Callable<Asciidoctor>() { @Override public Asciidoctor call() throws Exception { return Asciidoctor.Factory.create(); } }); es.shutdown(); } private static class Updater implements Runnable { private final AtomicBoolean run; private final AsciidoctorRefreshMojo mojo; private Updater(final AtomicBoolean run, final AsciidoctorRefreshMojo mojo) { this.run = run; this.mojo = mojo; } @Override public void run() { if (run.get()) { run.set(false); mojo.doExecute(); } } } }
package org.commcare.activities; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.util.Base64; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Toast; import org.commcare.CommCareApplication; import org.commcare.android.database.app.models.UserKeyRecord; import org.commcare.android.database.user.models.FormRecord; import org.commcare.android.database.user.models.SessionStateDescriptor; import org.commcare.core.process.CommCareInstanceInitializer; import org.commcare.dalvik.BuildConfig; import org.commcare.dalvik.R; import org.commcare.fragments.BreadcrumbBarFragment; import org.commcare.interfaces.CommCareActivityUIController; import org.commcare.interfaces.ConnectorWithResultCallback; import org.commcare.interfaces.WithUIController; import org.commcare.logging.AndroidLogger; import org.commcare.logging.analytics.GoogleAnalyticsFields; import org.commcare.logging.analytics.GoogleAnalyticsUtils; import org.commcare.models.AndroidSessionWrapper; import org.commcare.models.database.SqlStorage; import org.commcare.preferences.CommCarePreferences; import org.commcare.preferences.DeveloperPreferences; import org.commcare.provider.FormsProviderAPI; import org.commcare.provider.InstanceProviderAPI; import org.commcare.session.CommCareSession; import org.commcare.session.SessionFrame; import org.commcare.session.SessionNavigationResponder; import org.commcare.session.SessionNavigator; import org.commcare.suite.model.Entry; import org.commcare.suite.model.EntityDatum; import org.commcare.suite.model.SessionDatum; import org.commcare.suite.model.StackFrameStep; import org.commcare.suite.model.SyncEntry; import org.commcare.suite.model.SyncPost; import org.commcare.suite.model.Text; import org.commcare.tasks.DataPullTask; import org.commcare.tasks.FormLoaderTask; import org.commcare.tasks.FormRecordCleanupTask; import org.commcare.tasks.ProcessAndSendTask; import org.commcare.tasks.PullTaskReceiver; import org.commcare.tasks.ResultAndError; import org.commcare.utils.ACRAUtil; import org.commcare.utils.AndroidCommCarePlatform; import org.commcare.utils.AndroidInstanceInitializer; import org.commcare.utils.ChangeLocaleUtil; import org.commcare.utils.ConnectivityStatus; import org.commcare.utils.ConsumerAppsUtil; import org.commcare.utils.EntityDetailUtils; import org.commcare.utils.GlobalConstants; import org.commcare.utils.SessionUnavailableException; import org.commcare.utils.StorageUtils; import org.commcare.views.UserfacingErrorHandling; import org.commcare.views.dialogs.StandardAlertDialog; import org.commcare.views.dialogs.CommCareAlertDialog; import org.commcare.views.dialogs.CustomProgressDialog; import org.commcare.views.dialogs.DialogChoiceItem; import org.commcare.views.dialogs.DialogCreationHelpers; import org.commcare.views.dialogs.PaneledChoiceDialog; import org.commcare.views.notifications.NotificationMessageFactory; import org.commcare.views.notifications.NotificationMessageFactory.StockMessages; import org.javarosa.core.model.User; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.Logger; import org.javarosa.core.services.locale.Localization; import org.javarosa.xpath.XPathTypeMismatchException; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Map; import java.util.Vector; public class CommCareHomeActivity extends SessionAwareCommCareActivity<CommCareHomeActivity> implements SessionNavigationResponder, WithUIController, PullTaskReceiver, ConnectorWithResultCallback<CommCareHomeActivity> { private static final String TAG = CommCareHomeActivity.class.getSimpleName(); /** * Request code for launching a menu list or menu grid */ private static final int GET_COMMAND = 1; /** * Request code for launching EntitySelectActivity (to allow user to select a case), * or EntityDetailActivity (to allow user to confirm an auto-selected case) */ private static final int GET_CASE = 2; private static final int GET_REMOTE_DATA = 3; private static final int MAKE_REMOTE_POST = 5; /** * Request code for launching FormEntryActivity */ private static final int MODEL_RESULT = 4; private static final int GET_INCOMPLETE_FORM = 16; public static final int REPORT_PROBLEM_ACTIVITY = 64; private static final int PREFERENCES_ACTIVITY=512; private static final int ADVANCED_ACTIONS_ACTIVITY=1024; private static final int CREATE_PIN = 16384; private static final int AUTHENTICATION_FOR_PIN = 32768; private static final int MENU_UPDATE = Menu.FIRST; private static final int MENU_SAVED_FORMS = Menu.FIRST + 1; private static final int MENU_CHANGE_LANGUAGE = Menu.FIRST + 2; private static final int MENU_PREFERENCES = Menu.FIRST + 3; private static final int MENU_ADVANCED = Menu.FIRST + 4; private static final int MENU_ABOUT = Menu.FIRST + 5; private static final int MENU_PIN = Menu.FIRST + 6; /** * Restart is a special CommCare return code which means that the session was invalidated in the * calling activity and that the current session should be resynced */ public static final int RESULT_RESTART = 3; private static final String KEY_PENDING_SESSION_DATA = "pending-session-data-id"; private static final String KEY_PENDING_SESSION_DATUM_ID = "pending-session-datum-id"; private static final String AIRPLANE_MODE_CATEGORY = "airplane-mode"; public static final String MENU_STYLE_GRID = "grid"; // The API allows for external calls. When this occurs, redispatch to their // activity instead of commcare. private boolean wasExternal = false; private static final String WAS_EXTERNAL_KEY = "was_external"; private int mDeveloperModeClicks = 0; private HomeActivityUIController uiController; private SessionNavigator sessionNavigator; private FormAndDataSyncer formAndDataSyncer; private boolean loginExtraWasConsumed; private static final String EXTRA_CONSUMED_KEY = "login_extra_was_consumed"; private boolean isRestoringSession = false; private boolean isSyncUserLaunched = false; private boolean sessionNavigationProceedingAfterOnResume; @Override protected void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); loadInstanceState(savedInstanceState); ACRAUtil.registerAppData(); uiController.setupUI(); sessionNavigator = new SessionNavigator(this); formAndDataSyncer = new FormAndDataSyncer(); processFromExternalLaunch(savedInstanceState); processFromShortcutLaunch(); processFromLoginLaunch(); } private void loadInstanceState(Bundle savedInstanceState) { if (savedInstanceState != null) { loginExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); wasExternal = savedInstanceState.getBoolean(WAS_EXTERNAL_KEY); } } /** * Set state that signifies activity was launch from external app. */ private void processFromExternalLaunch(Bundle savedInstanceState) { if (savedInstanceState == null && getIntent().hasExtra(DispatchActivity.WAS_EXTERNAL)) { wasExternal = true; sessionNavigator.startNextSessionStep(); } } private void processFromShortcutLaunch() { if (getIntent().getBooleanExtra(DispatchActivity.WAS_SHORTCUT_LAUNCH, false)) { sessionNavigator.startNextSessionStep(); } } private void processFromLoginLaunch() { if (getIntent().getBooleanExtra(DispatchActivity.START_FROM_LOGIN, false) && !loginExtraWasConsumed) { getIntent().removeExtra(DispatchActivity.START_FROM_LOGIN); loginExtraWasConsumed = true; CommCareSession session = CommCareApplication._().getCurrentSession(); if (session.getCommand() != null) { // restore the session state if there is a command. // For debugging and occurs when a serialized // session is stored upon login isRestoringSession = true; sessionNavigator.startNextSessionStep(); return; } // Trigger off a regular unsent task processor, unless we're about to sync (which will // then handle this in a blocking fashion) if (!CommCareApplication._().isSyncPending(false)) { checkAndStartUnsentFormsTask(false, false); } if (CommCareHomeActivity.isDemoUser()) { showDemoModeWarning(); } checkForPinLaunchConditions(); } } // See if we should launch either the pin choice dialog, or the create pin activity directly private void checkForPinLaunchConditions() { LoginMode loginMode = (LoginMode)getIntent().getSerializableExtra(LoginActivity.LOGIN_MODE); if (loginMode == LoginMode.PRIMED) { launchPinCreateScreen(loginMode); return; } if (loginMode == LoginMode.PASSWORD) { boolean pinCreationEnabledForApp = DeveloperPreferences.shouldOfferPinForLogin(); if (!pinCreationEnabledForApp) { return; } boolean userManuallyEnteredPasswordMode = getIntent() .getBooleanExtra(LoginActivity.MANUAL_SWITCH_TO_PW_MODE, false); boolean alreadyDismissedPinCreation = CommCareApplication._().getCurrentApp().getAppPreferences() .getBoolean(CommCarePreferences.HAS_DISMISSED_PIN_CREATION, false); if (!alreadyDismissedPinCreation || userManuallyEnteredPasswordMode) { showPinChoiceDialog(loginMode); } } } private void showPinChoiceDialog(final LoginMode loginMode) { String promptMessage; UserKeyRecord currentUserRecord = CommCareApplication._().getRecordForCurrentUser(); if (currentUserRecord.hasPinSet()) { promptMessage = Localization.get("pin.dialog.prompt.reset"); } else { promptMessage = Localization.get("pin.dialog.prompt.set"); } final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, promptMessage); DialogChoiceItem createPinChoice = new DialogChoiceItem( Localization.get("pin.dialog.yes"), -1, new View.OnClickListener() { @Override public void onClick(View v) { dismissAlertDialog(); launchPinCreateScreen(loginMode); } }); DialogChoiceItem nextTimeChoice = new DialogChoiceItem( Localization.get("pin.dialog.not.now"), -1, new View.OnClickListener() { @Override public void onClick(View v) { dismissAlertDialog(); } }); DialogChoiceItem notAgainChoice = new DialogChoiceItem( Localization.get("pin.dialog.never"), -1, new View.OnClickListener() { @Override public void onClick(View v) { dismissAlertDialog(); CommCareApplication._().getCurrentApp().getAppPreferences() .edit() .putBoolean(CommCarePreferences.HAS_DISMISSED_PIN_CREATION, true) .commit(); showPinFutureAccessDialog(); } }); dialog.setChoiceItems(new DialogChoiceItem[]{createPinChoice, nextTimeChoice, notAgainChoice}); dialog.addCollapsibleInfoPane(Localization.get("pin.dialog.extra.info")); showAlertDialog(dialog); } private void showPinFutureAccessDialog() { StandardAlertDialog.getBasicAlertDialog(this, Localization.get("pin.dialog.set.later.title"), Localization.get("pin.dialog.set.later.message"), null).showNonPersistentDialog(); } private void launchPinAuthentication() { Intent i = new Intent(this, PinAuthenticationActivity.class); startActivityForResult(i, AUTHENTICATION_FOR_PIN); } private void launchPinCreateScreen(LoginMode loginMode) { Intent i = new Intent(this, CreatePinActivity.class); i.putExtra(LoginActivity.LOGIN_MODE, loginMode); startActivityForResult(i, CREATE_PIN); } protected void goToFormArchive(boolean incomplete) { goToFormArchive(incomplete, null); } private void showLocaleChangeMenu() { final PaneledChoiceDialog dialog = new PaneledChoiceDialog(this, Localization.get("home.menu.locale.select")); AdapterView.OnItemClickListener listClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String[] localeCodes = ChangeLocaleUtil.getLocaleCodes(); if (position >= localeCodes.length) { Localization.setLocale("default"); } else { Localization.setLocale(localeCodes[position]); } // rebuild home buttons in case language changed; uiController.setupUI(); rebuildOptionMenu(); dismissAlertDialog(); } }; dialog.setChoiceItems(buildLocaleChoices(), listClickListener); showAlertDialog(dialog); } private static DialogChoiceItem[] buildLocaleChoices() { String[] locales = ChangeLocaleUtil.getLocaleNames(); DialogChoiceItem[] choices =new DialogChoiceItem[locales.length]; for (int i = 0; i < choices.length; i++) { choices[i] = DialogChoiceItem.nonListenerItem(locales[i]); } return choices; } private void goToFormArchive(boolean incomplete, FormRecord record) { if (incomplete) { GoogleAnalyticsUtils.reportViewArchivedFormsList(GoogleAnalyticsFields.LABEL_INCOMPLETE); } else { GoogleAnalyticsUtils.reportViewArchivedFormsList(GoogleAnalyticsFields.LABEL_COMPLETE); } Intent i = new Intent(getApplicationContext(), FormRecordListActivity.class); if (incomplete) { i.putExtra(FormRecord.META_STATUS, FormRecord.STATUS_INCOMPLETE); } if (record != null) { i.putExtra(FormRecordListActivity.KEY_INITIAL_RECORD_ID, record.getID()); } startActivityForResult(i, GET_INCOMPLETE_FORM); } void enterRootModule() { Intent i; if (useGridMenu(org.commcare.suite.model.Menu.ROOT_MENU_ID)) { i = new Intent(this, MenuGrid.class); } else { i = new Intent(this, MenuList.class); } addPendingDataExtra(i, CommCareApplication._().getCurrentSessionWrapper().getSession()); startActivityForResult(i, GET_COMMAND); } private boolean useGridMenu(String menuId) { // first check if this is enabled in profile if(CommCarePreferences.isGridMenuEnabled()) { return true; } // if not, check style attribute for this particular menu block if(menuId == null) { menuId = org.commcare.suite.model.Menu.ROOT_MENU_ID; } AndroidCommCarePlatform platform = CommCareApplication._().getCommCarePlatform(); String commonDisplayStyle = platform.getMenuDisplayStyle(menuId); return MENU_STYLE_GRID.equals(commonDisplayStyle); } void userTriggeredLogout() { setResult(RESULT_OK); finish(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(WAS_EXTERNAL_KEY, wasExternal); outState.putBoolean(EXTRA_CONSUMED_KEY, loginExtraWasConsumed); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if(resultCode == RESULT_RESTART) { sessionNavigator.startNextSessionStep(); } else { // if handling new return code (want to return to home screen) but a return at the end of your statement switch(requestCode) { case PREFERENCES_ACTIVITY: if (resultCode == AdvancedActionsActivity.RESULT_DATA_RESET) { finish(); } return; case ADVANCED_ACTIONS_ACTIVITY: handleAdvancedActionResult(resultCode, intent); return; case GET_INCOMPLETE_FORM: //TODO: We might need to load this from serialized state? if(resultCode == RESULT_CANCELED) { uiController.refreshView(); return; } else if(resultCode == RESULT_OK) { int record = intent.getIntExtra("FORMRECORDS", -1); if(record == -1) { //Hm, what to do here? break; } FormRecord r = CommCareApplication._().getUserStorage(FormRecord.class).read(record); //Retrieve and load the appropriate ssd SqlStorage<SessionStateDescriptor> ssdStorage = CommCareApplication._().getUserStorage(SessionStateDescriptor.class); Vector<Integer> ssds = ssdStorage.getIDsForValue(SessionStateDescriptor.META_FORM_RECORD_ID, r.getID()); AndroidSessionWrapper currentState = CommCareApplication._().getCurrentSessionWrapper(); if(ssds.size() == 1) { currentState.loadFromStateDescription(ssdStorage.read(ssds.firstElement())); } else { currentState.setFormRecordId(r.getID()); } AndroidCommCarePlatform platform = CommCareApplication._().getCommCarePlatform(); formEntry(platform.getFormContentUri(r.getFormNamespace()), r); return; } break; case GET_COMMAND: //TODO: We might need to load this from serialized state? AndroidSessionWrapper currentState = CommCareApplication._().getCurrentSessionWrapper(); if (resultCode == RESULT_CANCELED) { if (currentState.getSession().getCommand() == null) { //Needed a command, and didn't already have one. Stepping back from //an empty state, Go home! currentState.reset(); uiController.refreshView(); return; } else { currentState.getSession().stepBack(currentState.getEvaluationContext()); } } else if (resultCode == RESULT_OK) { CommCareSession session = currentState.getSession(); if (sessionStateUnchangedSinceCallout(session, intent)) { //Get our command, set it, and continue forward String command = intent.getStringExtra(SessionFrame.STATE_COMMAND_ID); session.setCommand(command); } else { clearSessionAndExit(currentState, true); return; } } break; case GET_CASE: //TODO: We might need to load this from serialized state? AndroidSessionWrapper asw = CommCareApplication._().getCurrentSessionWrapper(); CommCareSession currentSession = asw.getSession(); if (resultCode == RESULT_CANCELED) { currentSession.stepBack(asw.getEvaluationContext()); } else if (resultCode == RESULT_OK) { if (sessionStateUnchangedSinceCallout(currentSession, intent)) { String sessionDatumId = currentSession.getNeededDatum().getDataId(); String chosenCaseId = intent.getStringExtra(SessionFrame.STATE_DATUM_VAL); currentSession.setDatum(sessionDatumId, chosenCaseId); } else { clearSessionAndExit(asw, true); return; } } break; case MODEL_RESULT: boolean fetchNext = processReturnFromFormEntry(resultCode, intent); if (!fetchNext) { return; } break; case AUTHENTICATION_FOR_PIN: if (resultCode == RESULT_OK) { launchPinCreateScreen(LoginMode.PASSWORD); } return; case CREATE_PIN: boolean choseRememberPassword = intent != null && intent.getBooleanExtra(CreatePinActivity.CHOSE_REMEMBER_PASSWORD, false); if (choseRememberPassword) { CommCareApplication._().closeUserSession(); } else if (resultCode == RESULT_OK) { Toast.makeText(this, Localization.get("pin.set.success"), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, Localization.get("pin.not.set"), Toast.LENGTH_SHORT).show(); } return; case MAKE_REMOTE_POST: stepBackIfCancelled(resultCode); if (resultCode == RESULT_OK) { CommCareApplication._().getCurrentSessionWrapper().terminateSession(); } break; case GET_REMOTE_DATA: stepBackIfCancelled(resultCode); break; } sessionNavigationProceedingAfterOnResume = true; startNextSessionStepSafe(); } super.onActivityResult(requestCode, resultCode, intent); } private void handleAdvancedActionResult(int resultCode, Intent intent) { if (resultCode == AdvancedActionsActivity.RESULT_FORMS_PROCESSED) { int formProcessCount = intent.getIntExtra(AdvancedActionsActivity.FORM_PROCESS_COUNT_KEY, 0); String localizationKey = intent.getStringExtra(AdvancedActionsActivity.FORM_PROCESS_MESSAGE_KEY); displayMessage(Localization.get(localizationKey, new String[]{"" + formProcessCount}), false, false); uiController.refreshView(); } } private static void stepBackIfCancelled(int resultCode) { if (resultCode == RESULT_CANCELED) { AndroidSessionWrapper asw = CommCareApplication._().getCurrentSessionWrapper(); CommCareSession currentSession = asw.getSession(); currentSession.stepBack(asw.getEvaluationContext()); } } private void startNextSessionStepSafe() { try { sessionNavigator.startNextSessionStep(); } catch (CommCareInstanceInitializer.FixtureInitializationException e) { sessionNavigator.stepBack(); if (isDemoUser()) { // most likely crashing due to data not being available in demo mode UserfacingErrorHandling.createErrorDialog(this, Localization.get("demo.mode.feature.unavailable"), false); } else { UserfacingErrorHandling.createErrorDialog(this, e.getMessage(), false); } } } /** * @return If the nature of the data that the session is waiting for has not changed since the * callout that we are returning from was made */ private boolean sessionStateUnchangedSinceCallout(CommCareSession session, Intent intent) { EvaluationContext evalContext = CommCareApplication._().getCurrentSessionWrapper().getEvaluationContext(); boolean neededDataUnchanged = session.getNeededData(evalContext).equals( intent.getStringExtra(KEY_PENDING_SESSION_DATA)); String intentDatum = intent.getStringExtra(KEY_PENDING_SESSION_DATUM_ID); boolean datumIdsUnchanged = intentDatum == null || intentDatum.equals(session.getNeededDatum().getDataId()); return neededDataUnchanged && datumIdsUnchanged; } /** * Process user returning home from the form entry activity. * Triggers form submission cycle, cleans up some session state. * * @param resultCode exit code of form entry activity * @param intent The intent of the returning activity, with the * saved form provided as the intent URI data. Null if * the form didn't exit cleanly * @return Flag signifying that caller should fetch the next activity in * the session to launch. If false then caller should exit or spawn home * activity. */ private boolean processReturnFromFormEntry(int resultCode, Intent intent) { // TODO: We might need to load this from serialized state? AndroidSessionWrapper currentState = CommCareApplication._().getCurrentSessionWrapper(); // This is the state we were in when we _Started_ form entry FormRecord current = currentState.getFormRecord(); if (current == null) { // somehow we lost the form record for the current session // TODO: how should this be handled? -- PLM Toast.makeText(this, "Error while trying to save the form!", Toast.LENGTH_LONG).show(); Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Form Entry couldn't save because of corrupt state."); clearSessionAndExit(currentState, true); return false; } // TODO: This should be the default unless we're in some "Uninit" or "incomplete" state if ((intent != null && intent.getBooleanExtra(FormEntryActivity.IS_ARCHIVED_FORM, false)) || FormRecord.STATUS_COMPLETE.equals(current.getStatus()) || FormRecord.STATUS_SAVED.equals(current.getStatus())) { // Viewing an old form, so don't change the historical record // regardless of the exit code currentState.reset(); if (wasExternal) { setResult(RESULT_CANCELED); this.finish(); } else { // Return to where we started goToFormArchive(false, current); } return false; } if (resultCode == RESULT_OK) { // Determine if the form instance is complete Uri resultInstanceURI = null; if (intent != null) { resultInstanceURI = intent.getData(); } if (resultInstanceURI == null) { CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(StockMessages.FormEntry_Unretrievable)); Toast.makeText(this, "Error while trying to read the form! See the notification", Toast.LENGTH_LONG).show(); Logger.log(AndroidLogger.TYPE_ERROR_WORKFLOW, "Form Entry did not return a form"); clearSessionAndExit(currentState, true); return false; } Cursor c = null; String instanceStatus; try { c = getContentResolver().query(resultInstanceURI, null, null, null, null); if (!c.moveToFirst()) { throw new IllegalArgumentException("Empty query for instance record!"); } instanceStatus = c.getString(c.getColumnIndexOrThrow(InstanceProviderAPI.InstanceColumns.STATUS)); } finally { if (c != null) { c.close(); } } // was the record marked complete? boolean complete = InstanceProviderAPI.STATUS_COMPLETE.equals(instanceStatus); // The form is either ready for processing, or not, depending on how it was saved if (complete) { // We're honoring in order submissions, now, so trigger a full // submission cycle checkAndStartUnsentFormsTask(false, false); uiController.refreshView(); if (wasExternal) { setResult(RESULT_CANCELED); this.finish(); return false; } // Before we can terminate the session, we need to know that the form has been processed // in case there is state that depends on it. boolean terminateSuccessful; try { terminateSuccessful = currentState.terminateSession(); } catch (XPathTypeMismatchException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, true); return false; } if (!terminateSuccessful) { // If we didn't find somewhere to go, we're gonna stay here return false; } // Otherwise, we want to keep proceeding in order // to keep running the workflow } else { // Form record is now stored. // TODO: session state clearing might be something we want to do in InstanceProvider.bindToFormRecord. clearSessionAndExit(currentState, false); return false; } } else if (resultCode == RESULT_CANCELED) { // Nothing was saved during the form entry activity Logger.log(AndroidLogger.TYPE_FORM_ENTRY, "Form Entry Cancelled"); // If the form was unstarted, we want to wipe the record. if (current.getStatus().equals(FormRecord.STATUS_UNSTARTED)) { // Entry was cancelled. FormRecordCleanupTask.wipeRecord(this, currentState); } if (wasExternal) { currentState.reset(); setResult(RESULT_CANCELED); this.finish(); return false; } else if (current.getStatus().equals(FormRecord.STATUS_INCOMPLETE)) { currentState.reset(); // We should head back to the incomplete forms screen goToFormArchive(true, current); return false; } else { // If we cancelled form entry from a normal menu entry // we want to go back to where were were right before we started // entering the form. currentState.getSession().stepBack(currentState.getEvaluationContext()); currentState.setFormRecordId(-1); } } return true; } private void clearSessionAndExit(AndroidSessionWrapper currentState, boolean shouldWarnUser) { currentState.reset(); if (wasExternal) { setResult(RESULT_CANCELED); this.finish(); } uiController.refreshView(); if (shouldWarnUser) { showSessionRefreshWarning(); } } private void showSessionRefreshWarning() { showAlertDialog(StandardAlertDialog.getBasicAlertDialog(this, Localization.get("session.refresh.error.title"), Localization.get("session.refresh.error.message"), null)); } private void showDemoModeWarning() { showAlertDialog(StandardAlertDialog.getBasicAlertDialogWithIcon(this, Localization.get("demo.mode.warning.title"), Localization.get("demo.mode.warning"), android.R.drawable.ic_dialog_info, null)); } private void createErrorDialog(String errorMsg, AlertDialog.OnClickListener errorListener) { showAlertDialog(StandardAlertDialog.getBasicAlertDialogWithIcon(this, Localization.get("app.handled.error.title"), errorMsg, android.R.drawable.ic_dialog_info, errorListener)); } @Override public String getActivityTitle() { String userName; try { userName = CommCareApplication._().getSession().getLoggedInUser().getUsername(); if (userName != null) { return Localization.get("home.logged.in.message", new String[]{userName}); } } catch (Exception e) { //TODO: Better catch, here } return ""; } @Override protected boolean isTopNavEnabled() { return false; } // region - implementing methods for SessionNavigationResponder @Override public void processSessionResponse(int statusCode) { AndroidSessionWrapper asw = CommCareApplication._().getCurrentSessionWrapper(); switch(statusCode) { case SessionNavigator.ASSERTION_FAILURE: handleAssertionFailureFromSessionNav(asw); break; case SessionNavigator.NO_CURRENT_FORM: handleNoFormFromSessionNav(asw); break; case SessionNavigator.START_FORM_ENTRY: startFormEntry(asw); break; case SessionNavigator.GET_COMMAND: handleGetCommand(asw); break; case SessionNavigator.START_ENTITY_SELECTION: launchEntitySelect(asw.getSession()); break; case SessionNavigator.LAUNCH_CONFIRM_DETAIL: launchConfirmDetail(asw); break; case SessionNavigator.PROCESS_QUERY_REQUEST: launchQueryMaker(); break; case SessionNavigator.START_SYNC_REQUEST: launchRemoteSync(asw); break; case SessionNavigator.XPATH_EXCEPTION_THROWN: UserfacingErrorHandling .logErrorAndShowDialog(this, sessionNavigator.getCurrentException(), false); break; case SessionNavigator.REPORT_CASE_AUTOSELECT: GoogleAnalyticsUtils.reportFeatureUsage(GoogleAnalyticsFields.ACTION_CASE_AUTOSELECT_USED); break; } } @Override public CommCareSession getSessionForNavigator() { return CommCareApplication._().getCurrentSession(); } @Override public EvaluationContext getEvalContextForNavigator() { return CommCareApplication._().getCurrentSessionWrapper().getEvaluationContext(); } // endregion private void handleAssertionFailureFromSessionNav(final AndroidSessionWrapper asw) { EvaluationContext ec = asw.getEvaluationContext(); Text text = asw.getSession().getCurrentEntry().getAssertions().getAssertionFailure(ec); createErrorDialog(text.evaluate(ec), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dismissAlertDialog(); asw.getSession().stepBack(asw.getEvaluationContext()); CommCareHomeActivity.this.sessionNavigator.startNextSessionStep(); } }); } private void handleNoFormFromSessionNav(AndroidSessionWrapper asw) { boolean terminateSuccesful; try { terminateSuccesful = asw.terminateSession(); } catch (XPathTypeMismatchException e) { UserfacingErrorHandling.logErrorAndShowDialog(this, e, true); return; } if (terminateSuccesful) { sessionNavigator.startNextSessionStep(); } else { uiController.refreshView(); } } private void handleGetCommand(AndroidSessionWrapper asw) { Intent i; String command = asw.getSession().getCommand(); if (useGridMenu(command)) { i = new Intent(this, MenuGrid.class); } else { i = new Intent(this, MenuList.class); } i.putExtra(SessionFrame.STATE_COMMAND_ID, command); addPendingDataExtra(i, asw.getSession()); startActivityForResult(i, GET_COMMAND); } private void launchRemoteSync(AndroidSessionWrapper asw) { String command = asw.getSession().getCommand(); Entry commandEntry = CommCareApplication._().getCommCarePlatform().getEntry(command); if (commandEntry instanceof SyncEntry) { SyncPost syncPost = ((SyncEntry)commandEntry).getSyncPost(); Intent i = new Intent(getApplicationContext(), PostRequestActivity.class); i.putExtra(PostRequestActivity.URL_KEY, syncPost.getUrl()); i.putExtra(PostRequestActivity.PARAMS_KEY, new HashMap<>(syncPost.getEvaluatedParams(asw.getEvaluationContext()))); startActivityForResult(i, MAKE_REMOTE_POST); } else { // expected a sync entry; clear session and show vague 'session error' message to user clearSessionAndExit(asw, true); } } private void launchQueryMaker() { Intent i = new Intent(getApplicationContext(), QueryRequestActivity.class); startActivityForResult(i, GET_REMOTE_DATA); } private void launchEntitySelect(CommCareSession session) { startActivityForResult(getSelectIntent(session), GET_CASE); } private Intent getSelectIntent(CommCareSession session) { Intent i = new Intent(getApplicationContext(), EntitySelectActivity.class); i.putExtra(SessionFrame.STATE_COMMAND_ID, session.getCommand()); StackFrameStep lastPopped = session.getPoppedStep(); if (lastPopped != null && SessionFrame.STATE_DATUM_VAL.equals(lastPopped.getType())) { i.putExtra(EntitySelectActivity.EXTRA_ENTITY_KEY, lastPopped.getValue()); } addPendingDataExtra(i, session); addPendingDatumIdExtra(i, session); return i; } // Launch an intent to load the confirmation screen for the current selection private void launchConfirmDetail(AndroidSessionWrapper asw) { CommCareSession session = asw.getSession(); SessionDatum selectDatum = session.getNeededDatum(); if (selectDatum instanceof EntityDatum) { EntityDatum entityDatum = (EntityDatum) selectDatum; TreeReference contextRef = sessionNavigator.getCurrentAutoSelection(); if (this.getString(R.string.panes).equals("two") && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // Large tablet in landscape: send to entity select activity // (awesome mode, with case pre-selected) instead of entity detail Intent i = getSelectIntent(session); String caseId = EntityDatum.getCaseIdFromReference( contextRef, entityDatum, asw.getEvaluationContext()); i.putExtra(EntitySelectActivity.EXTRA_ENTITY_KEY, caseId); startActivityForResult(i, GET_CASE); } else { // Launch entity detail activity Intent detailIntent = new Intent(getApplicationContext(), EntityDetailActivity.class); EntityDetailUtils.populateDetailIntent( detailIntent, contextRef, entityDatum, asw); addPendingDataExtra(detailIntent, session); addPendingDatumIdExtra(detailIntent, session); startActivityForResult(detailIntent, GET_CASE); } } } private static void addPendingDataExtra(Intent i, CommCareSession session) { EvaluationContext evalContext = CommCareApplication._().getCurrentSessionWrapper().getEvaluationContext(); i.putExtra(KEY_PENDING_SESSION_DATA, session.getNeededData(evalContext)); } private static void addPendingDatumIdExtra(Intent i, CommCareSession session) { i.putExtra(KEY_PENDING_SESSION_DATUM_ID, session.getNeededDatum().getDataId()); } /** * Create (or re-use) a form record and pass it to the form entry activity * launcher. If there is an existing incomplete form that uses the same * case, ask the user if they want to edit or delete that one. * * @param state Needed for FormRecord manipulations */ private void startFormEntry(AndroidSessionWrapper state) { if (state.getFormRecordId() == -1) { if (CommCarePreferences.isIncompleteFormsEnabled()) { // Are existing (incomplete) forms using the same case? SessionStateDescriptor existing = state.getExistingIncompleteCaseDescriptor(); if (existing != null) { // Ask user if they want to just edit existing form that // uses the same case. createAskUseOldDialog(state, existing); return; } } // Generate a stub form record and commit it state.commitStub(); } else { Logger.log("form-entry", "Somehow ended up starting form entry with old state?"); } FormRecord record = state.getFormRecord(); AndroidCommCarePlatform platform = CommCareApplication._().getCommCarePlatform(); formEntry(platform.getFormContentUri(record.getFormNamespace()), record, CommCareActivity.getTitle(this, null)); } private void formEntry(Uri formUri, FormRecord r) { formEntry(formUri, r, null); } private void formEntry(Uri formUri, FormRecord r, String headerTitle) { Logger.log(AndroidLogger.TYPE_FORM_ENTRY, "Form Entry Starting|" + r.getFormNamespace()); //TODO: This is... just terrible. Specify where external instance data should come from FormLoaderTask.iif = new AndroidInstanceInitializer(CommCareApplication._().getCurrentSession()); // Create our form entry activity callout Intent i = new Intent(getApplicationContext(), FormEntryActivity.class); i.setAction(Intent.ACTION_EDIT); i.putExtra(FormEntryActivity.KEY_INSTANCEDESTINATION, CommCareApplication._().getCurrentApp().fsPath((GlobalConstants.FILE_CC_FORMS))); // See if there's existing form data that we want to continue entering // (note, this should be stored in the form record as a URI link to // the instance provider in the future) if(r.getInstanceURI() != null) { i.setData(r.getInstanceURI()); } else { i.setData(formUri); } i.putExtra(FormEntryActivity.KEY_RESIZING_ENABLED, CommCarePreferences.getResizeMethod()); i.putExtra(FormEntryActivity.KEY_INCOMPLETE_ENABLED, CommCarePreferences.isIncompleteFormsEnabled()); i.putExtra(FormEntryActivity.KEY_AES_STORAGE_KEY, Base64.encodeToString(r.getAesKey(), Base64.DEFAULT)); i.putExtra(FormEntryActivity.KEY_FORM_CONTENT_URI, FormsProviderAPI.FormsColumns.CONTENT_URI.toString()); i.putExtra(FormEntryActivity.KEY_INSTANCE_CONTENT_URI, InstanceProviderAPI.InstanceColumns.CONTENT_URI.toString()); i.putExtra(FormEntryActivity.KEY_RECORD_FORM_ENTRY_SESSION, DeveloperPreferences.isSessionSavingEnabled()); if (headerTitle != null) { i.putExtra(FormEntryActivity.KEY_HEADER_STRING, headerTitle); } if (isRestoringSession) { isRestoringSession = false; SharedPreferences prefs = CommCareApplication._().getCurrentApp().getAppPreferences(); String formEntrySession = prefs.getString(CommCarePreferences.CURRENT_FORM_ENTRY_SESSION, ""); if (!"".equals(formEntrySession)) { i.putExtra(FormEntryActivity.KEY_FORM_ENTRY_SESSION, formEntrySession); } } startActivityForResult(i, MODEL_RESULT); } /** * Triggered by a user manually clicking the sync button */ void syncButtonPressed() { if (!ConnectivityStatus.isNetworkAvailable(CommCareHomeActivity.this)) { if (ConnectivityStatus.isAirplaneModeOn(CommCareHomeActivity.this)) { displayMessage(Localization.get("notification.sync.airplane.action"), true, true); CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Sync_AirplaneMode, AIRPLANE_MODE_CATEGORY)); } else { displayMessage(Localization.get("notification.sync.connections.action"), true, true); CommCareApplication._().reportNotificationMessage(NotificationMessageFactory.message(NotificationMessageFactory.StockMessages.Sync_NoConnections, AIRPLANE_MODE_CATEGORY)); } GoogleAnalyticsUtils.reportSyncAttempt( GoogleAnalyticsFields.ACTION_USER_SYNC_ATTEMPT, GoogleAnalyticsFields.LABEL_SYNC_FAILURE, GoogleAnalyticsFields.VALUE_NO_CONNECTION); return; } CommCareApplication._().clearNotifications(AIRPLANE_MODE_CATEGORY); sendFormsOrSync(true); } /** * Triggered when an automatic sync is pending */ private void handlePendingSync() { long lastSync = CommCareApplication._().getCurrentApp().getAppPreferences().getLong("last-ota-restore", 0); String footer = lastSync == 0 ? "never" : SimpleDateFormat.getDateTimeInstance().format(lastSync); Logger.log(AndroidLogger.TYPE_USER, "autosync triggered. Last Sync|" + footer); uiController.refreshView(); sendFormsOrSync(false); } /** * Attempts first to send unsent forms to the server. If any forms are sent, a sync will be * triggered after they are submitted. If no forms are sent, triggers a sync explicitly. */ private void sendFormsOrSync(boolean userTriggeredSync) { boolean formsSentToServer = checkAndStartUnsentFormsTask(true, userTriggeredSync); if(!formsSentToServer) { formAndDataSyncer.syncDataForLoggedInUser(this, false, userTriggeredSync); } } /** * @return Were forms sent to the server by this method invocation? */ private boolean checkAndStartUnsentFormsTask(final boolean syncAfterwards, boolean userTriggered) { isSyncUserLaunched = userTriggered; SqlStorage<FormRecord> storage = CommCareApplication._().getUserStorage(FormRecord.class); FormRecord[] records = StorageUtils.getUnsentRecords(storage); if(records.length > 0) { formAndDataSyncer.processAndSendForms(this, records, syncAfterwards, userTriggered); return true; } else { return false; } } @Override protected void onResumeSessionSafe() { if (!sessionNavigationProceedingAfterOnResume) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { refreshActionBar(); } attemptDispatchHomeScreen(); } sessionNavigationProceedingAfterOnResume = false; } /** * Decides if we should actually be on the home screen, or else should redirect elsewhere */ private void attemptDispatchHomeScreen() { try { CommCareApplication._().getSession(); } catch (SessionUnavailableException e) { // User was logged out somehow, so we want to return to dispatch activity setResult(RESULT_OK); this.finish(); return; } if (CommCareApplication._().isSyncPending(false)) { // There is a sync pending handlePendingSync(); } else if (CommCareApplication._().isConsumerApp()) { // so that the user never sees the real home screen in a consumer app enterRootModule(); } else { // Display the normal home screen! uiController.refreshView(); } } private void createAskUseOldDialog(final AndroidSessionWrapper state, final SessionStateDescriptor existing) { final AndroidCommCarePlatform platform = CommCareApplication._().getCommCarePlatform(); String title = Localization.get("app.workflow.incomplete.continue.title"); String msg = Localization.get("app.workflow.incomplete.continue"); StandardAlertDialog d = new StandardAlertDialog(this, title, msg); DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int i) { switch (i) { case DialogInterface.BUTTON_POSITIVE: // use the old form instance and load the it's state from the descriptor state.loadFromStateDescription(existing); formEntry(platform.getFormContentUri(state.getSession().getForm()), state.getFormRecord()); break; case DialogInterface.BUTTON_NEGATIVE: // delete the old incomplete form FormRecordCleanupTask.wipeRecord(CommCareHomeActivity.this, existing); // fallthrough to new now that old record is gone case DialogInterface.BUTTON_NEUTRAL: // create a new form record and begin form entry state.commitStub(); formEntry(platform.getFormContentUri(state.getSession().getForm()), state.getFormRecord()); } dismissAlertDialog(); } }; d.setPositiveButton(Localization.get("option.yes"), listener); d.setNegativeButton(Localization.get("app.workflow.incomplete.continue.option.delete"), listener); d.setNeutralButton(Localization.get("option.no"), listener); showAlertDialog(d); } @Override public void reportSuccess(String message) { displayMessage(message, false, false); } @Override public void reportFailure(String message, boolean showPopupNotification) { displayMessage(message, true, !showPopupNotification); } void displayMessage(String message, boolean bad, boolean suppressToast) { uiController.displayMessage(message, bad, suppressToast); } public static boolean isDemoUser() { try { User u = CommCareApplication._().getSession().getLoggedInUser(); return (User.TYPE_DEMO.equals(u.getUserType())); } catch (SessionUnavailableException e) { // Default to a normal user: this should only happen if session // expires and hasn't redirected to login. return false; } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_UPDATE, 0, Localization.get("home.menu.update")).setIcon( android.R.drawable.ic_menu_upload); menu.add(0, MENU_SAVED_FORMS, 0, Localization.get("home.menu.saved.forms")).setIcon( android.R.drawable.ic_menu_save); menu.add(0, MENU_CHANGE_LANGUAGE, 0, Localization.get("home.menu.locale.change")).setIcon( android.R.drawable.ic_menu_set_as); menu.add(0, MENU_ABOUT, 0, Localization.get("home.menu.about")).setIcon( android.R.drawable.ic_menu_help); menu.add(0, MENU_ADVANCED, 0, Localization.get("home.menu.advanced")).setIcon( android.R.drawable.ic_menu_edit); menu.add(0, MENU_PREFERENCES, 0, Localization.get("home.menu.settings")).setIcon( android.R.drawable.ic_menu_preferences); menu.add(0, MENU_PIN, 0, Localization.get("home.menu.pin.set")); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); GoogleAnalyticsUtils.reportOptionsMenuEntry(GoogleAnalyticsFields.CATEGORY_HOME_SCREEN); //In Holo theme this gets called on startup boolean enableMenus = !isDemoUser(); menu.findItem(MENU_UPDATE).setVisible(enableMenus); menu.findItem(MENU_SAVED_FORMS).setVisible(enableMenus); menu.findItem(MENU_CHANGE_LANGUAGE).setVisible(enableMenus); menu.findItem(MENU_PREFERENCES).setVisible(enableMenus); menu.findItem(MENU_ADVANCED).setVisible(enableMenus); menu.findItem(MENU_ABOUT).setVisible(enableMenus); preparePinMenu(menu, enableMenus); return true; } private static void preparePinMenu(Menu menu, boolean enableMenus) { boolean pinEnabled = enableMenus && DeveloperPreferences.shouldOfferPinForLogin(); menu.findItem(MENU_PIN).setVisible(pinEnabled); boolean hasPinSet = false; try { hasPinSet = CommCareApplication._().getRecordForCurrentUser().hasPinSet(); } catch (SessionUnavailableException e) { Log.d(TAG, "Session expired and menu is being created before redirect to login screen"); } if (hasPinSet) { menu.findItem(MENU_PIN).setTitle(Localization.get("home.menu.pin.change")); } else { menu.findItem(MENU_PIN).setTitle(Localization.get("home.menu.pin.set")); } } @Override public boolean onOptionsItemSelected(MenuItem item) { Map<Integer, String> menuIdToAnalyticsEventLabel = createMenuItemToEventMapping(); GoogleAnalyticsUtils.reportOptionsMenuItemEntry( GoogleAnalyticsFields.CATEGORY_HOME_SCREEN, menuIdToAnalyticsEventLabel.get(item.getItemId())); switch (item.getItemId()) { case MENU_UPDATE: Intent i = new Intent(getApplicationContext(), UpdateActivity.class); startActivity(i); return true; case MENU_SAVED_FORMS: goToFormArchive(false); return true; case MENU_CHANGE_LANGUAGE: showLocaleChangeMenu(); return true; case MENU_PREFERENCES: createPreferencesMenu(this); return true; case MENU_ADVANCED: startAdvancedActionsActivity(); return true; case MENU_ABOUT: showAboutCommCareDialog(); return true; case MENU_PIN: launchPinAuthentication(); return true; } return super.onOptionsItemSelected(item); } private static Map<Integer, String> createMenuItemToEventMapping() { Map<Integer, String> menuIdToAnalyticsEvent = new HashMap<>(); menuIdToAnalyticsEvent.put(MENU_UPDATE, GoogleAnalyticsFields.LABEL_UPDATE_CC); menuIdToAnalyticsEvent.put(MENU_SAVED_FORMS, GoogleAnalyticsFields.LABEL_SAVED_FORMS); menuIdToAnalyticsEvent.put(MENU_CHANGE_LANGUAGE, GoogleAnalyticsFields.LABEL_LOCALE); menuIdToAnalyticsEvent.put(MENU_PREFERENCES, GoogleAnalyticsFields.LABEL_SETTINGS); menuIdToAnalyticsEvent.put(MENU_ADVANCED, GoogleAnalyticsFields.LABEL_ADVANCED_ACTIONS); menuIdToAnalyticsEvent.put(MENU_ABOUT, GoogleAnalyticsFields.LABEL_ABOUT_CC); return menuIdToAnalyticsEvent; } public static void createPreferencesMenu(Activity activity) { Intent i = new Intent(activity, CommCarePreferences.class); activity.startActivityForResult(i, PREFERENCES_ACTIVITY); } private void startAdvancedActionsActivity() { startActivityForResult(new Intent(this, AdvancedActionsActivity.class), ADVANCED_ACTIONS_ACTIVITY); } private void showAboutCommCareDialog() { CommCareAlertDialog dialog = DialogCreationHelpers.buildAboutCommCareDialog(this); dialog.makeCancelable(); dialog.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { handleDeveloperModeClicks(); } }); showAlertDialog(dialog); } private void handleDeveloperModeClicks() { mDeveloperModeClicks++; if (mDeveloperModeClicks == 4) { CommCareApplication._().getCurrentApp().getAppPreferences() .edit() .putString(DeveloperPreferences.SUPERUSER_ENABLED, CommCarePreferences.YES) .commit(); Toast.makeText(CommCareHomeActivity.this, Localization.get("home.developer.options.enabled"), Toast.LENGTH_SHORT).show(); } } @Override public CustomProgressDialog generateProgressDialog(int taskId) { String title, message; CustomProgressDialog dialog; switch (taskId) { case ProcessAndSendTask.SEND_PHASE_ID: title = Localization.get("sync.progress.submitting.title"); message = Localization.get("sync.progress.submitting"); dialog = CustomProgressDialog.newInstance(title, message, taskId); break; case ProcessAndSendTask.PROCESSING_PHASE_ID: title = Localization.get("form.entry.processing.title"); message = Localization.get("form.entry.processing"); dialog = CustomProgressDialog.newInstance(title, message, taskId); dialog.addProgressBar(); break; case DataPullTask.DATA_PULL_TASK_ID: title = Localization.get("sync.communicating.title"); message = Localization.get("sync.progress.purge"); dialog = CustomProgressDialog.newInstance(title, message, taskId); if (isSyncUserLaunched) { // allow users to cancel syncs that they launched dialog.addCancelButton(); } isSyncUserLaunched = false; break; default: Log.w(TAG, "taskId passed to generateProgressDialog does not match " + "any valid possibilities in CommCareHomeActivity"); return null; } return dialog; } @Override public boolean isBackEnabled() { return false; } /** * For Testing purposes only */ public SessionNavigator getSessionNavigator() { if (BuildConfig.DEBUG) { return sessionNavigator; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } /** * For Testing purposes only */ public void setFormAndDataSyncer(FormAndDataSyncer formAndDataSyncer) { if (BuildConfig.DEBUG) { this.formAndDataSyncer = formAndDataSyncer; } else { throw new RuntimeException("On principal of design, only meant for testing purposes"); } } public FormAndDataSyncer getFormAndDataSyncer() { return formAndDataSyncer; } @Override public void initUIController() { uiController = new HomeActivityUIController(this); } @Override public CommCareActivityUIController getUIController() { return this.uiController; } @Override public void handlePullTaskResult(ResultAndError<DataPullTask.PullTaskResult> resultAndErrorMessage, boolean userTriggeredSync, boolean formsToSend) { getUIController().refreshView(); if (CommCareApplication._().isConsumerApp()) { return; } SyncUIHandling.handleSyncResult(this, resultAndErrorMessage, userTriggeredSync, formsToSend); } @Override public void handlePullTaskUpdate(Integer... update) { SyncUIHandling.handleSyncUpdate(this, update); } @Override public void handlePullTaskError(Exception e) { reportFailure(Localization.get("sync.fail.unknown"), true); } }
package org.bouncycastle.crypto.tls; /** * RFC 5246 7.2. */ public class AlertDescription { /** * This message notifies the recipient that the sender will not send any more messages on this * connection. The session becomes unresumable if any connection is terminated without proper * close_notify messages with level equal to warning. */ public static final short close_notify = 0; /** * An inappropriate message was received. This alert is always fatal and should never be * observed in communication between proper implementations. */ public static final short unexpected_message = 10; /** * This alert is returned if a record is received with an incorrect MAC. This alert also MUST be * returned if an alert is sent because a TLSCiphertext decrypted in an invalid way: either it * wasn't an even multiple of the block length, or its padding values, when checked, weren't * correct. This message is always fatal and should never be observed in communication between * proper implementations (except when messages were corrupted in the network). */ public static final short bad_record_mac = 20; /** * This alert was used in some earlier versions of TLS, and may have permitted certain attacks * against the CBC mode [CBCATT]. It MUST NOT be sent by compliant implementations. */ public static final short decryption_failed = 21; /** * A TLSCiphertext record was received that had a length more than 2^14+2048 bytes, or a record * decrypted to a TLSCompressed record with more than 2^14+1024 bytes. This message is always * fatal and should never be observed in communication between proper implementations (except * when messages were corrupted in the network). */ public static final short record_overflow = 22; /** * The decompression function received improper input (e.g., data that would expand to excessive * length). This message is always fatal and should never be observed in communication between * proper implementations. */ public static final short decompression_failure = 30; /** * Reception of a handshake_failure alert message indicates that the sender was unable to * negotiate an acceptable set of security parameters given the options available. This is a * fatal error. */ public static final short handshake_failure = 40; /** * This alert was used in SSLv3 but not any version of TLS. It MUST NOT be sent by compliant * implementations. */ public static final short no_certificate = 41; /** * A certificate was corrupt, contained signatures that did not verify correctly, etc. */ public static final short bad_certificate = 42; /** * A certificate was of an unsupported type. */ public static final short unsupported_certificate = 43; /** * A certificate was revoked by its signer. */ public static final short certificate_revoked = 44; /** * A certificate has expired or is not currently valid. */ public static final short certificate_expired = 45; /** * Some other (unspecified) issue arose in processing the certificate, rendering it * unacceptable. */ public static final short certificate_unknown = 46; /** * A field in the handshake was out of range or inconsistent with other fields. This message is * always fatal. */ public static final short illegal_parameter = 47; /** * A valid certificate chain or partial chain was received, but the certificate was not accepted * because the CA certificate could not be located or couldn't be matched with a known, trusted * CA. This message is always fatal. */ public static final short unknown_ca = 48; /** * A valid certificate was received, but when access control was applied, the sender decided not * to proceed with negotiation. This message is always fatal. */ public static final short access_denied = 49; /** * A message could not be decoded because some field was out of the specified range or the * length of the message was incorrect. This message is always fatal and should never be * observed in communication between proper implementations (except when messages were corrupted * in the network). */ public static final short decode_error = 50; /** * A handshake cryptographic operation failed, including being unable to correctly verify a * signature or validate a Finished message. This message is always fatal. */ public static final short decrypt_error = 51; /** * This alert was used in some earlier versions of TLS. It MUST NOT be sent by compliant * implementations. */ public static final short export_restriction = 60; /** * The protocol version the client has attempted to negotiate is recognized but not supported. * (For example, old protocol versions might be avoided for security reasons.) This message is * always fatal. */ public static final short protocol_version = 70; /** * Returned instead of handshake_failure when a negotiation has failed specifically because the * server requires ciphers more secure than those supported by the client. This message is * always fatal. */ public static final short insufficient_security = 71; /** * An internal error unrelated to the peer or the correctness of the protocol (such as a memory * allocation failure) makes it impossible to continue. This message is always fatal. */ public static final short internal_error = 80; /** * This handshake is being canceled for some reason unrelated to a protocol failure. If the user * cancels an operation after the handshake is complete, just closing the connection by sending * a close_notify is more appropriate. This alert should be followed by a close_notify. This * message is generally a warning. */ public static final short user_canceled = 90; /** * Sent by the client in response to a hello request or by the server in response to a client * hello after initial handshaking. Either of these would normally lead to renegotiation; when * that is not appropriate, the recipient should respond with this alert. At that point, the * original requester can decide whether to proceed with the connection. One case where this * would be appropriate is where a server has spawned a process to satisfy a request; the * process might receive security parameters (key length, authentication, etc.) at startup, and * it might be difficult to communicate changes to these parameters after that point. This * message is always a warning. */ public static final short no_renegotiation = 100; /** * Sent by clients that receive an extended server hello containing an extension that they did * not put in the corresponding client hello. This message is always fatal. */ public static final short unsupported_extension = 110; /* * RFC 3546 */ /** * This alert is sent by servers who are unable to retrieve a certificate chain from the URL * supplied by the client (see Section 3.3). This message MAY be fatal - for example if client * authentication is required by the server for the handshake to continue and the server is * unable to retrieve the certificate chain, it may send a fatal alert. */ public static final short certificate_unobtainable = 111; /** * This alert is sent by servers that receive a server_name extension request, but do not * recognize the server name. This message MAY be fatal. */ public static final short unrecognized_name = 112; /** * This alert is sent by clients that receive an invalid certificate status response (see * Section 3.6). This message is always fatal. */ public static final short bad_certificate_status_response = 113; /** * This alert is sent by servers when a certificate hash does not match a client provided * certificate_hash. This message is always fatal. */ public static final short bad_certificate_hash_value = 114; /* * RFC 4279 */ /** * If the server does not recognize the PSK identity, it MAY respond with an * "unknown_psk_identity" alert message. */ public static final short unknown_psk_identity = 115; }
package org.dainst.gazetteer.helpers; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import org.dainst.gazetteer.domain.PlaceName; public class PlaceNameHelper { private Locale locale; private Locale originalLocale; private LanguagesHelper languagesHelper; private Map<String, String> localizedLanguages; public List<PlaceName> sortPlaceNames(Set<PlaceName> placeNames) { localizedLanguages = languagesHelper.getLocalizedLanguages(locale); List<PlaceName> result = new ArrayList<PlaceName>(placeNames); Collections.sort(result, new PlaceNameComparator()); return result; } public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } public Locale getOriginalLocale() { return originalLocale; } public void setOriginalLocale(Locale originalLocale) { this.originalLocale = originalLocale; } public LanguagesHelper getLanguagesHelper() { return languagesHelper; } public void setLanguagesHelper(LanguagesHelper languagesHelper) { this.languagesHelper = languagesHelper; } private class PlaceNameComparator implements Comparator<PlaceName> { public int compare(PlaceName placeName1, PlaceName placeName2) { int langComp; if ((placeName1.getLanguage() == null || placeName1.getLanguage().isEmpty()) && (placeName2.getLanguage() != null && !placeName2.getLanguage().isEmpty())) langComp = 1; else if ((placeName2.getLanguage() == null || placeName2.getLanguage().isEmpty()) && (placeName1.getLanguage() != null && !placeName1.getLanguage().isEmpty())) langComp = -1; else if ((placeName1.getLanguage() == null || placeName1.getLanguage().isEmpty()) && (placeName2.getLanguage() == null || placeName2.getLanguage().isEmpty())) langComp = 0; else if (originalLocale.getISO3Language().equals(new Locale(placeName1.getLanguage()).getISO3Language()) && !originalLocale.getISO3Language().equals(new Locale(placeName2.getLanguage()).getISO3Language())) langComp = -1; else if (originalLocale.getISO3Language().equals(new Locale(placeName2.getLanguage()).getISO3Language()) && !originalLocale.getISO3Language().equals(new Locale(placeName1.getLanguage()).getISO3Language())) langComp = 1; else { String localizedLanguage1 = localizedLanguages.get(placeName1.getLanguage()); String localizedLanguage2 = localizedLanguages.get(placeName2.getLanguage()); if (localizedLanguage1 != null && localizedLanguage2 != null) langComp = Collator.getInstance(locale).compare(localizedLanguage1, localizedLanguage2); else langComp = 0; } if (langComp != 0) return langComp; else return Collator.getInstance(locale).compare(placeName1.getTitle(), placeName2.getTitle()); } } }
package org.dannil.httpdownloader.utility; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; /** * Class for fetching and manipulate data from XML files. * * @author Daniel Nilsson */ public final class XMLUtility { private String path; /** * Default constructor */ private XMLUtility() { } /** * Overloaded constructor * * @param path * the path of the XML file */ public XMLUtility(final String path) { this(); this.path = path; } /** * Returns the value for a specific element, as decided by the specified XPath expression. * * @param expression * the expression to compute * * @return the element's value */ public final String getElementValue(final String expression) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(this.path); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(expression); return (String) expr.evaluate(doc, XPathConstants.STRING); } catch (Exception e) { e.printStackTrace(); } return null; } }
package org.ftcTeam.opmodes.registrar1; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.hardware.DcMotor; import org.ftcTeam.configurations.Team8702Auto; import org.ftcTeam.opmodes.AutoStepEncoder; import org.ftcTeam.opmodes.BeaconHitter; import org.ftcTeam.opmodes.ColorValue; import org.ftcTeam.opmodes.RobotAutonomousUtils; import org.ftcbootstrap.ActiveOpMode; import org.ftcbootstrap.components.operations.motors.TankDriveToEncoder; import org.ftcbootstrap.components.operations.motors.TankDriveToODS; import org.ftcbootstrap.components.utils.DriveDirection; /** * Note: This Exercise assumes that you have used your Robot Controller App to "scan" your hardware and * saved the configuration named: "DemoBot" and creating a class by the same name: {@link Team8702Auto}. * <p/> * Note: It is assumed that the proper registry is used for this set of demos. To confirm please * search for "Enter your custom registry here" in {@link org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity;} * <p/> * Summary: * <p/> * Opmode demonstrates running a motor from and encoder */ @Autonomous public class AutoODEncoder extends ActiveOpMode { private Team8702Auto robot; private TankDriveToODS tankDriveToODS; private TankDriveToEncoder tankDriveToEncoder; private int majorStep; ColorValue rainbowValue; BeaconHitter firstBeacon; BeaconHitter secondBeacon; boolean targetReached = false; /** * Implement this method to define the code to run when the Init button is pressed on the Driver station. */ @Override protected void onInit() { //specify configuration name save from scan operation robot = Team8702Auto.newConfig(hardwareMap, getTelemetryUtil()); getTelemetryUtil().addData("Init", getClass().getSimpleName() + " initialized."); getTelemetryUtil().sendTelemetry(); tankDriveToEncoder = new TankDriveToEncoder(this, robot.motorL, robot.motorR); tankDriveToODS = new TankDriveToODS( this, robot.ods, robot.motorL, robot.motorR ); getTelemetryUtil().sendTelemetry(); //firstBeacon = new BeaconHitter(getTelemetryUtil(), rainbowValue); //secondBeacon = new BeaconHitter(getTelemetryUtil(), rainbowValue); } @Override protected void onStart() throws InterruptedException { super.onStart(); tankDriveToODS.setName("driving to white line"); majorStep = 1; } /** * Implement this method to define the code to run when the Start button is pressed on the Driver station. * This method will be called on each hardware cycle just as the loop() method is called for event based Opmodes * @throws InterruptedException */ @Override protected void activeLoop() throws InterruptedException { getTelemetryUtil().addData("Current Major Step: ", majorStep); //send any telemetry that may have been added in the above operations switch(majorStep) { case 1: // Go straight towards the beacon boolean reachedDestination = false; getTelemetryUtil().addData("Current Major Step: ", majorStep); // Need to change the motors to run without encoder to use OD robot.motorL.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); robot.motorR.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); while(!reachedDestination) { reachedDestination = tankDriveToODS.runToTarget(0.2, 0.5, DriveDirection.DRIVE_FORWARD); } if( reachedDestination) { majorStep++; getTelemetryUtil().addData("Current Major Step: ", majorStep); getTelemetryUtil().sendTelemetry(); RobotAutonomousUtils.pauseMotor(robot.motorR, robot.motorL); } break; case 2: //Turn left towards the beacon targetReached = false; getTelemetryUtil().addData("Current Major Step: ", majorStep); while(!targetReached) { targetReached = tankDriveToEncoder.runToTarget(0.2, AutoStepEncoder.NINTY_ANGLE_TURN_VALUE , DriveDirection.SPIN_LEFT,DcMotor.RunMode.RUN_USING_ENCODER); } RobotAutonomousUtils.pauseMotor(robot.motorR, robot.motorL); getTelemetryUtil().sendTelemetry(); majorStep++; break; case 3: //Go straight to in front of the beacon targetReached = false; double power = 0.1; //brightness assumes fixed distance from the target //i.e. line follow or stop on white line double targetBrightness = 0.5; double targetTime = 5; //seconds getTelemetryUtil().addData("Current Major Step: ", majorStep); while(!targetReached) { if (tankDriveToODS.lineFollowForTime( power, targetBrightness, targetTime, DriveDirection.PIVOT_FORWARD_RIGHT)) { // step++; } } //majorStep++; majorStep = 99; break; case 99: getTelemetryUtil().addData("Running: ", "99: "); robot.motorR.setPower(0); robot.motorL.setPower(0); break; } getTelemetryUtil().sendTelemetry(); } }
package org.ihtsdo.otf.rest.client; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.stream.JsonWriter; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.time.FastDateFormat; import org.apache.http.HttpEntity; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.ihtsdo.otf.rest.client.resty.HttpEntityContent; import org.ihtsdo.otf.rest.client.resty.RestyHelper; import org.ihtsdo.otf.rest.exception.BadRequestException; import org.ihtsdo.otf.rest.exception.BusinessServiceException; import org.ihtsdo.otf.rest.exception.ProcessingException; import org.ihtsdo.otf.utils.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Required; import org.springframework.util.Assert; import us.monoid.json.JSONArray; import us.monoid.json.JSONException; import us.monoid.json.JSONObject; import us.monoid.web.BinaryResource; import us.monoid.web.JSONResource; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; public class SnowOwlRestClient { public static final String SNOWOWL_CONTENT_TYPE = "application/vnd.com.b2international.snowowl+json"; public static final String ANY_CONTENT_TYPE = "*/*"; public static final FastDateFormat SIMPLE_DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd_HH-mm-ss"); public static final String US_EN_LANG_REFSET = "900000000000509007"; private final SnowOwlRestUrlHelper urlHelper; public enum ExtractType { DELTA, SNAPSHOT, FULL; }; public enum ProcessingStatus { COMPLETED, SAVED } public enum ExportType { PUBLISHED, UNPUBLISHED; } private final RestyHelper resty; private String reasonerId; private String logPath; private String rolloverLogPath; private final Gson gson; private int importTimeoutMinutes; private int classificationTimeoutMinutes; //Timeout of 0 means don't time out. private static final int INDENT = 2; private final Logger logger = LoggerFactory.getLogger(getClass()); public SnowOwlRestClient(String snowOwlUrl, String username, String password) { this.resty = new RestyHelper(ANY_CONTENT_TYPE); urlHelper = new SnowOwlRestUrlHelper(snowOwlUrl); resty.authenticate(snowOwlUrl, username, password.toCharArray()); gson = new GsonBuilder().setPrettyPrinting().create(); } public void createProjectBranch(String branchName) throws RestClientException { createBranch(urlHelper.getMainBranchPath(), branchName); } public void createProjectBranchIfNeeded(String projectName) throws RestClientException { if (!listProjectBranches().contains(projectName)) { createProjectBranch(projectName); } } private void createBranch(String parentBranch, String newBranchName) throws RestClientException { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("parent", parentBranch); jsonObject.put("name", newBranchName); resty.json(urlHelper.getBranchesUrl(), RestyHelper.content((jsonObject), SNOWOWL_CONTENT_TYPE)); } catch (Exception e) { throw new RestClientException("Failed to create branch " + newBranchName + ", parent branch " + parentBranch, e); } } public List<String> listProjectBranches() throws RestClientException { return listBranchDirectChildren(urlHelper.getMainBranchPath()); } public List<String> listProjectTasks(String projectName) throws RestClientException { return listBranchDirectChildren(urlHelper.getBranchPath(projectName)); } private List<String> listBranchDirectChildren(String branchPath) throws RestClientException { try { List<String> projectNames = new ArrayList<>(); JSONResource json = resty.json(urlHelper.getBranchChildrenUrl(branchPath)); try { @SuppressWarnings("unchecked") List<String> childBranchPaths = (List<String>) json.get("items.path"); for (String childBranchPath : childBranchPaths) { String branchName = childBranchPath.substring((branchPath + "/").length()); if (!branchName.contains("/")) { projectNames.add(branchName); } } } catch (JSONException e) { // this thrown if there are no items.. do nothing } return projectNames; } catch (IOException e) { throw new RestClientException("Failed to retrieve branch list.", e); } catch (Exception e) { throw new RestClientException("Failed to parse branch list.", e); } } public void deleteProjectBranch(String projectBranchName) throws RestClientException { deleteBranch(projectBranchName); } public void deleteTaskBranch(String projectName, String taskName) throws RestClientException { deleteBranch(projectName + "/" + taskName); } private void deleteBranch(String branchPathRelativeToMain) throws RestClientException { try { resty.json(urlHelper.getBranchUrlRelativeToMain(branchPathRelativeToMain), RestyHelper.delete()); } catch (Exception e) { throw new RestClientException("Failed to delete branch " + branchPathRelativeToMain, e); } } public void createProjectTask(String projectName, String taskName) throws RestClientException { createBranch(urlHelper.getBranchPath(projectName), taskName); } public void createProjectTaskIfNeeded(String projectName, String taskName) throws RestClientException { if (!listProjectTasks(projectName).contains(taskName)) { createProjectTask(projectName, taskName); } } public boolean importRF2Archive(String projectName, String taskName, final InputStream rf2ZipFileStream) throws RestClientException { Assert.notNull(rf2ZipFileStream, "Archive to import should not be null."); try { // Create import String branchPath = urlHelper.getBranchPath(projectName, taskName); logger.info("Create import, branch '{}'", branchPath); JSONObject params = new JSONObject(); params.put("type", "DELTA"); params.put("branchPath", branchPath); params.put("languageRefSetId", US_EN_LANG_REFSET); params.put("createVersions", "false"); resty.withHeader("Accept", SNOWOWL_CONTENT_TYPE); JSONResource json = resty.json(urlHelper.getImportsUrl(), RestyHelper.content(params, SNOWOWL_CONTENT_TYPE)); String location = json.getUrlConnection().getHeaderField("Location"); String importId = location.substring(location.lastIndexOf("/") + 1); // Create file from stream File tempDirectory = Files.createTempDirectory(getClass().getSimpleName()).toFile(); File tempFile = new File(tempDirectory, "SnomedCT_Release_INT_20150101.zip"); try { try (FileOutputStream output = new FileOutputStream(tempFile)) { IOUtils.copy(rf2ZipFileStream, output); } // Post file to TS MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addBinaryBody("file", tempFile, ContentType.create("application/zip"), tempFile.getName()); multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); HttpEntity httpEntity = multipartEntityBuilder.build(); resty.withHeader("Accept", ANY_CONTENT_TYPE); resty.json(urlHelper.getImportArchiveUrl(importId), new HttpEntityContent(httpEntity)); } finally { tempFile.delete(); tempDirectory.delete(); } // Poll import entity until complete or times-out logger.info("SnowOwl processing import, this will probably take a few minutes. (Import ID '{}')", importId); return waitForStatus(urlHelper.getImportUrl(importId), getTimeoutDate(importTimeoutMinutes), ProcessingStatus.COMPLETED, "import"); } catch (Exception e) { throw new RestClientException("Import failed.", e); } } public ClassificationResults startClassification (String branchPath) throws RestClientException { ClassificationResults results = new ClassificationResults(); try { JSONObject requestJson = new JSONObject().put("reasonerId", reasonerId); String classifyURL = urlHelper.getClassificationsUrl(branchPath); logger.info("Initiating classification via {}", classifyURL); JSONResource jsonResponse = resty.json(classifyURL, requestJson, SNOWOWL_CONTENT_TYPE); String classificationLocation = jsonResponse.getUrlConnection().getHeaderField("Location"); if (classificationLocation == null) { String errorMsg = "Failed to recover classificationLocation. Call to " + classifyURL + " returned httpStatus '" + jsonResponse.getHTTPStatus() + "'"; try { errorMsg += " and body '" + jsonResponse.toObject().toString(INDENT) + "'."; } catch (Exception e) { errorMsg += ". Also failed to parse response object."; } throw new RestClientException (errorMsg); } results.setClassificationId(classificationLocation.substring(classificationLocation.lastIndexOf("/") + 1)); results.setClassificationLocation(classificationLocation); } catch (JSONException | IOException e) { throw new RestClientException("Create classification failed.", e); } return results; } /** * Initiates a classification and waits for the results. * {@link #isClassificationInProgressOnBranch(String)} can be used to check that a classification is not already in progress * prior to calling this method. * @param branchPath * @return * @throws RestClientException * @throws InterruptedException */ public ClassificationResults classify(String branchPath) throws RestClientException, InterruptedException { ClassificationResults results = startClassification(branchPath); results = waitForClassificationToComplete(results); return results; } public ClassificationResults waitForClassificationToComplete(ClassificationResults results) throws RestClientException, InterruptedException { String classificationLocation = results.getClassificationLocation(); String date = SIMPLE_DATE_FORMAT.format(new Date()); logger.info("SnowOwl classifier running, this will probably take a few minutes. (Classification URL '{}')", classificationLocation); boolean classifierCompleted = waitForStatus(classificationLocation, getTimeoutDate(classificationTimeoutMinutes), ProcessingStatus.COMPLETED, "classifier"); if (classifierCompleted) { results.setStatus(ProcessingStatus.COMPLETED.toString()); try { // Check equivalent concepts JSONArray items = getItems(urlHelper.getEquivalentConceptsUrl(classificationLocation)); boolean equivalentConceptsFound = !(items == null || items.length() == 0); results.setEquivalentConceptsFound(equivalentConceptsFound); if (equivalentConceptsFound) { results.setEquivalentConceptsJson(toPrettyJson(items.toString())); } } catch (Exception e) { throw new RestClientException("Failed to retrieve equivalent concepts of classification.", e); } try { // Check relationship changes JSONResource relationshipChangesUnlimited = resty.json(urlHelper.getRelationshipChangesFirstTenThousand(classificationLocation)); Integer total = (Integer) relationshipChangesUnlimited.get("total"); results.setRelationshipChangesCount(total); Path tempDirectory = Files.createTempDirectory(getClass().getSimpleName()); File file = new File(tempDirectory.toFile(), "relationship-changes-" + date + ".json"); toPrettyJson(relationshipChangesUnlimited.object().toString(), file); results.setRelationshipChangesFile(file); } catch (Exception e) { throw new RestClientException("Failed to retrieve relationship changes of classification.", e); } return results; } else { throw new RestClientException("Classification failed, see SnowOwl logs for details."); } } public String getLatestClassificationOnBranch(String branchPath) throws RestClientException { JSONObject obj = getLatestClassificationObjectOnBranch(branchPath); return (obj != null) ? obj.toString() : null; } public boolean isClassificationInProgressOnBranch(String branchPath) throws RestClientException, JSONException { final JSONObject classification = getLatestClassificationObjectOnBranch(branchPath); if (classification != null) { final String status = classification.getString("status"); return "SCHEDULED".equals(status) || "RUNNING".equals(status); } return false; } private JSONObject getLatestClassificationObjectOnBranch(String branchPath) throws RestClientException { final String classificationsUrl = urlHelper.getClassificationsUrl(branchPath); try { final JSONArray items = getItems(classificationsUrl); if (items != null) { return items.getJSONObject(items.length() - 1); } return null; } catch (Exception e) { throw new RestClientException("Failed to retrieve list of classifications.", e); } } public void saveClassification(String branchPath, String classificationId) throws RestClientException, InterruptedException { String classifyURL = urlHelper.getClassificationsUrl(branchPath); try { logger.debug("Saving classification via {}", classifyURL); JSONObject jsonObj = new JSONObject().put("status", "SAVED"); resty.put(classifyURL, jsonObj, SNOWOWL_CONTENT_TYPE); //We'll wait the same time for saving as we do for the classification boolean savingCompleted = waitForStatus(classifyURL, getTimeoutDate(classificationTimeoutMinutes), ProcessingStatus.SAVED, "classifier result saving"); if (!savingCompleted) { throw new IOException("Classifier reported non-saved status when saving"); } } catch (Exception e) { throw new RestClientException("Failed to save classification via URL " + classifyURL, e); } } private JSONArray getItems(String url) throws Exception { JSONResource jsonResource = resty.json(url); JSONArray items = null; try { items = (JSONArray) jsonResource.get("items"); } catch (Exception e) { // TODO Change this back to JSONException when Resty handles that. // this gets thrown when the attribute does not exist logger.info("No items property of resource at '{}'", url); } return items; } public File exportTask(String projectName, String taskName, ExtractType extractType) throws Exception { String branchPath = urlHelper.getBranchPath(projectName, taskName); return export(branchPath, null, ExportType.UNPUBLISHED, extractType); } public File exportProject(String projectName, ExtractType extractType) throws Exception { String branchPath = urlHelper.getBranchPath(projectName, null); return export(branchPath, null, ExportType.UNPUBLISHED, extractType); } public File export(String branchPath, String effectiveDate, ExportType exportType, ExtractType extractType) throws BusinessServiceException { JSONObject jsonObj = prepareExportJSON(branchPath, effectiveDate, exportType, extractType); String exportLocationURL = initiateExport(jsonObj); return recoverExportedArchive(exportLocationURL); } private JSONObject prepareExportJSON(String branchPath, String effectiveDate, ExportType exportType, ExtractType extractType) throws BusinessServiceException { JSONObject jsonObj = new JSONObject(); try { jsonObj.put("type", extractType); jsonObj.put("branchPath", branchPath); switch (exportType) { case UNPUBLISHED: String tet = (effectiveDate == null) ? DateUtils.now(DateUtils.YYYYMMDD) : effectiveDate; jsonObj.put("transientEffectiveTime", tet); break; case PUBLISHED: if (effectiveDate == null) { throw new ProcessingException("Cannot export published data without an effective date"); } jsonObj.put("deltaStartEffectiveTime", effectiveDate); jsonObj.put("deltaEndEffectiveTime", effectiveDate); jsonObj.put("transientEffectiveTime", effectiveDate); break; default: throw new BadRequestException("Export type " + exportType + " not recognised"); } } catch (JSONException e) { throw new ProcessingException("Failed to prepare JSON for export request.", e); } return jsonObj; } private String initiateExport(JSONObject jsonObj) throws BusinessServiceException { try { logger.info("Initiating export via url {} with json: {}", urlHelper.getExportsUrl(), jsonObj.toString()); JSONResource jsonResponse = resty.json(urlHelper.getExportsUrl(), RestyHelper.content(jsonObj, SNOWOWL_CONTENT_TYPE)); Object exportLocationURLObj = jsonResponse.getUrlConnection().getHeaderField("Location"); if (exportLocationURLObj == null) { throw new ProcessingException("Failed to obtain location of export, instead got status '" + jsonResponse.getHTTPStatus() + "' and body: " + jsonResponse.toObject().toString(INDENT)); } return exportLocationURLObj.toString() + "/archive"; } catch (Exception e) { // TODO Change this to catch JSONException once Resty no longer throws Exceptions throw new ProcessingException("Failed to initiate export", e); } } private File recoverExportedArchive(String exportLocationURL) throws BusinessServiceException { try { logger.debug("Recovering exported archive from {}", exportLocationURL); resty.withHeader("Accept", ANY_CONTENT_TYPE); BinaryResource archiveResource = resty.bytes(exportLocationURL); File archive = File.createTempFile("ts-extract", ".zip"); archiveResource.save(archive); logger.debug("Extract saved to {}", archive.getAbsolutePath()); return archive; } catch (IOException e) { throw new BusinessServiceException("Unable to recover exported archive from " + exportLocationURL, e); } } public void rebaseTask(String projectName, String taskName) throws RestClientException { String taskPath = urlHelper.getBranchPath(projectName, taskName); String projectPath = urlHelper.getBranchPath(projectName); logger.info("Rebasing branch {} from parent {}", taskPath, projectPath); merge(projectPath, taskPath); } public void mergeTaskToProject(String projectName, String taskName) throws RestClientException { String taskPath = urlHelper.getBranchPath(projectName, taskName); String projectPath = urlHelper.getBranchPath(projectName); logger.info("Promoting branch {} to {}", taskPath, projectPath); merge(taskPath, projectPath); } private void merge(String sourcePath, String targetPath) throws RestClientException { try { JSONObject params = new JSONObject(); params.put("source", sourcePath); params.put("target", targetPath); resty.put(urlHelper.getMergesUrl(), params, SNOWOWL_CONTENT_TYPE); } catch (Exception e) { throw new RestClientException("Failed to merge " + sourcePath + " to " + targetPath, e); } } /** * Warning - this only works when the SnowOwl log is on the same machine. */ public InputStream getLogStream() throws FileNotFoundException { return new FileInputStream(logPath); } /** * Returns stream from rollover log or null. * @return * @throws FileNotFoundException */ public InputStream getRolloverLogStream() throws FileNotFoundException { if (new File(rolloverLogPath).isFile()) { return new FileInputStream(rolloverLogPath); } else { return null; } } private boolean waitForStatus(String url, Date timeoutDate, ProcessingStatus targetStatus, final String waitingFor) throws RestClientException, InterruptedException { String status = ""; boolean finalStateAchieved = false; while (!finalStateAchieved) { try { Object statusObj = resty.json(url).get("status"); status = statusObj.toString() ; } catch (Exception e) { throw new RestClientException("Rest client error while checking status of " + waitingFor + ".", e); } finalStateAchieved = !("RUNNING".equals(status) || "SCHEDULED".equals(status) || "SAVING_IN_PROGRESS".equals(status)); if (!finalStateAchieved && timeoutDate != null && new Date().after(timeoutDate)) { throw new RestClientException("Client timeout waiting for " + waitingFor + "."); } if (!finalStateAchieved) { Thread.sleep(1000 * 10); } } boolean targetStatusAchieved = targetStatus.toString().equals(status); if (!targetStatusAchieved) { logger.warn("TS reported non-complete status {} from URL {}", status, url); } return targetStatusAchieved; } private Date getTimeoutDate(int importTimeoutMinutes) { if (importTimeoutMinutes > 0) { GregorianCalendar timeoutCalendar = new GregorianCalendar(); timeoutCalendar.add(Calendar.MINUTE, importTimeoutMinutes); return timeoutCalendar.getTime(); } return null; } private String toPrettyJson(String jsonString) { JsonElement el = new JsonParser().parse(jsonString); return gson.toJson(el); } private void toPrettyJson(String jsonString, File outFile) throws IOException { JsonElement el = new JsonParser().parse(jsonString); try (JsonWriter writer = new JsonWriter(new FileWriter(outFile))) { gson.toJson(el, writer); } } public void setReasonerId(String reasonerId) { this.reasonerId = reasonerId; } public String getReasonerId() { return reasonerId; } public void setLogPath(String logPath) { this.logPath = logPath; } public void setRolloverLogPath(String rolloverLogPath) { this.rolloverLogPath = rolloverLogPath; } @Required public void setImportTimeoutMinutes(int importTimeoutMinutes) { this.importTimeoutMinutes = importTimeoutMinutes; } @Required public void setClassificationTimeoutMinutes(int classificationTimeoutMinutes) { this.classificationTimeoutMinutes = classificationTimeoutMinutes; } }
package org.jenkinsci.plugins.koji.xmlrpc; import org.apache.log4j.*; import org.apache.xmlrpc.XmlRpcException; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.List; import java.util.Map; public class XMLRPCTest { private KojiClient koji; private final String build = "classworlds-classworlds-1.1_alpha_2-1"; private final String pkg = "classworlds-classworlds"; private final String tag = "mead-import-maven-all"; public static void main(String[] args) { String kojiInstanceURL = "http://koji.localdomain/kojihub"; XMLRPCTest kojiTest = new XMLRPCTest(kojiInstanceURL); kojiTest.executeTests(); } public void executeTests() { testKojiHello(); testLogin(); KojiClient.BuildParams buildParams = new KojiClient.BuildParamsBuilder().setTag(tag).setPackage(pkg).setLatest(true).build(); koji.listTaggedBuilds(buildParams); // System.out.println(koji.getSession()); // testGetLatestBuilds(); // testGeBuildInfo(); private void testLogin() { Map<String, ?> session = null; try { session = koji.login(); } catch (XmlRpcException e) { e.printStackTrace(); } // printMap(session); // Integer sessionId = (Integer) session.get("session-id"); System.out.println(koji.getSession()); } public static void printMap(Map<String, String> map) { for (Map.Entry<String, String> m : map.entrySet()) { String key = m.getKey(); Object value = m.getValue(); System.out.println(key + ": " + value); } } private void testKojiHello() { String hello = koji.sayHello(); System.out.println(hello); } private void testListTaggedBuilds() { KojiClient.BuildParams buildParams = new KojiClient.BuildParamsBuilder().setTag(tag).setPackage(pkg).setLatest(true).build(); List<Map<String, String>> results = null; try { results = koji.listTaggedBuilds(buildParams); } catch (XmlRpcException e) { if (e.getMessage() == "empty") { System.out.println("No build with id=" + build + " found in the database."); return; } else e.printStackTrace(); } for (Map<String, String> map : results) { printMap(map); } } private void testGeBuildInfo() { Map<String, String> buildInfo = null; try { buildInfo = koji.getBuildInfo(build); } catch (XmlRpcException e) { if (e.getMessage() == "empty") { System.out.println("No build with id=" + build + " found in the database."); return; } else e.printStackTrace(); } printMap(buildInfo); } private void testGetLatestBuilds() { Map<String, String> result = null; try { result = koji.getLatestBuilds(tag, pkg); } catch (XmlRpcException e) { if (e.getMessage() == "empty") { System.out.println("No package " + pkg + " found for tag " + tag); return; } else { System.out.println(e.getMessage()); return; } } printMap(result); } public XMLRPCTest(String kojiInstanceURL) { this.koji = KojiClient.getKojiClient(kojiInstanceURL); koji.setDebug(true); initLogger(); } private void initLogger() { Logger logger = LogManager.getLogger(getClass()); BasicConfigurator.configure(); // basic log4j configuration Logger.getRootLogger().setLevel(Level.DEBUG); FileAppender fileAppender = null; try { fileAppender = new RollingFileAppender(new PatternLayout("%d{dd-MM-yyyy HH:mm:ss} %C %L %-5p:%m%n"),"file.log"); logger.addAppender(fileAppender); } catch (IOException e) { e.printStackTrace(); } logger.info("TEST LOG ENTRY"); } }
package org.jruby.rack; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * A pooling application factory that creates runtimes and manages a fixed- or * unlimited-size pool. * <p> * It has several context init parameters to control behavior: * <ul> * <li> jruby.min.runtimes: Initial number of runtimes to create and put in * the pool. Default is none. * <li> jruby.max.runtimes: Maximum size of the pool. Default is unlimited, in * which case new requests for an application object will create one if none * are available. * <li> jruby.runtime.timeout.sec: Value (in seconds) indicating when * a thread will timeout when no runtimes are available. Default is 30. * <li> jruby.runtime.initializer.threads: Number of threads to use at startup to * intialize and fill the pool. Default is 4. * </ul> * * @author nicksieger */ public class PoolingRackApplicationFactory implements RackApplicationFactory { static final int DEFAULT_TIMEOUT = 30; protected RackContext rackContext; private RackApplicationFactory realFactory; protected final Queue<RackApplication> applicationPool = new LinkedList<RackApplication>(); private Integer initial, maximum; private long timeout = DEFAULT_TIMEOUT; private Semaphore permits; public PoolingRackApplicationFactory(RackApplicationFactory factory) { realFactory = factory; } public void init(final RackContext rackContext) throws RackInitializationException { this.rackContext = rackContext; realFactory.init(rackContext); Integer specifiedTimeout = getPositiveInteger("jruby.runtime.timeout.sec"); if (specifiedTimeout != null) { timeout = specifiedTimeout.longValue(); } rackContext.log("Info: using runtime pool timeout of " + timeout + " seconds"); initial = getInitial(); maximum = getMaximum(); if (maximum != null) { if (initial != null && initial > maximum) { maximum = initial; } permits = new Semaphore(maximum, true); // does fairness matter? } if (initial != null) { fillInitialPool(); } } public RackApplication newApplication() throws RackInitializationException { return getApplication(); } public RackApplication getApplication() throws RackInitializationException { if (permits != null) { boolean acquired = false; try { acquired = permits.tryAcquire(timeout, TimeUnit.SECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } if (!acquired) { throw new RackInitializationException("timeout: all listeners busy", new InterruptedException()); } } synchronized (applicationPool) { if (!applicationPool.isEmpty()) { return applicationPool.remove(); } } return realFactory.getApplication(); } public void finishedWithApplication(RackApplication app) { synchronized (applicationPool) { if (maximum != null && applicationPool.size() >= maximum) { return; } if (applicationPool.contains(app)){ return; } applicationPool.add(app); if (permits != null) { permits.release(); } } } public RackApplication getErrorApplication() { return realFactory.getErrorApplication(); } public void destroy() { synchronized (applicationPool) { for (RackApplication app : applicationPool) { app.destroy(); } } } /** Used only by unit tests */ public Collection<RackApplication> getApplicationPool() { return Collections.unmodifiableCollection(applicationPool); } /** This creates the application objects in the foreground thread to avoid * leakage when the web application is undeployed from the application server. */ protected void fillInitialPool() throws RackInitializationException { Queue<RackApplication> apps = createApplications(); launchInitializerThreads(apps); synchronized (applicationPool) { if (applicationPool.isEmpty()) { waitForNextAvailable(DEFAULT_TIMEOUT * 1000); } } } protected void launchInitializerThreads(final Queue<RackApplication> apps) { Integer numThreads = getPositiveInteger("jruby.runtime.initializer.threads"); if (numThreads == null) { numThreads = 4; } for (int i = 0; i < numThreads; i++) { new Thread(new Runnable() { public void run() { try { while (true) { RackApplication app = null; synchronized (apps) { if (apps.isEmpty()) { break; } app = apps.remove(); } app.init(); synchronized (applicationPool) { if (maximum != null && applicationPool.size() >= maximum) { break; } applicationPool.add(app); rackContext.log("Info: add application to the pool. size now = " + applicationPool.size()); applicationPool.notifyAll(); } } } catch (RackInitializationException ex) { rackContext.log("Error: unable to initialize application", ex); } } }, "JRuby-Rack-App-Init-" + i).start(); } } protected Queue<RackApplication> createApplications() throws RackInitializationException { Queue<RackApplication> apps = new LinkedList<RackApplication>(); for (int i = 0; i < initial; i++) { apps.add(realFactory.newApplication()); } return apps; } /** Wait the specified time or until a runtime is available. */ public void waitForNextAvailable(long timeout) { try { synchronized (applicationPool) { applicationPool.wait(timeout); } } catch (InterruptedException ex) { } } private Integer getInitial() { return getRangeValue("min", "minIdle"); } private Integer getMaximum() { return getRangeValue("max", "maxActive"); } private Integer getRangeValue(String end, String gsValue) { Integer v = getPositiveInteger("jruby." + end + ".runtimes"); if (v == null) { v = getPositiveInteger("jruby.pool." + gsValue); } if (v == null) { rackContext.log("Warning: no " + end + " runtimes specified."); } else { rackContext.log("Info: received " + end + " runtimes = " + v); } return v; } private Integer getPositiveInteger(String string) { try { int i = Integer.parseInt(rackContext.getInitParameter(string)); if (i > 0) { return new Integer(i); } } catch (Exception e) { } return null; } }
package org.jtrfp.trcl.game; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.lang.ref.WeakReference; import org.jtrfp.trcl.core.Feature; import org.jtrfp.trcl.core.FeatureFactory; import org.jtrfp.trcl.core.Features; import org.jtrfp.trcl.core.TRFactory; import org.jtrfp.trcl.core.TRFactory.TR; import org.jtrfp.trcl.gui.LevelSkipWindow; import org.jtrfp.trcl.gui.MenuSystem; import org.jtrfp.trcl.shell.GameShellFactory.GameShell; import org.springframework.stereotype.Component; @Component public class LevelSkipMenuItemFactory implements FeatureFactory<TVF3Game> { private MenuSystem menuSystem; private LevelSkipWindow levelSkipWindow; protected static final String [] MENU_ITEM_PATH = new String [] {"Game","Skip To Level"}; @Override public Feature<TVF3Game> newInstance(TVF3Game target) { return new LevelSkipMenuItem(); } @Override public Class<TVF3Game> getTargetClass() { return TVF3Game.class; } @Override public Class<? extends Feature> getFeatureClass() { return LevelSkipMenuItem.class; } class LevelSkipMenuItem implements Feature<TVF3Game>{ private final MenuItemListener menuItemListener = new MenuItemListener(); private final RunStateListener runStateListener = new RunStateListener(); private final VoxListener voxListener = new VoxListener(); private WeakReference<Game> target; @Override public void apply(TVF3Game target) { this.target = new WeakReference<Game>(target); final MenuSystem menuSystem = getMenuSystem(); menuSystem.addMenuItem(MENU_ITEM_PATH); menuSystem.addMenuItemListener(menuItemListener, MENU_ITEM_PATH); final TR tr = target.getTr(); tr.addPropertyChangeListener (TRFactory.RUN_STATE, runStateListener); target.addPropertyChangeListener(TVF3Game.VOX , voxListener); this.getLevelSkipWindow();//This make sure the cache is set so that display() doesn't get stuck } @Override public void destruct(TVF3Game target) { target.getTr().removePropertyChangeListener(TRFactory.RUN_STATE,runStateListener); final MenuSystem menuSystem = getMenuSystem(); menuSystem.removeMenuItemListener(menuItemListener, MENU_ITEM_PATH); menuSystem.removeMenuItem(MENU_ITEM_PATH); target.removePropertyChangeListener(TVF3Game.VOX, voxListener); } private class MenuItemListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { //TODO: Use non-display() thread. getLevelSkipWindow().setVisible(true); } }//end MenuItemListener private class RunStateListener implements PropertyChangeListener{ @Override public void propertyChange(PropertyChangeEvent evt) { final MenuSystem menuSystem = getMenuSystem(); menuSystem.setMenuItemEnabled( evt.getNewValue() instanceof Game.GameLoadedMode, MENU_ITEM_PATH); }//end propertyChange(...) }//end RunStateListener private class VoxListener implements PropertyChangeListener{ @Override public void propertyChange(PropertyChangeEvent evt) { getLevelSkipWindow().setGame(target.get()); } }//end VoxListener public MenuSystem getMenuSystem() { final Frame frame = ((TVF3Game)(target.get())).getTr().getRootWindow(); return Features.get(frame, MenuSystem.class); } private LevelSkipWindow getLevelSkipWindow(){ if(levelSkipWindow==null){ final TVF3Game game = ((TVF3Game)(target.get())); final TR tr = game.getTr(); final LevelSkipWindow levelSkipWindow = new LevelSkipWindow(game.getTr()); final GameShell gameShell = Features.get(tr,GameShell.class); assert gameShell != null; levelSkipWindow.setGameShell(gameShell); LevelSkipMenuItemFactory.this.levelSkipWindow = levelSkipWindow; } return levelSkipWindow; }//end getLevelSkipWindow() }//end LevelSkipMenuItem }//end LevelSkipMenuItemFactory
package org.junit.experimental.categories; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Set; import java.util.Collections; import java.util.HashSet; import org.junit.runner.Description; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runners.Suite; import org.junit.runners.model.InitializationError; import org.junit.runners.model.RunnerBuilder; public class Categories extends Suite { // the way filters are implemented makes this unnecessarily complicated, // buggy, and difficult to specify. A new way of handling filters could // someday enable a better new implementation. @Retention(RetentionPolicy.RUNTIME) public @interface IncludeCategory { /** * Determines the tests to run that are annotated with categories specified in * the value of this annotation or their subtypes unless excluded with {@link ExcludeCategory}. */ public Class<?>[] value() default {}; /** * If <tt>true</tt>, runs tests annotated with <em>any</em> of the categories in * {@link IncludeCategory#value()}. Otherwise, runs tests only if annotated with <em>all</em> of the categories. */ public boolean matchAny() default true; } @Retention(RetentionPolicy.RUNTIME) public @interface ExcludeCategory { /** * Determines the tests which do not run if they are annotated with categories specified in the * value of this annotation or their subtypes regardless of being included in {@link IncludeCategory#value()}. */ public Class<?>[] value() default {}; /** * If <tt>true</tt>, the tests annotated with <em>any</em> of the categories in {@link ExcludeCategory#value()} * do not run. Otherwise, the tests do not run if and only if annotated with <em>all</em> categories. */ public boolean matchAny() default true; } public static class CategoryFilter extends Filter { private final Set<Class<?>> fIncluded; private final Set<Class<?>> fExcluded; private final boolean fIncludedAny; private final boolean fExcludedAny; public static CategoryFilter include(boolean matchAny, Class<?>... categories) { if (hasNull(categories)) { throw new NullPointerException("has null category"); } return categoryFilter(matchAny, createSet(categories), true, null); } public static CategoryFilter include(Class<?> category) { return include(true, category); } public static CategoryFilter include(Class<?>... categories) { return include(true, categories); } public static CategoryFilter exclude(boolean matchAny, Class<?>... categories) { if (hasNull(categories)) { throw new NullPointerException("has null category"); } return categoryFilter(true, null, matchAny, createSet(categories)); } public static CategoryFilter exclude(Class<?> category) { return exclude(true, category); } public static CategoryFilter exclude(Class<?>... categories) { return exclude(true, categories); } public static CategoryFilter categoryFilter(boolean matchAnyInclusions, Set<Class<?>> inclusions, boolean matchAnyExclusions, Set<Class<?>> exclusions) { return new CategoryFilter(matchAnyInclusions, inclusions, matchAnyExclusions, exclusions); } private CategoryFilter(boolean matchAnyIncludes, Set<Class<?>> includes, boolean matchAnyExcludes, Set<Class<?>> excludes) { fIncludedAny= matchAnyIncludes; fExcludedAny= matchAnyExcludes; fIncluded= copyAndRefine(includes); fExcluded= copyAndRefine(excludes); } /** * @see #toString() */ @Override public String describe() { return toString(); } /** * Returns string in the form <tt>&quot;[included categories] - [excluded categories]&quot;</tt>, where both * sets have comma separated names of categories. * * @return string representation for the relative complement of excluded categories set * in the set of included categories. Examples: * <ul> * <li> <tt>&quot;categories [all]&quot;</tt> for all included categories and no excluded ones; * <li> <tt>&quot;categories [all] - [A, B]&quot;</tt> for all included categories and given excluded ones; * <li> <tt>&quot;categories [A, B] - [C, D]&quot;</tt> for given included categories and given excluded ones. * </ul> * @see Class#toString() name of category */ @Override public String toString() { StringBuilder description= new StringBuilder("categories ") .append(fIncluded.isEmpty() ? "[all]" : fIncluded); if (!fExcluded.isEmpty()) { description.append(" - ").append(fExcluded); } return description.toString(); } @Override public boolean shouldRun(Description description) { if (hasCorrectCategoryAnnotation(description)) { return true; } for (Description each : description.getChildren()) { if (shouldRun(each)) { return true; } } return false; } private boolean hasCorrectCategoryAnnotation(Description description) { final Set<Class<?>> childCategories= categories(description); // If a child has no categories, immediately return. if (childCategories.isEmpty()) { return fIncluded.isEmpty(); } if (!fExcluded.isEmpty()) { if (fExcludedAny) { if (matchesAnyParentCategories(childCategories, fExcluded)) { return false; } } else { if (matchesAllParentCategories(childCategories, fExcluded)) { return false; } } } if (fIncluded.isEmpty()) { // Couldn't be excluded, and with no suite's included categories treated as should run. return true; } else { if (fIncludedAny) { return matchesAnyParentCategories(childCategories, fIncluded); } else { return matchesAllParentCategories(childCategories, fIncluded); } } return false; } /** * @return <tt>true</tt> if at least one (any) parent category match a child, otherwise <tt>false</tt>. * If empty <tt>parentCategories</tt>, returns <tt>false</tt>. */ private boolean matchesAnyParentCategories(Set<Class<?>> childCategories, Set<Class<?>> parentCategories) { for (Class<?> parentCategory : parentCategories) { if (hasAssignableTo(childCategories, parentCategory)) { return true; } } return false; } /** * @return <tt>false</tt> if at least one parent category does not match children, otherwise <tt>true</tt>. * If empty <tt>parentCategories</tt>, returns <tt>true</tt>. */ private boolean matchesAllParentCategories(Set<Class<?>> childCategories, Set<Class<?>> parentCategories) { for (Class<?> parentCategory : parentCategories) { if (!hasAssignableTo(childCategories, parentCategory)) { return false; } } return true; } private static Set<Class<?>> categories(Description description) { Set<Class<?>> categories= new HashSet<Class<?>>(); Collections.addAll(categories, directCategories(description)); Collections.addAll(categories, directCategories(parentDescription(description))); return categories; } private static Description parentDescription(Description description) { Class<?> testClass= description.getTestClass(); return testClass == null ? null : Description.createSuiteDescription(testClass); } private static Class<?>[] directCategories(Description description) { if (description == null) { return new Class<?>[0]; } Category annotation= description.getAnnotation(Category.class); return annotation == null ? new Class<?>[0] : annotation.value(); } private static Set<Class<?>> copyAndRefine(Set<Class<?>> classes) { HashSet<Class<?>> c= new HashSet<Class<?>>(); if (classes != null) { c.addAll(classes); } c.remove(null); return c; } private static boolean hasNull(Class<?>... classes) { if (classes == null) return false; for (Class<?> clazz : classes) { if (clazz == null) { return true; } } return false; } } public Categories(Class<?> klass, RunnerBuilder builder) throws InitializationError { super(klass, builder); try { Set<Class<?>> included= getIncludedCategory(klass); Set<Class<?>> excluded= getExcludedCategory(klass); boolean isAnyIncluded= isAnyIncluded(klass); boolean isAnyExcluded= isAnyExcluded(klass); filter(CategoryFilter.categoryFilter(isAnyIncluded, included, isAnyExcluded, excluded)); } catch (NoTestsRemainException e) { throw new InitializationError(e); } catch (ClassNotFoundException e) { throw new InitializationError(e); } assertNoCategorizedDescendentsOfUncategorizeableParents(getDescription()); } private static Set<Class<?>> getIncludedCategory(Class<?> klass) throws ClassNotFoundException { IncludeCategory annotation= klass.getAnnotation(IncludeCategory.class); return createSet(annotation == null ? null : annotation.value()); } private static boolean isAnyIncluded(Class<?> klass) { IncludeCategory annotation= klass.getAnnotation(IncludeCategory.class); return annotation == null || annotation.matchAny(); } private static Set<Class<?>> getExcludedCategory(Class<?> klass) throws ClassNotFoundException { ExcludeCategory annotation= klass.getAnnotation(ExcludeCategory.class); return createSet(annotation == null ? null : annotation.value()); } private static boolean isAnyExcluded(Class<?> klass) { ExcludeCategory annotation= klass.getAnnotation(ExcludeCategory.class); return annotation == null || annotation.matchAny(); } private static void assertNoCategorizedDescendentsOfUncategorizeableParents(Description description) throws InitializationError { if (!canHaveCategorizedChildren(description)) { assertNoDescendantsHaveCategoryAnnotations(description); } for (Description each : description.getChildren()) { assertNoCategorizedDescendentsOfUncategorizeableParents(each); } } private static void assertNoDescendantsHaveCategoryAnnotations(Description description) throws InitializationError { for (Description each : description.getChildren()) { if (each.getAnnotation(Category.class) != null) { throw new InitializationError("Category annotations on Parameterized classes are not supported on individual methods."); } assertNoDescendantsHaveCategoryAnnotations(each); } } // If children have names like [0], our current magical category code can't determine their parentage. private static boolean canHaveCategorizedChildren(Description description) { for (Description each : description.getChildren()) { if (each.getTestClass() == null) { return false; } } return true; } private static boolean hasAssignableTo(Set<Class<?>> assigns, Class<?> to) { for (final Class<?> from : assigns) { if (to.isAssignableFrom(from)) { return true; } } return false; } private static Set<Class<?>> createSet(Class<?>... t) { final Set<Class<?>> set= new HashSet<Class<?>>(); if (t != null) { Collections.addAll(set, t); } return set; } }
package org.openlmis.referencedata.web.fhir; import static org.openlmis.referencedata.web.fhir.Coding.AREA; import static org.openlmis.referencedata.web.fhir.Coding.SITE; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.common.collect.ImmutableList; import com.vividsolutions.jts.geom.Point; import lombok.Getter; import org.openlmis.referencedata.domain.Facility; import org.openlmis.referencedata.domain.FacilityOperator; import org.openlmis.referencedata.domain.GeographicZone; import org.openlmis.referencedata.domain.SupportedProgram; import org.openlmis.referencedata.web.FacilityOperatorController; import org.openlmis.referencedata.web.FacilityTypeController; import org.openlmis.referencedata.web.GeographicLevelController; import org.openlmis.referencedata.web.GeographicZoneController; import org.openlmis.referencedata.web.ProgramController; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; @Getter @JsonInclude(JsonInclude.Include.NON_NULL) public final class Location extends Resource { private static final String LOCATION = "Location"; private final List<String> alias; private final List<Identifier> identifier; private final String name; private final Position position; private final PhysicalType physicalType; private final Reference partOf; private final String description; private final String status; /** * Creates new instance of Location based on data from {@link GeographicZone}. */ Location(String serviceUrl, GeographicZone zone) { this(zone.getId(), ImmutableList.of(zone.getCode()), getIdentifier(serviceUrl, zone), zone.getName(), new Position(zone.getLongitude(), zone.getLatitude()), new PhysicalType(AREA), getGeographicZoneAsReference(serviceUrl, zone.getParent()), null, null); } /** * Creates new instance of Location based on data from {@link Facility}. */ Location(String serviceUrl, Facility facility) { this(facility.getId(), ImmutableList.of(facility.getCode()), getIdentifier(serviceUrl, facility), facility.getName(), getPosition(facility.getLocation()), new PhysicalType(SITE), getGeographicZoneAsReference(serviceUrl, facility.getGeographicZone()), facility.getDescription(), getStatus(facility)); } private Location(UUID id, List<String> alias, List<Identifier> identifier, String name, Position position, PhysicalType physicalType, Reference partOf, String description, String status) { super(id, LOCATION); this.alias = alias; this.identifier = identifier; this.name = name; this.position = position; this.physicalType = physicalType; this.partOf = partOf; this.description = description; this.status = status; } private static List<Identifier> getIdentifier(String serviceUrl, GeographicZone zone) { return ImmutableList.of( new Identifier( serviceUrl, GeographicLevelController.RESOURCE_PATH, zone.getLevel().getId())); } private static List<Identifier> getIdentifier(String serviceUrl, Facility facility) { Set<SupportedProgram> supportedPrograms = facility.getSupportedPrograms(); List<Identifier> identifier; if (supportedPrograms != null) { identifier = new ArrayList<>(supportedPrograms.size() + 2); supportedPrograms.forEach(sp -> identifier.add(new Identifier( serviceUrl, ProgramController.RESOURCE_PATH, sp.getProgram().getId()))); } else { identifier = new ArrayList<>(2); } identifier.add(new Identifier( serviceUrl, FacilityTypeController.RESOURCE_PATH, facility.getType().getId())); FacilityOperator operator = facility.getOperator(); if (operator != null) { identifier.add(new Identifier( serviceUrl, FacilityOperatorController.RESOURCE_PATH, operator.getId())); } return identifier; } private static Reference getGeographicZoneAsReference(String serviceUrl, GeographicZone zone) { return zone != null ? new Reference(serviceUrl, GeographicZoneController.RESOURCE_PATH, zone.getId()) : null; } private static Position getPosition(Point location) { return location != null ? new Position(location.getX(), location.getY()) : null; } private static String getStatus(Facility facility) { return facility.getActive() ? Status.ACTIVE.toString() : Status.INACTIVE.toString(); } }
package org.roaringbitmap.buffer; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.util.Arrays; /** * Specialized array to store the containers used by a RoaringBitmap. This class * is similar to org.roaringbitmap.RoaringArray but meant to be used with memory * mapping. This is not meant to be used by end users. * * Objects of this class reside in RAM. */ public final class MutableRoaringArray implements Cloneable, Externalizable, PointableRoaringArray { protected static final class Element implements Cloneable, Comparable<Element> { final short key; MappeableContainer value; public Element(short key, MappeableContainer value) { this.key = key; this.value = value; } @Override public Element clone() throws CloneNotSupportedException { Element c = (Element) super.clone(); // key copied by clone c.value = this.value.clone(); return c; } @Override public int compareTo(Element o) { return BufferUtil.toIntUnsigned(this.key) - BufferUtil.toIntUnsigned(o.key); } @Override public boolean equals(Object o) { if (o instanceof Element) { Element e = (Element) o; return (e.key == key) && e.value.equals(value); } return false; } @Override public int hashCode() { return key * 0xF0F0F0 + value.hashCode(); } } protected static final int INITIAL_CAPACITY = 4; protected static final short SERIAL_COOKIE = 12345; private static final long serialVersionUID = 4L; Element[] array = null; int size = 0; protected MutableRoaringArray() { this.array = new Element[INITIAL_CAPACITY]; } /** * Create a roaring array based on a previously serialized ByteBuffer. As * much as possible, the ByteBuffer is used as the backend, however if you * modify the content, the result is unspecified. * * @param bb * The source ByteBuffer */ protected MutableRoaringArray(ByteBuffer bb) { bb.order(ByteOrder.LITTLE_ENDIAN); if (bb.getInt() != SERIAL_COOKIE) throw new RuntimeException("I failed to find the right cookie."); this.size = bb.getInt(); // we fully read the meta-data array to RAM, but the containers // themselves are memory-mapped this.array = new Element[this.size]; final short keys[] = new short[this.size]; final int cardinalities[] = new int[this.size]; final boolean isBitmap[] = new boolean[this.size]; for (int k = 0; k < this.size; ++k) { keys[k] = bb.getShort(); cardinalities[k] = BufferUtil.toIntUnsigned(bb.getShort()) + 1; isBitmap[k] = cardinalities[k] > MappeableArrayContainer.DEFAULT_MAX_SIZE; } for (int k = 0; k < this.size; ++k) { if (cardinalities[k] == 0) throw new RuntimeException("no"); MappeableContainer val; if (isBitmap[k]) { final LongBuffer bitmapArray = bb.asLongBuffer().slice(); bitmapArray.limit(MappeableBitmapContainer.MAX_CAPACITY / 64); bb.position(bb.position() + MappeableBitmapContainer.MAX_CAPACITY / 8); val = new MappeableBitmapContainer(bitmapArray, cardinalities[k]); } else { final ShortBuffer shortArray = bb.asShortBuffer().slice(); shortArray.limit(cardinalities[k]); bb.position(bb.position() + cardinalities[k] * 2); val = new MappeableArrayContainer(shortArray, cardinalities[k]); } this.array[k] = new Element(keys[k], val); } } protected void append(short key, MappeableContainer value) { extendArray(1); this.array[this.size++] = new Element(key, value); } /** * Append copies of the values AFTER a specified key (may or may not be * present) to end. * * @param highLowContainer * the other array * @param beforeStart * given key is the largest key that we won't copy */ protected void appendCopiesAfter(PointableRoaringArray highLowContainer, short beforeStart) { int startLocation = highLowContainer.getIndex(beforeStart); if (startLocation >= 0) startLocation++; else startLocation = -startLocation - 1; extendArray(highLowContainer.size() - startLocation); for (int i = startLocation; i < highLowContainer.size(); ++i) { this.array[this.size++] = new Element( highLowContainer.getKeyAtIndex(i), highLowContainer .getContainerAtIndex(i).clone()); } } /** * Append copies of the values from another array, from the start * * @param highLowContainer * the other array * @param stoppingKey * any equal or larger key in other array will terminate copying */ protected void appendCopiesUntil(PointableRoaringArray highLowContainer, short stoppingKey) { final int stopKey = BufferUtil.toIntUnsigned(stoppingKey); MappeableContainerPointer cp = highLowContainer.getContainerPointer(); while (cp.hasContainer()) { if (BufferUtil.toIntUnsigned(cp.key()) >= stopKey) break; extendArray(1); this.array[this.size++] = new Element(cp.key(), cp.getContainer() .clone()); cp.advance(); } } /** * Append copies of the values from another array * * @param highLowContainer * other array * @param startingIndex * starting index in the other array * @param end * last index array in the other array */ protected void appendCopy(PointableRoaringArray highLowContainer, int startingIndex, int end) { extendArray(end - startingIndex); for (int i = startingIndex; i < end; ++i) { this.array[this.size++] = new Element( highLowContainer.getKeyAtIndex(i), highLowContainer .getContainerAtIndex(i).clone()); } } protected void appendCopy(short key, MappeableContainer value) { extendArray(1); this.array[this.size++] = new Element(key, value.clone()); } private int binarySearch(int begin, int end, short key) { int low = begin; int high = end - 1; final int ikey = BufferUtil.toIntUnsigned(key); while (low <= high) { final int middleIndex = (low + high) >>> 1; final int middleValue = BufferUtil .toIntUnsigned(array[middleIndex].key); if (middleValue < ikey) low = middleIndex + 1; else if (middleValue > ikey) high = middleIndex - 1; else return middleIndex; } return -(low + 1); } protected void clear() { this.array = null; this.size = 0; } @Override public MutableRoaringArray clone() { MutableRoaringArray sa; try { sa = (MutableRoaringArray) super.clone(); sa.array = Arrays.copyOf(this.array, this.size); for (int k = 0; k < this.size; ++k) sa.array[k] = sa.array[k].clone(); sa.size = this.size; return sa; } catch (CloneNotSupportedException e) { return null; } } /** * Deserialize. * * @param in * the DataInput stream * @throws IOException * Signals that an I/O exception has occurred. */ public void deserialize(DataInput in) throws IOException { this.clear(); final byte[] buffer4 = new byte[4]; final byte[] buffer = new byte[2]; // little endian in.readFully(buffer4); final int cookie = (buffer4[0] & 0xFF) | ((buffer4[1] & 0xFF) << 8) | ((buffer4[2] & 0xFF) << 16) | ((buffer4[3] & 0xFF) << 24); if (cookie != SERIAL_COOKIE) throw new IOException("I failed to find the right cookie."); in.readFully(buffer4); this.size = (buffer4[0] & 0xFF) | ((buffer4[1] & 0xFF) << 8) | ((buffer4[2] & 0xFF) << 16) | ((buffer4[3] & 0xFF) << 24); if ((this.array == null) || (this.array.length < this.size)) this.array = new Element[this.size]; final short keys[] = new short[this.size]; final int cardinalities[] = new int[this.size]; final boolean isBitmap[] = new boolean[this.size]; for (int k = 0; k < this.size; ++k) { in.readFully(buffer); keys[k] = (short) (buffer[0] & 0xFF | ((buffer[1] & 0xFF) << 8)); in.readFully(buffer); cardinalities[k] = 1 + (buffer[0] & 0xFF | ((buffer[1] & 0xFF) << 8)); isBitmap[k] = cardinalities[k] > MappeableArrayContainer.DEFAULT_MAX_SIZE; } for (int k = 0; k < this.size; ++k) { MappeableContainer val; if (isBitmap[k]) { final LongBuffer bitmapArray = LongBuffer .allocate(MappeableBitmapContainer.MAX_CAPACITY / 64); final byte[] buf = new byte[8]; // little endian for (int l = 0; l < bitmapArray.limit(); ++l) { in.readFully(buf); bitmapArray.put(l, (((long) buf[7] << 56) + ((long) (buf[6] & 255) << 48) + ((long) (buf[5] & 255) << 40) + ((long) (buf[4] & 255) << 32) + ((long) (buf[3] & 255) << 24) + ((buf[2] & 255) << 16) + ((buf[1] & 255) << 8) + (buf[0] & 255))); } val = new MappeableBitmapContainer(bitmapArray, cardinalities[k]); } else { final ShortBuffer shortArray = ShortBuffer .allocate(cardinalities[k]); for (int l = 0; l < shortArray.limit(); ++l) { in.readFully(buffer); shortArray .put(l, (short) (buffer[0] & 0xFF | ((buffer[1] & 0xFF) << 8))); } val = new MappeableArrayContainer(shortArray, cardinalities[k]); } this.array[k] = new Element(keys[k], val); } } @Override public boolean equals(Object o) { if (o instanceof MutableRoaringArray) { final MutableRoaringArray srb = (MutableRoaringArray) o; if (srb.size != this.size) return false; for (int i = 0; i < srb.size; ++i) { Element self = this.array[i]; Element other = srb.array[i]; if (self.key != other.key || !self.value.equals(other.value)) return false; } return true; } if (o instanceof ImmutableRoaringArray) { final ImmutableRoaringArray srb = (ImmutableRoaringArray) o; MappeableContainerPointer cp1 = srb.getContainerPointer(); MappeableContainerPointer cp2 = srb.getContainerPointer(); while (cp1.hasContainer()) { if (!cp2.hasContainer()) return false; if (cp1.key() != cp2.key()) return false; if (cp1.getCardinality() != cp2.getCardinality()) return false; if (!cp1.getContainer().equals(cp2.getContainer())) return false; } if (cp2.hasContainer()) return false; return true; } return false; } // make sure there is capacity for at least k more elements protected void extendArray(int k) { // size + 1 could overflow if (this.size + k >= this.array.length) { int newCapacity; if (this.array.length < 1024) { newCapacity = 2 * (this.size + k); } else { newCapacity = 5 * (this.size + k) / 4; } this.array = Arrays.copyOf(this.array, newCapacity); } } // involves a binary search public MappeableContainer getContainer(short x) { final int i = this.binarySearch(0, size, x); if (i < 0) return null; return this.array[i].value; } public MappeableContainer getContainerAtIndex(int i) { return this.array[i].value; } public MappeableContainerPointer getContainerPointer() { return new MappeableContainerPointer() { int k = 0; @Override public void advance() { ++k; } @Override public int compareTo(MappeableContainerPointer o) { if (key() != o.key()) return BufferUtil.toIntUnsigned(key()) - BufferUtil.toIntUnsigned(o.key()); return o.getCardinality() - getCardinality(); } @Override public int getCardinality() { return getContainer().getCardinality(); } @Override public MappeableContainer getContainer() { if (k >= MutableRoaringArray.this.size) return null; return MutableRoaringArray.this.array[k].value; } @Override public boolean hasContainer() { return k < MutableRoaringArray.this.size; } @Override public short key() { return MutableRoaringArray.this.array[k].key; } @Override public MappeableContainerPointer clone() { try { return (MappeableContainerPointer) super.clone(); } catch (CloneNotSupportedException e) { return null;// will not happen } } }; } // involves a binary search public int getIndex(short x) { // before the binary search, we optimize for frequent cases if ((size == 0) || (array[size - 1].key == x)) return size - 1; // no luck we have to go through the list return this.binarySearch(0, size, x); } public short getKeyAtIndex(int i) { return this.array[i].key; } @Override public int hashCode() { int hashvalue = 0; for (int k = 0; k < this.size; ++k) hashvalue = 31 * hashvalue + array[k].hashCode(); return hashvalue; } // insert a new key, it is assumed that it does not exist protected void insertNewKeyValueAt(int i, short key, MappeableContainer value) { extendArray(1); System.arraycopy(array, i, array, i + 1, size - i); array[i] = new Element(key, value); size++; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { deserialize(in); } protected void removeAtIndex(int i) { System.arraycopy(array, i + 1, array, i, size - i - 1); array[size - 1] = null; size } protected void resize(int newLength) { for (int k = newLength; k < this.size; ++k) { this.array[k] = null; } this.size = newLength; } /** * Serialize. * * The current bitmap is not modified. * * @param out * the DataOutput stream * @throws IOException * Signals that an I/O exception has occurred. */ public void serialize(DataOutput out) throws IOException { out.write(SERIAL_COOKIE & 0xFF); out.write((SERIAL_COOKIE >>> 8) & 0xFF); out.write((SERIAL_COOKIE >>> 16) & 0xFF); out.write((SERIAL_COOKIE >>> 24) & 0xFF); out.write(this.size & 0xFF); out.write((this.size >>> 8) & 0xFF); out.write((this.size >>> 16) & 0xFF); out.write((this.size >>> 24) & 0xFF); for (int k = 0; k < size; ++k) { out.write(this.array[k].key & 0xFF); out.write((this.array[k].key >>> 8) & 0xFF); out.write((this.array[k].value.getCardinality() - 1) & 0xFF); out.write(((this.array[k].value.getCardinality() - 1) >>> 8) & 0xFF); } //writing the containers offsets int startOffset = 4 + 4 + (1 << (2 << this.size)); for(int k=0; k<this.size; k++){ out.write(startOffset); startOffset=startOffset+BufferUtil.getSizeInBytesFromCardinality(this.array[k].value.getCardinality()); } for (int k = 0; k < size; ++k) { array[k].value.writeArray(out); } } /** * Report the number of bytes required for serialization. * * @return the size in bytes */ public int serializedSizeInBytes() { int count = 4 + 4 + 1 << (2 << size); for (int k = 0; k < size; ++k) { count += array[k].value.getArraySizeInBytes(); } return count; } protected void setContainerAtIndex(int i, MappeableContainer c) { this.array[i].value = c; } public int size() { return this.size; } @Override public void writeExternal(ObjectOutput out) throws IOException { serialize(out); } }
package org.spongepowered.api.world.biome; import org.spongepowered.api.Sponge; import java.util.function.Supplier; /** * An enumeration of all possible {@link BiomeType}s available in vanilla * minecraft. */ public final class BiomeTypes { // Standard Biomes // SORTFIELDS:ON public static final Supplier<BiomeType> BADLANDS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "badlands"); public static final Supplier<BiomeType> BADLANDS_PLATEAU = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "badlands_plateau"); public static final Supplier<BiomeType> BAMBOO_JUNGLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "bamboo_jungle"); public static final Supplier<BiomeType> BAMBOO_JUNGLE_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "bamboo_jungle_hills"); public static final Supplier<BiomeType> BEACH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "beach"); public static final Supplier<BiomeType> BIRCH_FOREST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "birch_forest"); public static final Supplier<BiomeType> BIRCH_FOREST_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "birch_forest_hills"); public static final Supplier<BiomeType> COLD_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "cold_ocean"); public static final Supplier<BiomeType> DARK_FOREST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "dark_forest"); public static final Supplier<BiomeType> DARK_FOREST_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "dark_forest_hills"); public static final Supplier<BiomeType> DEEP_COLD_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "deep_cold_ocean"); public static final Supplier<BiomeType> DEEP_FROZEN_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "deep_frozen_ocean"); public static final Supplier<BiomeType> DEEP_LUKEWARM_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "deep_lukewarm_ocean"); public static final Supplier<BiomeType> DEEP_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "deep_ocean"); public static final Supplier<BiomeType> DEEP_WARM_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "deep_warm_ocean"); public static final Supplier<BiomeType> DESERT = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "desert"); public static final Supplier<BiomeType> DESERT_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "desert_hills"); public static final Supplier<BiomeType> DESERT_LAKES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "desert_lakes"); public static final Supplier<BiomeType> END_BARRENS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "end_barrens"); public static final Supplier<BiomeType> END_HIGHLANDS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "end_highlands"); public static final Supplier<BiomeType> END_MIDLANDS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "end_midlands"); public static final Supplier<BiomeType> ERODED_BADLANDS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "eroded_badlands"); public static final Supplier<BiomeType> FLOWER_FOREST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "flower_forest"); public static final Supplier<BiomeType> FOREST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "forest"); public static final Supplier<BiomeType> FROZEN_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "frozen_ocean"); public static final Supplier<BiomeType> FROZEN_RIVER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "frozen_river"); public static final Supplier<BiomeType> GIANT_SPRUCE_TAIGA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "giant_spruce_taiga"); public static final Supplier<BiomeType> GIANT_SPRUCE_TAIGA_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "giant_spruce_taiga_hills"); public static final Supplier<BiomeType> GIANT_TREE_TAIGA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "giant_tree_taiga"); public static final Supplier<BiomeType> GIANT_TREE_TAIGA_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "giant_tree_taiga_hills"); public static final Supplier<BiomeType> GRAVELLY_MOUNTAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "gravelly_mountains"); public static final Supplier<BiomeType> ICE_SPIKES = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "ice_spikes"); public static final Supplier<BiomeType> JUNGLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "jungle"); public static final Supplier<BiomeType> JUNGLE_EDGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "jungle_edge"); public static final Supplier<BiomeType> JUNGLE_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "jungle_hills"); public static final Supplier<BiomeType> LUKEWARM_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "lukewarm_ocean"); public static final Supplier<BiomeType> MODIFIED_BADLANDS_PLATEAU = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "modified_badlands_plateau"); public static final Supplier<BiomeType> MODIFIED_GRAVELLY_MOUNTAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "modified_gravelly_mountains"); public static final Supplier<BiomeType> MODIFIED_JUNGLE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "modified_jungle"); public static final Supplier<BiomeType> MODIFIED_JUNGLE_EDGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "modified_jungle_edge"); public static final Supplier<BiomeType> MODIFIED_WOODED_BADLANDS_PLATEAU = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "modified_wooded_badlands_plateau"); public static final Supplier<BiomeType> MOUNTAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "mountains"); public static final Supplier<BiomeType> MOUNTAIN_EDGE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "mountain_edge"); public static final Supplier<BiomeType> MUSHROOM_FIELDS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "mushroom_fields"); public static final Supplier<BiomeType> MUSHROOM_FIELD_SHORE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "mushroom_field_shore"); public static final Supplier<BiomeType> NETHER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "nether"); public static final Supplier<BiomeType> OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "ocean"); public static final Supplier<BiomeType> PLAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "plains"); public static final Supplier<BiomeType> RIVER = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "river"); public static final Supplier<BiomeType> SAVANNA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "savanna"); public static final Supplier<BiomeType> SAVANNA_PLATEAU = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "savanna_plateau"); public static final Supplier<BiomeType> SHATTERED_SAVANNA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "shattered_savanna"); public static final Supplier<BiomeType> SHATTERED_SAVANNA_PLATEAU = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "shattered_savanna_plateau"); public static final Supplier<BiomeType> SMALL_END_ISLANDS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "small_end_islands"); public static final Supplier<BiomeType> SNOWY_BEACH = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "snowy_beach"); public static final Supplier<BiomeType> SNOWY_MOUNTAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "snowy_mountains"); public static final Supplier<BiomeType> SNOWY_TAIGA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "snowy_taiga"); public static final Supplier<BiomeType> SNOWY_TAIGA_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "snowy_taiga_hills"); public static final Supplier<BiomeType> SNOWY_TAIGA_MOUNTAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "snowy_taiga_mountains"); public static final Supplier<BiomeType> SNOWY_TUNDRA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "snowy_tundra"); public static final Supplier<BiomeType> STONE_SHORE = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "stone_shore"); public static final Supplier<BiomeType> SUNFLOWER_PLAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "sunflower_plains"); public static final Supplier<BiomeType> SWAMP = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "swamp"); public static final Supplier<BiomeType> SWAMP_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "swamp_hills"); public static final Supplier<BiomeType> TAIGA = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "taiga"); public static final Supplier<BiomeType> TAIGA_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "taiga_hills"); public static final Supplier<BiomeType> TAIGA_MOUNTAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "taiga_mountains"); public static final Supplier<BiomeType> TALL_BIRCH_FOREST = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "tall_birch_forest"); public static final Supplier<BiomeType> TALL_BIRCH_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "tall_birch_hills"); public static final Supplier<BiomeType> THE_END = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "the_end"); public static final Supplier<BiomeType> THE_VOID = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "the_void"); public static final Supplier<BiomeType> WARM_OCEAN = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "warm_ocean"); public static final Supplier<BiomeType> WOODED_BADLANDS_PLATEAU = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "wooded_badlands_plateau"); public static final Supplier<BiomeType> WOODED_HILLS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "wooded_hills"); public static final Supplier<BiomeType> WOODED_MOUNTAINS = Sponge.getRegistry().getCatalogRegistry().provideSupplier(BiomeType.class, "wooded_mountains"); // SORTFIELDS:OFF // Suppress default constructor to ensure non-instantiability. private BiomeTypes() { throw new AssertionError("You should not be attempting to instantiate this class."); } }
package org.synyx.urlaubsverwaltung.mail; import org.synyx.urlaubsverwaltung.person.MailNotification; import org.synyx.urlaubsverwaltung.person.Person; import java.util.List; import java.util.Map; /** * This service provides sending notification emails. */ public interface MailService { /** * Sends a mail to a person * * @param person to get this email * @param subjectMessageKey message key of the subject * @param templateName name of template * @param model additional information based on the template */ void sendMailTo(Person person, String subjectMessageKey, String templateName, Map<String, Object> model); /** * Sends a mail to a each person separately * * @param persons to get this email each * @param subjectMessageKey message key of the subject * @param templateName name of template * @param model additional information based on the template * @param args additional information for subjectMessageKey */ void sendMailToEach(List<Person> persons, String subjectMessageKey, String templateName, Map<String, Object> model, Object... args); /** * Sends a mail defined by mail notification groups * * @param mailNotification group of people to get this email * @param subjectMessageKey message key of the subject * @param templateName name of template * @param model additional information based on the template */ void sendMailTo(MailNotification mailNotification, String subjectMessageKey, String templateName, Map<String, Object> model); /** * Sends a technical mail to the defined administrator in the {@link org.synyx.urlaubsverwaltung.settings.MailSettings} * * @param subjectMessageKey message key of the subject * @param templateName name of template * @param model additional information based on the template */ void sendTechnicalMail(String subjectMessageKey, String templateName, Map<String, Object> model); }
package org.zalando.nakadi.domain; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.concurrent.Immutable; import javax.validation.constraints.NotNull; @Immutable public class SubscriptionCursor extends Cursor { @NotNull private final String eventType; @NotNull private final String cursorToken; public SubscriptionCursor(@JsonProperty("partition") final String partition, @JsonProperty("offset") final String offset, @JsonProperty("event_type") final String eventType, @JsonProperty("cursor_token") final String cursorToken) { super(partition, offset); this.eventType = eventType; this.cursorToken = cursorToken; } public String getEventType() { return eventType; } public String getCursorToken() { return cursorToken; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; final SubscriptionCursor that = (SubscriptionCursor) o; return eventType.equals(that.eventType) && cursorToken.equals(that.cursorToken); } @Override public int hashCode() { int result = super.hashCode(); // eventType and cursorToken are checked for null here only because of validation implementation that // calls hashCode before checking fields for not-null result = 31 * result + (eventType != null ? eventType.hashCode() : 0); result = 31 * result + (cursorToken != null ? cursorToken.hashCode() : 0); return result; } @Override public String toString() { return "SubscriptionCursor{" + "partition='" + getPartition() + '\'' + ", offset='" + getOffset() + '\'' + ", eventType='" + eventType + '\'' + ", cursorToken='" + cursorToken + '\'' + '}'; } }
package seedu.address.logic.parser; import com.joestelmach.natty.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * Tokenizes arguments string of the form: {@code preamble <prefix>value <prefix>value ...}<br> * e.g. {@code some preamble text /t 11.00/dToday /t 12.00 /k /m July} where prefixes are {@code /t /d /k /m}.<br> * 1. An argument's value can be an empty string e.g. the value of {@code /k} in the above example.<br> * 2. Leading and trailing whitespaces of an argument value will be discarded.<br> * 3. A prefix need not have leading and trailing spaces e.g. the {@code /d in 11.00/dToday} in the above example<br> * 4. An argument may be repeated and all its values will be accumulated e.g. the value of {@code /t} * in the above example.<br> */ public class ArgumentTokenizer { /** Given prefixes **/ private final List<Prefix> prefixes; /** Arguments found after tokenizing **/ private final Map<Prefix, List<String>> tokenizedArguments = new HashMap<>(); /** * Creates an ArgumentTokenizer that can tokenize arguments string as described by prefixes */ public ArgumentTokenizer(Prefix... prefixes) { this.prefixes = Arrays.asList(prefixes); } /** * @param argsString arguments string of the form: preamble <prefix>value <prefix>value ... */ public void tokenize(String argsString) { resetTokenizerState(); List<PrefixPosition> positions = findAllPrefixPositions(argsString); extractArguments(argsString, positions); } /** * Returns last value of given prefix. */ public Optional<String> getValue(Prefix prefix) { return getAllValues(prefix).flatMap((values) -> Optional.of(values.get(values.size() - 1))); } /** * Returns all values of given prefix. */ public Optional<List<String>> getAllValues(Prefix prefix) { if (!this.tokenizedArguments.containsKey(prefix)) { return Optional.empty(); } List<String> values = new ArrayList<>(this.tokenizedArguments.get(prefix)); return Optional.of(values); } /** * Returns the preamble (text before the first valid prefix), if any. Leading/trailing spaces will be trimmed. * If the string before the first prefix is empty, Optional.empty() will be returned. */ public Optional<String> getPreamble() { Optional<String> storedPreamble = getValue(new Prefix("")); /* An empty preamble is considered 'no preamble present' */ if (storedPreamble.isPresent() && !storedPreamble.get().isEmpty()) { return storedPreamble; } else { return Optional.empty(); } } private void resetTokenizerState() { this.tokenizedArguments.clear(); } /** * Finds all positions in an arguments string at which any prefix appears */ private List<PrefixPosition> findAllPrefixPositions(String argsString) { List<PrefixPosition> positions = new ArrayList<>(); for (Prefix prefix : this.prefixes) { positions.addAll(findPrefixPositions(argsString, prefix)); } return positions; } /** * Finds all positions in an arguments string at which a given {@code prefix} appears */ private List<PrefixPosition> findPrefixPositions(String argsString, Prefix prefix) { List<PrefixPosition> positions = new ArrayList<>(); int argumentStart = argsString.indexOf(prefix.getPrefix()); while (argumentStart != -1) { PrefixPosition extendedPrefix = new PrefixPosition(prefix, argumentStart); positions.add(extendedPrefix); argumentStart = argsString.indexOf(prefix.getPrefix(), argumentStart + 1); } return positions; } /** * Extracts the preamble/arguments and stores them in local variables. * @param prefixPositions must contain all prefixes in the {@code argsString} */ private void extractArguments(String argsString, List<PrefixPosition> prefixPositions) { // Sort by start position prefixPositions.sort((prefix1, prefix2) -> prefix1.getStartPosition() - prefix2.getStartPosition()); // Insert a PrefixPosition to represent the preamble PrefixPosition preambleMarker = new PrefixPosition(new Prefix(""), 0); prefixPositions.add(0, preambleMarker); // Add a dummy PrefixPosition to represent the end of the string PrefixPosition endPositionMarker = new PrefixPosition(new Prefix(""), argsString.length()); prefixPositions.add(endPositionMarker); // Extract the prefixed arguments and preamble (if any) for (int i = 0; i < prefixPositions.size() - 1; i++) { String argValue = extractArgumentValue(argsString, prefixPositions.get(i), prefixPositions.get(i + 1)); saveArgument(prefixPositions.get(i).getPrefix(), argValue); } } /** * Returns the trimmed value of the argument specified by {@code currentPrefixPosition}. * The end position of the value is determined by {@code nextPrefixPosition} */ private String extractArgumentValue(String argsString, PrefixPosition currentPrefixPosition, PrefixPosition nextPrefixPosition) { Prefix prefix = currentPrefixPosition.getPrefix(); int valueStartPos = currentPrefixPosition.getStartPosition() + prefix.getPrefix().length(); String value = argsString.substring(valueStartPos, nextPrefixPosition.getStartPosition()); if (prefix.getPrefix().equals("d/") ) { // Parse date value = parseNLPDate(value); } return value.trim(); } /** * Parses, analyses and converts 'rich text' into a timestamp * @param String - e.g. 'Tomorrow' * @return String - Timestamp */ private String parseNLPDate(String argsString) { com.joestelmach.natty.Parser nParser = new com.joestelmach.natty.Parser(); List<DateGroup> groups = nParser.parse(argsString); String output = ""; for(DateGroup group:groups) { List dates = group.getDates(); output = dates.get(0).toString().replace("CST", ""); } return output; } /** * Stores the value of the given prefix in the state of this tokenizer */ private void saveArgument(Prefix prefix, String value) { if (this.tokenizedArguments.containsKey(prefix)) { this.tokenizedArguments.get(prefix).add(value); return; } List<String> values = new ArrayList<>(); values.add(value); this.tokenizedArguments.put(prefix, values); } /** * A prefix that marks the beginning of an argument. * e.g. '/t' in 'add James /t friend' */ public static class Prefix { final String prefix; Prefix(String prefix) { this.prefix = prefix; } String getPrefix() { return this.prefix; } @Override public int hashCode() { return this.prefix == null ? 0 : this.prefix.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof Prefix)) { return false; } if (obj == this) { return true; } Prefix otherPrefix = (Prefix) obj; return otherPrefix.getPrefix().equals(getPrefix()); } } /** * Represents a prefix's position in an arguments string */ private class PrefixPosition { private int startPosition; private final Prefix prefix; PrefixPosition(Prefix prefix, int startPosition) { this.prefix = prefix; this.startPosition = startPosition; } int getStartPosition() { return this.startPosition; } Prefix getPrefix() { return this.prefix; } } }
package studentcapture.datalayer.database; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; @Repository public class Submission { // This template should be used to send queries to the database @Autowired protected JdbcTemplate jdbcTemplate; /** * Add a new submission for an assignment * * @param assignmentID Unique identifier for the assignment we're submitting to * @param studentID Unique identifier for the student submitting * @return True if everything went well, otherwise false */ public boolean addSubmission(String assignmentID,String studentID) { String sql = "INSERT INTO Submission (assignmentId, studentId, SubmissionDate) VALUES (?,?,?)"; java.util.Date date = new java.util.Date(System.currentTimeMillis()); java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime()); timestamp.setNanos(0); int rowsAffected = jdbcTemplate.update(sql,new Object[]{assignmentID,studentID,timestamp}); if(rowsAffected == 1){ return true; } return false; } /** * Add a grade for a submission * * @param assID Unique identifier for the assignment with the submission being graded * @param teacherID Unique identifier for the teacher grading * @param studentID Unique identifier for the student being graded * @param grade The grade of the submission * @return True if everything went well, otherwise false */ public boolean setGrade(String assID, String teacherID, String studentID, String grade) { String setGrade = "UPDATE Submission (Grade, TeacherID, Date) = (?, ?, ?) WHERE (AssignmentID = ?) AND (StudentID = ?)"; SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm"); Date date = new Date(); int updatedRows = jdbcTemplate.update(setGrade, new Object[]{grade, teacherID, dateFormat.format(date), assID, studentID}); if (updatedRows == 1) return true; else return false; } /** * Remove a submission * * @param assID Unique identifier for the assignment with the submission being removed * @param studentID Unique identifier for the student whose submission is removed * @return True if everything went well, otherwise false */ private static final String removeSubmissionStatement = "DELETE FROM " + "Submission WHERE (AssignmentId=? AND StudentId=?)"; public boolean removeSubmission(String assID, String studentID) { boolean result; int assignmentId = Integer.parseInt(assID); int studentId = Integer.parseInt(studentID); try { int rowsAffected = jdbcTemplate.update(removeSubmissionStatement, new Object[] {assignmentId, studentId}); if(rowsAffected == 1) { result = true; } else { result = false; } }catch (IncorrectResultSizeDataAccessException e){ result = false; }catch (DataAccessException e1){ result = false; } return result; } /** * Changes the grade of a submission * * @param assID Unique identifier for the assignment with the submission being graded * @param teacherID Unique identifier of the teacher updating * @param studentID Unique identifier for the student * @param grade The new grade of the submission * @param date The date the grade was updated * @return True if everything went well, otherwise false */ public boolean updateGrade(String assID, String teacherID, String studentID, String grade, Date date) { return true; } /** * Get information about the grade of a submission * * @param assignmentID Unique identifier for the assignment submission grade bra * @param studentID Unique identifier for the student associated with the submission * @return A list containing the grade, date, and grader */ public Map<String, Object> getGrade(int studentID, int assignmentID) { String query = "SELECT grade, submissiondate as time, concat(firstname,' ', lastname) as teacher" + " FROM submission JOIN users ON (teacherid = userid) WHERE (studentid = ? AND assignmentid = ?)"; Map<String, Object> response; try { response = jdbcTemplate.queryForMap(query, studentID, assignmentID); //return the time as string instead of timestamp response.put("time", response.get("time").toString()); } catch (IncorrectResultSizeDataAccessException e) { response = new HashMap<>(); //TODO create better error message response.put("error", e.getMessage()); } catch (DataAccessException e) { response = new HashMap<>(); //TODO create better error message response.put("error", e.getMessage()); } return response; } /** * Get all ungraded submissions for an assignment * * @param assID The assignment to get submissions for * @return A list of ungraded submissions for the assignment */ private final static String getAllUngradedStatement = "SELECT " + "sub.AssignmentId,sub.StudentId,stu.FirstName,stu.LastName," + "sub.SubmissionDate,sub.Grade,sub.TeacherId FROM " + "Submission AS sub LEFT JOIN Users AS stu ON " + "sub.studentId=stu.userId WHERE (AssignmentId=?) AND " + "(Grade IS NULL)"; public Optional<List<SubmissionWrapper>> getAllUngraded(String assId) { List<SubmissionWrapper> submissions = new ArrayList<>(); int assignmentId = Integer.parseInt(assId); try { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getAllUngradedStatement, new Object[] {assignmentId}); for (Map<String, Object> row : rows) { SubmissionWrapper submission = new SubmissionWrapper(); submission.assignmentId = (int) row.get("AssignmentId"); submission.studentId = (int) row.get("StudentId"); submission.teacherId = (int) row.get("TeacherId"); submission.grade = (String) row.get("Grade"); submission.submissionDate = ((Timestamp) row.get("SubmissionDate")).toString(); String firstName = (String) row.get("FirstName"); String lastName = (String) row.get("LastName"); submission.studentName = firstName + " " + lastName; submissions.add(submission); } } catch (IncorrectResultSizeDataAccessException e) { //TODO return Optional.empty(); } catch (DataAccessException e1) { //TODO return Optional.empty(); } return Optional.of(submissions); } /** * Get all submissions for an assignment * @param assID The assignment to get submissions for * @return A list of submissions for the assignment */ private final static String getAllSubmissionsStatement = "SELECT " + "sub.AssignmentId,sub.StudentId,stu.FirstName,stu.LastName," + "sub.SubmissionDate,sub.Grade,sub.TeacherId FROM " + "Submission AS sub LEFT JOIN Users AS stu ON " + "sub.studentId=stu.userId WHERE (AssignmentId=?)"; public Optional<List<SubmissionWrapper>> getAllSubmissions(String assId) { List<SubmissionWrapper> submissions = new ArrayList<>(); int assignmentId = Integer.parseInt(assId); try { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getAllSubmissionsStatement, new Object[] {assignmentId}); for (Map<String, Object> row : rows) { SubmissionWrapper submission = new SubmissionWrapper(); submission.assignmentId = (int) row.get("AssignmentId"); submission.studentId = (int) row.get("StudentId"); try { submission.teacherId = (int) row.get("TeacherId"); } catch (NullPointerException e) { submission.teacherId = null; } try { submission.grade = (String) row.get("Grade"); } catch (NullPointerException e) { submission.grade = null; } submission.submissionDate = ((Timestamp) row.get("SubmissionDate")).toString(); String firstName = (String) row.get("FirstName"); String lastName = (String) row.get("LastName"); submission.studentName = firstName + " " + lastName; submissions.add(submission); } } catch (IncorrectResultSizeDataAccessException e){ //TODO return Optional.empty(); } catch (DataAccessException e1){ //TODO return Optional.empty(); } return Optional.of(submissions); } /** * * Get all submissions for an assignment, including students that have not * yet made a submission. * * @param assID The assignment to get submissions for * @return A list of submissions for the assignment */ private final static String getAllSubmissionsWithStudentsStatement = "SELECT ass.AssignmentId,par.UserId AS StudentId,sub.SubmissionDate" + ",sub.Grade,sub.TeacherId FROM Assignment AS ass RIGHT JOIN " + "Participant AS par ON ass.CourseId=par.CourseId LEFT JOIN " + "Submission AS sub ON par.userId=sub.studentId WHERE " + "(par.function='Student') AND (ass.AssignmentId=?)"; public Optional<List<SubmissionWrapper>> getAllSubmissionsWithStudents (String assId) { List<SubmissionWrapper> submissions = new ArrayList<>(); int assignmentId = Integer.parseInt(assId); try { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getAllSubmissionsWithStudentsStatement, new Object[] {assignmentId}); for (Map<String, Object> row : rows) { SubmissionWrapper submission = new SubmissionWrapper(); submission.assignmentId = (int) row.get("AssignmentId"); submission.studentId = (int) row.get("StudentId"); try { submission.teacherId = (int) row.get("TeacherId"); } catch (NullPointerException e) { submission.teacherId = null; } try { submission.grade = (String) row.get("Grade"); } catch (NullPointerException e) { submission.grade = null; } try { submission.submissionDate = ((Timestamp) row.get("SubmissionDate")).toString(); } catch (NullPointerException e) { submission.submissionDate = null; } submissions.add(submission); } } catch (IncorrectResultSizeDataAccessException e){ //TODO return Optional.empty(); } catch (DataAccessException e1){ //TODO return Optional.empty(); } return Optional.of(submissions); } public class SubmissionWrapper { public int assignmentId; public int studentId; public String studentName; public String submissionDate; public String grade; public Integer teacherId; } }
package studentcapture.datalayer.database; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.*; @Repository public class Submission { // This template should be used to send queries to the database @Autowired protected JdbcTemplate jdbcTemplate; /** * Add a new submission for an assignment * * @param assignmentID Unique identifier for the assignment we're submitting to * @param studentID Unique identifier for the student submitting * @return True if everything went well, otherwise false */ public boolean addSubmission(String assignmentID,String studentID) { String sql = "INSERT INTO Submission (assignmentId, studentId, SubmissionDate) VALUES (?,?,?)"; java.util.Date date = new java.util.Date(System.currentTimeMillis()); java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime()); timestamp.setNanos(0); int assID = Integer.parseInt(assignmentID); int subID = Integer.parseInt(studentID); int rowsAffected = 0; try{ rowsAffected = jdbcTemplate.update(sql,assID,subID,timestamp); } catch (Exception e) { return false; } return rowsAffected == 1; } /** * Add a grade for a submission * * @param assID Unique identifier for the assignment with the submission being graded * @param teacherID Unique identifier for the teacher grading * @param studentID Unique identifier for the student being graded * @param grade The grade of the submission * @return True if everything went well, otherwise false */ public boolean setGrade(int assID, int teacherID, int studentID, String grade) { String setGrade = "UPDATE Submission (Grade, TeacherID, Date) = (?, ?, ?) WHERE (AssignmentID = ?) AND (StudentID = ?)"; SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm"); Date date = new Date(); int updatedRows = jdbcTemplate.update(setGrade, grade, teacherID, dateFormat.format(date), assID, studentID); return updatedRows == 1; } private static final String removeSubmissionStatement = "DELETE FROM " + "Submission WHERE (AssignmentId=? AND StudentId=?)"; /** * Remove a submission * * @param assID Unique identifier for the assignment with the submission being removed * @param studentID Unique identifier for the student whose submission is removed * @return True if everything went well, otherwise false */ public boolean removeSubmission(String assID, String studentID) { boolean result; int assignmentId = Integer.parseInt(assID); int studentId = Integer.parseInt(studentID); try { int rowsAffected = jdbcTemplate.update(removeSubmissionStatement, assignmentId, studentId); result = rowsAffected == 1; } catch (IncorrectResultSizeDataAccessException e){ result = false; } catch (DataAccessException e1){ result = false; } return result; } /** * Changes the grade of a submission * * @param assID Unique identifier for the assignment with the submission being graded * @param teacherID Unique identifier of the teacher updating * @param studentID Unique identifier for the student * @param grade The new grade of the submission * @param date The date the grade was updated * @return True if everything went well, otherwise false */ public boolean updateGrade(String assID, String teacherID, String studentID, String grade, Date date) { return true; } /** * Get information about the grade of a submission * * @param assignmentID Unique identifier for the assignment submission grade bra * @param studentID Unique identifier for the student associated with the submission * @return A list containing the grade, date, and grader */ public Map<String, Object> getGrade(int studentID, int assignmentID) { String query = "SELECT grade, submissiondate as time, concat(firstname,' ', lastname) as teacher" + " FROM submission JOIN users ON (teacherid = userid) WHERE (studentid = ? AND assignmentid = ?)"; Map<String, Object> response; try { response = jdbcTemplate.queryForMap(query, studentID, assignmentID); //return the time as string instead of timestamp response.put("time", response.get("time").toString()); } catch (IncorrectResultSizeDataAccessException e) { response = new HashMap<>(); //TODO create better error message response.put("error", e.getMessage()); } catch (DataAccessException e) { response = new HashMap<>(); //TODO create better error message response.put("error", e.getMessage()); } return response; } /** * Get all ungraded submissions for an assignment * * @param assID The assignment to get submissions for * @return A list of ungraded submissions for the assignment */ public Optional<List<SubmissionWrapper>> getAllUngraded(String assId) { String getAllUngradedStatement = "SELECT " + "sub.AssignmentId,sub.StudentId,stu.FirstName,stu.LastName," + "sub.SubmissionDate,sub.Grade,sub.TeacherId FROM " + "Submission AS sub LEFT JOIN Users AS stu ON " + "sub.studentId=stu.userId WHERE (AssignmentId=?) AND " + "(Grade IS NULL)"; List<SubmissionWrapper> submissions = new ArrayList<>(); int assignmentId = Integer.parseInt(assId); try { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getAllUngradedStatement, assignmentId); for (Map<String, Object> row : rows) { SubmissionWrapper submission = new SubmissionWrapper(); submission.assignmentId = (int) row.get("AssignmentId"); submission.studentId = (int) row.get("StudentId"); //submission.teacherId = (int) row.get("TeacherId"); //submission.grade = (String) row.get("Grade"); submission.submissionDate = row.get("SubmissionDate").toString(); try { String firstName = (String) row.get("FirstName"); String lastName = (String) row.get("LastName"); submission.studentName = firstName + " " + lastName; } catch (NullPointerException e) { submission.studentName = null; } submissions.add(submission); } } catch (IncorrectResultSizeDataAccessException e) { //TODO return Optional.empty(); } catch (DataAccessException e1) { //TODO return Optional.empty(); } return Optional.of(submissions); } /** * Get all submissions for an assignment * @param assId The assignment to get submissions for * @return A list of submissions for the assignment */ public Optional<List<SubmissionWrapper>> getAllSubmissions(String assId) { List<SubmissionWrapper> submissions = new ArrayList<>(); int assignmentId = Integer.parseInt(assId); String getAllSubmissionsStatement = "SELECT " + "sub.AssignmentId,sub.StudentId,stu.FirstName,stu.LastName," + "sub.SubmissionDate,sub.Grade,sub.TeacherId FROM " + "Submission AS sub LEFT JOIN Users AS stu ON " + "sub.studentId=stu.userId WHERE (AssignmentId=?)"; try { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getAllSubmissionsStatement, assignmentId); for (Map<String, Object> row : rows) { SubmissionWrapper submission = new SubmissionWrapper(); submission.assignmentId = (int) row.get("AssignmentId"); submission.studentId = (int) row.get("StudentId"); try { submission.teacherId = (int) row.get("TeacherId"); } catch (NullPointerException e) { submission.teacherId = null; } try { submission.grade = (String) row.get("Grade"); } catch (NullPointerException e) { submission.grade = null; } submission.submissionDate = ((Timestamp) row.get("SubmissionDate")).toString(); try { String firstName = (String) row.get("FirstName"); String lastName = (String) row.get("LastName"); submission.studentName = firstName + " " + lastName; } catch (NullPointerException e) { submission.studentName = null; } submissions.add(submission); } } catch (IncorrectResultSizeDataAccessException e){ //TODO return Optional.empty(); } catch (DataAccessException e1){ //TODO return Optional.empty(); } return Optional.of(submissions); } /** * * Get all submissions for an assignment, including students that have not * yet made a submission. * * @param assId The assignment to get submissions for * @return A list of submissions for the assignment */ public Optional<List<SubmissionWrapper>> getAllSubmissionsWithStudents (String assId) { List<SubmissionWrapper> submissions = new ArrayList<>(); int assignmentId = Integer.parseInt(assId); String getAllSubmissionsWithStudentsStatement = "SELECT ass.AssignmentId,par.UserId AS StudentId,sub.SubmissionDate" + ",sub.Grade,sub.TeacherId FROM Assignment AS ass RIGHT JOIN " + "Participant AS par ON ass.CourseId=par.CourseId LEFT JOIN " + "Submission AS sub ON par.userId=sub.studentId WHERE " + "(par.function='Student') AND (ass.AssignmentId=?)"; try { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getAllSubmissionsWithStudentsStatement, assignmentId); for (Map<String, Object> row : rows) { SubmissionWrapper submission = new SubmissionWrapper(); submission.assignmentId = (int) row.get("AssignmentId"); submission.studentId = (int) row.get("StudentId"); try { submission.teacherId = (int) row.get("TeacherId"); } catch (NullPointerException e) { submission.teacherId = null; } try { submission.grade = (String) row.get("Grade"); } catch (NullPointerException e) { submission.grade = null; } try { submission.submissionDate = ((Timestamp) row.get("SubmissionDate")).toString(); } catch (NullPointerException e) { submission.submissionDate = null; } submissions.add(submission); } } catch (IncorrectResultSizeDataAccessException e){ //TODO return Optional.empty(); } catch (DataAccessException e1){ //TODO return Optional.empty(); } return Optional.of(submissions); } public Optional<SubmissionWrapper> getSubmissionWithWrapper(int assignmentId, int studentId) { SubmissionWrapper result = new SubmissionWrapper(); String getStudentSubmissionStatement = "SELECT * FROM Submission WHERE AssignmentId=? AND StudentId=?"; try { List<Map<String, Object>> rows = jdbcTemplate.queryForList( getStudentSubmissionStatement, assignmentId, studentId); for (Map<String, Object> row : rows) { result.assignmentId = (int) row.get("AssignmentId"); result.studentId = (int) row.get("StudentId"); try { result.teacherId = (int) row.get("TeacherId"); } catch (NullPointerException e) { result.teacherId = null; } try { result.grade = (String) row.get("Grade"); } catch (NullPointerException e) { result.grade = null; } try { result.submissionDate = row.get("SubmissionDate").toString(); } catch (NullPointerException e) { result.submissionDate = null; } // TODO: This break statements negates the for loop (it ends on its first iteration) break; } } catch (IncorrectResultSizeDataAccessException e){ //TODO return Optional.empty(); } catch (DataAccessException e1){ //TODO return Optional.empty(); } return Optional.of(result); } public static class SubmissionWrapper { public int assignmentId; public int studentId; public String studentName; public String submissionDate; public String grade; public Integer teacherId; } }
package uk.ac.ebi.phenotype.solr.indexer; import org.apache.commons.lang3.StringUtils; import org.apache.solr.client.solrj.SolrServer; import org.apache.solr.client.solrj.SolrServerException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import uk.ac.ebi.phenotype.service.dto.*; import uk.ac.ebi.phenotype.solr.indexer.utils.IndexerMap; import uk.ac.ebi.phenotype.solr.indexer.utils.SolrUtils; import javax.sql.DataSource; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.apache.solr.client.solrj.SolrQuery; /** * Populate the MA core */ public class GeneIndexer extends AbstractIndexer { private static final Logger logger = LoggerFactory.getLogger(GeneIndexer.class); private Connection komp2DbConnection; @Autowired @Qualifier("komp2DataSource") DataSource komp2DataSource; @Autowired @Qualifier("alleleIndexing") SolrServer alleleCore; @Autowired @Qualifier("geneIndexing") SolrServer geneCore; @Autowired @Qualifier("mpIndexing") SolrServer mpCore; @Autowired @Qualifier("sangerImagesIndexing") SolrServer imagesCore; private Map<String, List<Map<String, String>>> phenotypeSummaryGeneAccessionsToPipelineInfo = new HashMap<>(); private Map<String, List<SangerImageDTO>> sangerImages = new HashMap<>(); private Map<String, List<MpDTO>> mgiAccessionToMP = new HashMap<>(); public GeneIndexer() { } public static final long MIN_EXPECTED_ROWS = 55000; @Override public void validateBuild() throws IndexerException { SolrQuery query = new SolrQuery().setQuery("*:*").setRows(0); try { Long numFound = geneCore.query(query).getResults().getNumFound(); if (numFound < MIN_EXPECTED_ROWS) { throw new IndexerException("validateBuild(): Expected " + MIN_EXPECTED_ROWS + " rows but found " + numFound + " rows."); } logger.info("MIN_EXPECTED_ROWS: " + MIN_EXPECTED_ROWS + ". Actual rows: " + numFound); } catch (SolrServerException sse) { throw new IndexerException(sse); } } @Override public void initialise(String[] args) throws IndexerException { super.initialise(args); applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true); try { komp2DbConnection = komp2DataSource.getConnection(); } catch (SQLException sqle) { logger.error("Caught SQL Exception initialising database connections: {}", sqle.getMessage()); throw new IndexerException(sqle); } } @Override public void run() throws IndexerException { long startTime = System.currentTimeMillis(); try { logger.info("Starting Gene Indexer..."); initialiseSupportingBeans(); int count = 0; List<AlleleDTO> alleles = IndexerMap.getAlleles(alleleCore); System.out.println("alleles size=" + alleles.size()); geneCore.deleteByQuery("*:*"); for (AlleleDTO allele : alleles) { //System.out.println("allele="+allele.getMarkerSymbol()); GeneDTO gene = new GeneDTO(); gene.setMgiAccessionId(allele.getMgiAccessionId()); gene.setDataType(allele.getDataType()); gene.setMarkerType(allele.getMarkerType()); gene.setMarkerSymbol(allele.getMarkerSymbol()); gene.setMarkerSynonym(allele.getMarkerSynonym()); gene.setMarkerName(allele.getMarkerName()); gene.setHumanGeneSymbol(allele.getHumanGeneSymbol()); gene.setLatestEsCellStatus(allele.getLatestEsCellStatus()); gene.setImitsPhenotypeStarted(allele.getImitsPhenotypeStarted()); gene.setImitsPhenotypeComplete(allele.getImitsPhenotypeComplete()); gene.setImitsPhenotypeStatus(allele.getImitsPhenotypeStatus()); gene.setLatestMouseStatus(allele.getLatestMouseStatus()); gene.setLatestProjectStatus(allele.getLatestProjectStatus()); gene.setStatus(allele.getStatus()); gene.setLatestPhenotypeStatus(allele.getLatestPhenotypeStatus()); gene.setLegacy_phenotype_status(allele.getLegacyPhenotypeStatus()); gene.setLatestProductionCentre(allele.getLatestProductionCentre()); gene.setLatestPhenotypingCentre(allele.getLatestPhenotypingCentre()); gene.setAlleleName(allele.getAlleleName()); gene.setEsCellStatus(allele.getEsCellStatus()); gene.setMouseStatus(allele.getMouseStatus()); gene.setPhenotypeStatus(allele.getPhenotypeStatus()); gene.setProductionCentre(allele.getProductionCentre()); gene.setPhenotypingCentre(allele.getPhenotypingCentre()); gene.setType(allele.getType()); gene.setDiseaseSource(allele.getDiseaseSource()); gene.setDiseaseId(allele.getDiseaseId()); gene.setDiseaseTerm(allele.getDiseaseTerm()); gene.setDiseaseAlts(allele.getDiseaseAlts()); gene.setDiseaseClasses(allele.getDiseaseClasses()); gene.setHumanCurated(allele.getHumanCurated()); gene.setMouseCurated(allele.getMouseCurated()); gene.setMgiPredicted(allele.getMgiPredicted()); gene.setImpcPredicted(allele.getImpcPredicted()); gene.setMgiPredicted(allele.getMgiPredicted()); gene.setMgiPredictedKnonwGene(allele.getMgiPredictedKnownGene()); gene.setImpcNovelPredictedInLocus(allele.getImpcNovelPredictedInLocus()); gene.setDiseaseHumanPhenotypes(allele.getDiseaseHumanPhenotypes()); gene.setGoTermIds(allele.getGoTermIds()); gene.setGoTermNames(allele.getGoTermNames()); // gene.getGoTermDefs().addAll(allele.getGoTermDefs()); gene.setGoTermEvids(allele.getGoTermEvids()); gene.setGoTermDomains(allele.getGoTermDomains()); //gene.setMpId(allele.getM) // Populate pipeline and procedure info if we have a phenotypeCallSummary entry for this allele/gene if (phenotypeSummaryGeneAccessionsToPipelineInfo.containsKey(allele.getMgiAccessionId())) { List<Map<String, String>> rows = phenotypeSummaryGeneAccessionsToPipelineInfo.get(allele.getMgiAccessionId()); List<String> pipelineNames = new ArrayList<>(); List<String> pipelineStableIds = new ArrayList<>(); List<String> procedureNames = new ArrayList<>(); List<String> procedureStableIds = new ArrayList<>(); List<String> parameterNames = new ArrayList<>(); List<String> parameterStableIds = new ArrayList<>(); for (Map<String, String> row : rows) { pipelineNames.add(row.get(ObservationDTO.PIPELINE_NAME)); pipelineStableIds.add(row.get(ObservationDTO.PIPELINE_STABLE_ID)); procedureNames.add(row.get(ObservationDTO.PROCEDURE_NAME)); procedureStableIds.add(row.get(ObservationDTO.PROCEDURE_STABLE_ID)); parameterNames.add(row.get(ObservationDTO.PARAMETER_NAME)); parameterStableIds.add(row.get(ObservationDTO.PARAMETER_STABLE_ID)); } gene.setPipelineName(pipelineNames); gene.setPipelineStableId(pipelineStableIds); gene.setProcedureName(procedureNames); gene.setProcedureStableId(procedureStableIds); gene.setParameterName(parameterNames); gene.setParameterStableId(parameterStableIds); } //do images core data // Initialize all the ontology term lists gene.setMpId(new ArrayList<String>()); gene.setMpTerm(new ArrayList<String>()); gene.setMpTermSynonym(new ArrayList<String>()); gene.setMpTermDefinition(new ArrayList<String>()); gene.setOntologySubset(new ArrayList<String>()); gene.setMaId(new ArrayList<String>()); gene.setMaTerm(new ArrayList<String>()); gene.setMaTermSynonym(new ArrayList<String>()); gene.setMaTermDefinition(new ArrayList<String>()); gene.setHpId(new ArrayList<String>()); gene.setHpTerm(new ArrayList<String>()); gene.setTopLevelMpId(new ArrayList<String>()); gene.setTopLevelMpTerm(new ArrayList<String>()); gene.setTopLevelMpTermSynonym(new ArrayList<String>()); gene.setIntermediateMpId(new ArrayList<String>()); gene.setIntermediateMpTerm(new ArrayList<String>()); gene.setIntermediateMpTermSynonym(new ArrayList<String>()); gene.setChildMpId(new ArrayList<String>()); gene.setChildMpTerm(new ArrayList<String>()); gene.setChildMpTermSynonym(new ArrayList<String>()); gene.setChildMpId(new ArrayList<String>()); gene.setChildMpTerm(new ArrayList<String>()); gene.setChildMpTermSynonym(new ArrayList<String>()); gene.setInferredMaId(new ArrayList<String>()); gene.setInferredMaTerm(new ArrayList<String>()); gene.setInferredMaTermSynonym(new ArrayList<String>()); gene.setSelectedTopLevelMaId(new ArrayList<String>()); gene.setSelectedTopLevelMaTerm(new ArrayList<String>()); gene.setSelectedTopLevelMaTermSynonym(new ArrayList<String>()); gene.setInferredChildMaId(new ArrayList<String>()); gene.setInferredChildMaTerm(new ArrayList<String>()); gene.setInferredChildMaTermSynonym(new ArrayList<String>()); gene.setInferredSelectedTopLevelMaId(new ArrayList<String>()); gene.setInferredSelectedTopLevelMaTerm(new ArrayList<String>()); gene.setInferredSelectedTopLevelMaTermSynonym(new ArrayList<String>()); // Add all ontology information from images associated to this gene if (sangerImages.containsKey(allele.getMgiAccessionId())) { List<SangerImageDTO> list = sangerImages.get(allele.getMgiAccessionId()); for (SangerImageDTO image : list) { if (image.getMp_id() != null && ! gene.getMpId().contains(image.getMp_id())) { gene.getMpId().addAll(image.getMp_id()); gene.getMpTerm().addAll(image.getMpTerm()); if (image.getMpSyns() != null) { gene.getMpTermSynonym().addAll(image.getMpSyns()); } if (image.getAnnotatedHigherLevelMpTermId() != null) { gene.getTopLevelMpId().addAll(image.getAnnotatedHigherLevelMpTermId()); } if (image.getAnnotatedHigherLevelMpTermName() != null) { gene.getTopLevelMpTerm().addAll(image.getAnnotatedHigherLevelMpTermName()); } if (image.getTopLevelMpTermSynonym() != null) { gene.getTopLevelMpTermSynonym().addAll(image.getTopLevelMpTermSynonym()); } if (image.getIntermediateMpId() != null) { gene.getIntermediateMpId().addAll(image.getIntermediateMpId()); } if (image.getIntermediateMpTerm() != null) { gene.getIntermediateMpTerm().addAll(image.getIntermediateMpTerm()); } if (image.getIntermediateMpTermSyn() != null) { gene.getIntermediateMpTermSynonym().addAll(image.getIntermediateMpTermSyn()); } } if (image.getMaTermId() != null) { gene.getMaId().addAll(image.getMaTermId()); gene.getMaTerm().addAll(image.getMaTermName()); if (image.getMaTermSynonym() != null) { gene.getMaTermSynonym().addAll(image.getMaTermSynonym()); } if (image.getSelectedTopLevelMaTermId() != null) { gene.setSelectedTopLevelMaId(image.getSelectedTopLevelMaTermId()); } if (image.getSelectedTopLevelMaTerm() != null) { gene.setSelectedTopLevelMaTerm(image.getSelectedTopLevelMaTerm()); } if (image.getSelectedTopLevelMaTermSynonym() != null) { gene.setSelectedTopLevelMaTermSynonym(image.getSelectedTopLevelMaTermSynonym()); } } } } // Add all ontology information directly associated from MP to this gene if (StringUtils.isNotEmpty(allele.getMgiAccessionId())) { if (mgiAccessionToMP.containsKey(allele.getMgiAccessionId())) { List<MpDTO> mps = mgiAccessionToMP.get(allele.getMgiAccessionId()); for (MpDTO mp : mps) { gene.getMpId().add(mp.getMpId()); gene.getMpTerm().add(mp.getMpTerm()); if (mp.getMpTermSynonym() != null) { gene.getMpTermSynonym().addAll(mp.getMpTermSynonym()); } if (mp.getOntologySubset() != null) { gene.getOntologySubset().addAll(mp.getOntologySubset()); } if (mp.getHpId() != null) { gene.getHpId().addAll(mp.getHpId()); gene.getHpTerm().addAll(mp.getHpTerm()); } if (mp.getTopLevelMpId() != null) { gene.getTopLevelMpId().addAll(mp.getTopLevelMpId()); gene.getTopLevelMpTerm().addAll(mp.getTopLevelMpTerm()); } if (mp.getTopLevelMpTermSynonym() != null) { gene.getTopLevelMpTermSynonym().addAll(mp.getTopLevelMpTermSynonym()); } if (mp.getIntermediateMpId() != null) { gene.getIntermediateMpId().addAll(mp.getIntermediateMpId()); gene.getIntermediateMpTerm().addAll(mp.getIntermediateMpTerm()); } if (mp.getIntermediateMpTermSynonym() != null) { gene.getIntermediateMpTermSynonym().addAll(mp.getIntermediateMpTermSynonym()); } if (mp.getChildMpId() != null) { gene.getChildMpId().addAll(mp.getChildMpId()); gene.getChildMpTerm().addAll(mp.getChildMpTerm()); } if (mp.getChildMpTermSynonym() != null) { gene.getChildMpTermSynonym().addAll(mp.getChildMpTermSynonym()); } if (mp.getInferredMaId() != null) { gene.getInferredMaId().addAll(mp.getInferredMaId()); gene.getInferredMaTerm().addAll(mp.getInferredMaTerm()); } if (mp.getInferredMaTermSynonym() != null) { gene.getInferredMaTermSynonym().addAll(mp.getInferredMaTermSynonym()); } if (mp.getInferredSelectedTopLevelMaId() != null) { gene.getInferredSelectedTopLevelMaId().addAll(mp.getInferredSelectedTopLevelMaId()); gene.getInferredSelectedTopLevelMaTerm().addAll(mp.getInferredSelectedTopLevelMaTerm()); } if (mp.getInferredSelectedTopLevelMaTermSynonym() != null) { gene.getInferredSelectedTopLevelMaTermSynonym().addAll(mp.getInferredSelectedTopLevelMaTermSynonym()); } if (mp.getInferredChildMaId() != null) { gene.getInferredChildMaId().addAll(mp.getInferredChildMaId()); gene.getInferredChildMaTerm().addAll(mp.getInferredChildMaTerm()); } if (mp.getInferredChildMaTermSynonym() != null) { gene.getInferredChildMaTermSynonym().addAll(mp.getInferredChildMaTermSynonym()); } } } } /** * Unique all the sets */ gene.setMpId(new ArrayList<>(new HashSet<>(gene.getMpId()))); gene.setMpTerm(new ArrayList<>(new HashSet<>(gene.getMpTerm()))); gene.setMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getMpTermSynonym()))); gene.setMpTermDefinition(new ArrayList<>(new HashSet<>(gene.getMpTermDefinition()))); gene.setOntologySubset(new ArrayList<>(new HashSet<>(gene.getOntologySubset()))); gene.setMaId(new ArrayList<>(new HashSet<>(gene.getMaId()))); gene.setMaTerm(new ArrayList<>(new HashSet<>(gene.getMaTerm()))); gene.setMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getMaTermSynonym()))); gene.setMaTermDefinition(new ArrayList<>(new HashSet<>(gene.getMaTermDefinition()))); gene.setHpId(new ArrayList<>(new HashSet<>(gene.getHpId()))); gene.setHpTerm(new ArrayList<>(new HashSet<>(gene.getHpTerm()))); gene.setTopLevelMpId(new ArrayList<>(new HashSet<>(gene.getTopLevelMpId()))); gene.setTopLevelMpTerm(new ArrayList<>(new HashSet<>(gene.getTopLevelMpTerm()))); gene.setTopLevelMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getTopLevelMpTermSynonym()))); gene.setIntermediateMpId(new ArrayList<>(new HashSet<>(gene.getIntermediateMpId()))); gene.setIntermediateMpTerm(new ArrayList<>(new HashSet<>(gene.getIntermediateMpTerm()))); gene.setIntermediateMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getIntermediateMpTermSynonym()))); gene.setChildMpId(new ArrayList<>(new HashSet<>(gene.getChildMpId()))); gene.setChildMpTerm(new ArrayList<>(new HashSet<>(gene.getChildMpTerm()))); gene.setChildMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getChildMpTermSynonym()))); gene.setChildMpId(new ArrayList<>(new HashSet<>(gene.getChildMpId()))); gene.setChildMpTerm(new ArrayList<>(new HashSet<>(gene.getChildMpTerm()))); gene.setChildMpTermSynonym(new ArrayList<>(new HashSet<>(gene.getChildMpTermSynonym()))); gene.setInferredMaId(new ArrayList<>(new HashSet<>(gene.getInferredMaId()))); gene.setInferredMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredMaTerm()))); gene.setInferredMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredMaTermSynonym()))); gene.setSelectedTopLevelMaId(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaId()))); gene.setSelectedTopLevelMaTerm(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaTerm()))); gene.setSelectedTopLevelMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getSelectedTopLevelMaTermSynonym()))); gene.setInferredChildMaId(new ArrayList<>(new HashSet<>(gene.getInferredChildMaId()))); gene.setInferredChildMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredChildMaTerm()))); gene.setInferredChildMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredChildMaTermSynonym()))); gene.setInferredSelectedTopLevelMaId(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaId()))); gene.setInferredSelectedTopLevelMaTerm(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaTerm()))); gene.setInferredSelectedTopLevelMaTermSynonym(new ArrayList<>(new HashSet<>(gene.getInferredSelectedTopLevelMaTermSynonym()))); geneCore.addBean(gene, 60000); count ++; if (count % 10000 == 0) { System.out.println(" added " + count + " beans"); } } logger.info("Committing to gene core for last time"); geneCore.commit(); } catch (IOException | SolrServerException e) { e.printStackTrace(); throw new IndexerException(e); } long endTime = System.currentTimeMillis(); System.out.println("time was " + (endTime - startTime) / 1000); logger.info("Gene Indexer complete!"); } // PROTECTED METHODS @Override protected Logger getLogger() { return logger; } // PRIVATE METHODS private void initialiseSupportingBeans() throws IndexerException { phenotypeSummaryGeneAccessionsToPipelineInfo = populatePhenotypeCallSummaryGeneAccessions(); sangerImages = IndexerMap.getSangerImagesByMgiAccession(imagesCore); mgiAccessionToMP = populateMgiAccessionToMp(); System.out.println("mgiAccessionToMP size=" + mgiAccessionToMP.size()); } private Map<String, List<MpDTO>> populateMgiAccessionToMp() throws IndexerException { return SolrUtils.populateMgiAccessionToMp(mpCore); } private Map<String, List<Map<String, String>>> populatePhenotypeCallSummaryGeneAccessions() { System.out.println("populating PCS pipeline info"); String queryString = "select pcs.*, param.name, param.stable_id, proc.stable_id, proc.name, pipe.stable_id, pipe.name" + " from phenotype_call_summary pcs" + " inner join ontology_term term on term.acc=mp_acc" + " inner join genomic_feature gf on gf.acc=pcs.gf_acc" + " inner join phenotype_parameter param on param.id=pcs.parameter_id" + " inner join phenotype_procedure proc on proc.id=pcs.procedure_id" + " inner join phenotype_pipeline pipe on pipe.id=pcs.pipeline_id"; try (PreparedStatement p = komp2DbConnection.prepareStatement(queryString)) { ResultSet resultSet = p.executeQuery(); while (resultSet.next()) { String gf_acc = resultSet.getString("gf_acc"); Map<String, String> rowMap = new HashMap<>(); rowMap.put(ObservationDTO.PARAMETER_NAME, resultSet.getString("param.name")); rowMap.put(ObservationDTO.PARAMETER_STABLE_ID, resultSet.getString("param.stable_id")); rowMap.put(ObservationDTO.PROCEDURE_STABLE_ID, resultSet.getString("proc.stable_id")); rowMap.put(ObservationDTO.PROCEDURE_NAME, resultSet.getString("proc.name")); rowMap.put(ObservationDTO.PIPELINE_STABLE_ID, resultSet.getString("pipe.stable_id")); rowMap.put(ObservationDTO.PIPELINE_NAME, resultSet.getString("pipe.name")); rowMap.put("proc_param_name", resultSet.getString("proc.name") + "___" + resultSet.getString("param.name")); rowMap.put("proc_param_stable_id", resultSet.getString("proc.stable_id") + "___" + resultSet.getString("param.stable_id")); List<Map<String, String>> rows = null; if (phenotypeSummaryGeneAccessionsToPipelineInfo.containsKey(gf_acc)) { rows = phenotypeSummaryGeneAccessionsToPipelineInfo.get(gf_acc); } else { rows = new ArrayList<>(); } rows.add(rowMap); phenotypeSummaryGeneAccessionsToPipelineInfo.put(gf_acc, rows); } } catch (Exception e) { e.printStackTrace(); } return phenotypeSummaryGeneAccessionsToPipelineInfo; } public static void main(String[] args) throws IndexerException { GeneIndexer indexer = new GeneIndexer(); indexer.initialise(args); indexer.run(); indexer.validateBuild(); logger.info("Process finished. Exiting."); } }
package zmaster587.advancedRocketry; import net.minecraft.block.Block; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.block.material.MaterialLiquid; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.item.EntityArmorStand; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemDoor; import net.minecraft.item.ItemStack; import net.minecraft.item.Item.ToolMaterial; import net.minecraft.world.World; import net.minecraft.world.WorldType; import net.minecraft.world.biome.Biome; import net.minecraftforge.common.ForgeChunkManager; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fml.common.Loader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.event.FMLServerStartedEvent; import net.minecraftforge.fml.common.event.FMLServerStartingEvent; import net.minecraftforge.fml.common.event.FMLServerStoppedEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.network.NetworkRegistry; import net.minecraftforge.fml.common.registry.EntityRegistry; import net.minecraftforge.fml.common.registry.GameRegistry; import net.minecraftforge.oredict.OreDictionary; import net.minecraftforge.oredict.OreDictionary.OreRegisterEvent; import net.minecraftforge.oredict.ShapedOreRecipe; import net.minecraftforge.oredict.ShapelessOreRecipe; import zmaster587.advancedRocketry.achievements.ARAchivements; import zmaster587.advancedRocketry.api.*; import zmaster587.advancedRocketry.api.atmosphere.AtmosphereRegister; import zmaster587.advancedRocketry.api.capability.CapabilitySpaceArmor; import zmaster587.advancedRocketry.api.dimension.solar.StellarBody; import zmaster587.advancedRocketry.api.fuel.FuelRegistry; import zmaster587.advancedRocketry.api.fuel.FuelRegistry.FuelType; import zmaster587.advancedRocketry.api.satellite.SatelliteProperties; import zmaster587.advancedRocketry.api.stations.ISpaceObject; import zmaster587.advancedRocketry.armor.ItemSpaceArmor; import zmaster587.advancedRocketry.atmosphere.AtmosphereVacuum; import zmaster587.advancedRocketry.backwardCompat.VersionCompat; import zmaster587.advancedRocketry.block.BlockAstroBed; import zmaster587.advancedRocketry.block.BlockCharcoalLog; import zmaster587.advancedRocketry.block.BlockCrystal; import zmaster587.advancedRocketry.block.BlockDoor2; import zmaster587.advancedRocketry.block.BlockElectricMushroom; import zmaster587.advancedRocketry.block.BlockFluid; import zmaster587.advancedRocketry.block.BlockHalfTile; import zmaster587.advancedRocketry.block.BlockIntake; import zmaster587.advancedRocketry.block.BlockLandingPad; import zmaster587.advancedRocketry.block.BlockLaser; import zmaster587.advancedRocketry.block.BlockLightSource; import zmaster587.advancedRocketry.block.BlockLinkedHorizontalTexture; import zmaster587.advancedRocketry.block.BlockMiningDrill; import zmaster587.advancedRocketry.block.BlockPlanetSoil; import zmaster587.advancedRocketry.block.BlockPress; import zmaster587.advancedRocketry.block.BlockPressurizedFluidTank; import zmaster587.advancedRocketry.block.BlockQuartzCrucible; import zmaster587.advancedRocketry.block.BlockRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockRocketMotor; import zmaster587.advancedRocketry.block.BlockRotatableModel; import zmaster587.advancedRocketry.block.BlockSeat; import zmaster587.advancedRocketry.block.BlockFuelTank; import zmaster587.advancedRocketry.block.BlockSolarGenerator; import zmaster587.advancedRocketry.block.BlockStationModuleDockingPort; import zmaster587.advancedRocketry.block.BlockTileNeighborUpdate; import zmaster587.advancedRocketry.block.BlockTileRedstoneEmitter; import zmaster587.advancedRocketry.block.BlockWarpCore; import zmaster587.advancedRocketry.block.BlockWarpShipMonitor; import zmaster587.advancedRocketry.block.cable.BlockDataCable; import zmaster587.advancedRocketry.block.cable.BlockEnergyCable; import zmaster587.advancedRocketry.block.cable.BlockLiquidPipe; import zmaster587.advancedRocketry.block.multiblock.BlockARHatch; import zmaster587.advancedRocketry.block.plant.BlockAlienLeaves; import zmaster587.advancedRocketry.block.plant.BlockAlienSapling; import zmaster587.advancedRocketry.block.plant.BlockAlienWood; import zmaster587.advancedRocketry.block.BlockTorchUnlit; import zmaster587.advancedRocketry.capability.CapabilityProtectiveArmor; import zmaster587.advancedRocketry.command.WorldCommand; import zmaster587.advancedRocketry.common.CommonProxy; import zmaster587.advancedRocketry.dimension.DimensionManager; import zmaster587.advancedRocketry.dimension.DimensionProperties; import zmaster587.advancedRocketry.dimension.DimensionProperties.AtmosphereTypes; import zmaster587.advancedRocketry.dimension.DimensionProperties.Temps; import zmaster587.advancedRocketry.entity.EntityDummy; import zmaster587.advancedRocketry.entity.EntityItemAbducted; import zmaster587.advancedRocketry.entity.EntityLaserNode; import zmaster587.advancedRocketry.entity.EntityRocket; import zmaster587.advancedRocketry.entity.EntityStationDeployedRocket; import zmaster587.advancedRocketry.event.BucketHandler; import zmaster587.advancedRocketry.event.CableTickHandler; import zmaster587.advancedRocketry.event.PlanetEventHandler; import zmaster587.advancedRocketry.event.WorldEvents; import zmaster587.advancedRocketry.integration.CompatibilityMgr; import zmaster587.libVulpes.inventory.GuiHandler; import zmaster587.libVulpes.items.ItemBlockMeta; import zmaster587.libVulpes.items.ItemIngredient; import zmaster587.libVulpes.items.ItemProjector; import zmaster587.advancedRocketry.item.*; import zmaster587.advancedRocketry.item.components.ItemJetpack; import zmaster587.advancedRocketry.item.components.ItemPressureTank; import zmaster587.advancedRocketry.item.components.ItemUpgrade; import zmaster587.advancedRocketry.item.tools.ItemBasicLaserGun; import zmaster587.advancedRocketry.mission.MissionGasCollection; import zmaster587.advancedRocketry.mission.MissionOreMining; import zmaster587.advancedRocketry.network.PacketAtmSync; import zmaster587.advancedRocketry.network.PacketBiomeIDChange; import zmaster587.advancedRocketry.network.PacketDimInfo; import zmaster587.advancedRocketry.network.PacketLaserGun; import zmaster587.advancedRocketry.network.PacketOxygenState; import zmaster587.advancedRocketry.network.PacketSatellite; import zmaster587.advancedRocketry.network.PacketSpaceStationInfo; import zmaster587.advancedRocketry.network.PacketStationUpdate; import zmaster587.advancedRocketry.network.PacketStellarInfo; import zmaster587.advancedRocketry.network.PacketStorageTileUpdate; import zmaster587.advancedRocketry.satellite.SatelliteBiomeChanger; import zmaster587.advancedRocketry.satellite.SatelliteComposition; import zmaster587.advancedRocketry.satellite.SatelliteDensity; import zmaster587.advancedRocketry.satellite.SatelliteEnergy; import zmaster587.advancedRocketry.satellite.SatelliteMassScanner; import zmaster587.advancedRocketry.satellite.SatelliteOptical; import zmaster587.advancedRocketry.satellite.SatelliteOreMapping; import zmaster587.advancedRocketry.stations.SpaceObject; import zmaster587.advancedRocketry.stations.SpaceObjectManager; import zmaster587.advancedRocketry.tile.Satellite.TileEntitySatelliteControlCenter; import zmaster587.advancedRocketry.tile.Satellite.TileSatelliteBuilder; import zmaster587.advancedRocketry.tile.*; import zmaster587.advancedRocketry.tile.cables.TileDataPipe; import zmaster587.advancedRocketry.tile.cables.TileEnergyPipe; import zmaster587.advancedRocketry.tile.cables.TileLiquidPipe; import zmaster587.advancedRocketry.tile.hatch.TileDataBus; import zmaster587.advancedRocketry.tile.hatch.TileSatelliteHatch; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityFuelingStation; import zmaster587.advancedRocketry.tile.infrastructure.TileEntityMoniteringStation; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketFluidUnloader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketLoader; import zmaster587.advancedRocketry.tile.infrastructure.TileRocketUnloader; import zmaster587.advancedRocketry.tile.multiblock.*; import zmaster587.advancedRocketry.tile.multiblock.energy.TileMicrowaveReciever; import zmaster587.advancedRocketry.tile.multiblock.machine.TileChemicalReactor; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCrystallizer; import zmaster587.advancedRocketry.tile.multiblock.machine.TileCuttingMachine; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectricArcFurnace; import zmaster587.advancedRocketry.tile.multiblock.machine.TileElectrolyser; import zmaster587.advancedRocketry.tile.multiblock.machine.TileLathe; import zmaster587.advancedRocketry.tile.multiblock.machine.TilePrecisionAssembler; import zmaster587.advancedRocketry.tile.multiblock.machine.TileRollingMachine; import zmaster587.advancedRocketry.tile.oxygen.TileCO2Scrubber; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenCharger; import zmaster587.advancedRocketry.tile.oxygen.TileOxygenVent; import zmaster587.advancedRocketry.tile.station.TileStationAltitudeController; import zmaster587.advancedRocketry.tile.station.TileDockingPort; import zmaster587.advancedRocketry.tile.station.TileLandingPad; import zmaster587.advancedRocketry.tile.station.TileStationGravityController; import zmaster587.advancedRocketry.tile.station.TileStationOrientationControl; import zmaster587.advancedRocketry.tile.station.TileWarpShipMonitor; import zmaster587.advancedRocketry.util.FluidColored; import zmaster587.advancedRocketry.util.OreGenProperties; import zmaster587.advancedRocketry.util.SealableBlockHandler; import zmaster587.advancedRocketry.util.XMLOreLoader; import zmaster587.advancedRocketry.util.XMLPlanetLoader; import zmaster587.advancedRocketry.util.XMLPlanetLoader.DimensionPropertyCoupling; import zmaster587.advancedRocketry.world.biome.BiomeGenAlienForest; import zmaster587.advancedRocketry.world.biome.BiomeGenCrystal; import zmaster587.advancedRocketry.world.biome.BiomeGenDeepSwamp; import zmaster587.advancedRocketry.world.biome.BiomeGenHotDryRock; import zmaster587.advancedRocketry.world.biome.BiomeGenMoon; import zmaster587.advancedRocketry.world.biome.BiomeGenMarsh; import zmaster587.advancedRocketry.world.biome.BiomeGenOceanSpires; import zmaster587.advancedRocketry.world.biome.BiomeGenSpace; import zmaster587.advancedRocketry.world.biome.BiomeGenStormland; import zmaster587.advancedRocketry.world.decoration.MapGenLander; import zmaster587.advancedRocketry.world.ore.OreGenerator; import zmaster587.advancedRocketry.world.provider.WorldProviderPlanet; import zmaster587.advancedRocketry.world.type.WorldTypePlanetGen; import zmaster587.advancedRocketry.world.type.WorldTypeSpace; import zmaster587.libVulpes.LibVulpes; import zmaster587.libVulpes.api.LibVulpesBlocks; import zmaster587.libVulpes.api.LibVulpesItems; import zmaster587.libVulpes.api.material.AllowedProducts; import zmaster587.libVulpes.api.material.MaterialRegistry; import zmaster587.libVulpes.api.material.MixedMaterial; import zmaster587.libVulpes.block.BlockAlphaTexture; import zmaster587.libVulpes.block.BlockMeta; import zmaster587.libVulpes.block.BlockTile; import zmaster587.libVulpes.block.multiblock.BlockMultiBlockComponentVisible; import zmaster587.libVulpes.block.multiblock.BlockMultiblockMachine; import zmaster587.libVulpes.network.PacketHandler; import zmaster587.libVulpes.network.PacketItemModifcation; import zmaster587.libVulpes.recipe.NumberedOreDictStack; import zmaster587.libVulpes.recipe.RecipesMachine; import zmaster587.libVulpes.tile.TileMaterial; import zmaster587.libVulpes.tile.multiblock.TileMultiBlock; import zmaster587.libVulpes.util.HashedBlockPosition; import zmaster587.libVulpes.util.InputSyncHandler; import zmaster587.libVulpes.util.SingleEntry; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @Mod(modid="advancedRocketry", name="Advanced Rocketry", version="%VERSION%", dependencies="required-after:libVulpes@[%LIBVULPESVERSION%,)") public class AdvancedRocketry { @SidedProxy(clientSide="zmaster587.advancedRocketry.client.ClientProxy", serverSide="zmaster587.advancedRocketry.common.CommonProxy") public static CommonProxy proxy; public final static String version = "%VERSION%"; @Instance(value = Constants.modId) public static AdvancedRocketry instance; public static WorldType planetWorldType; public static WorldType spaceWorldType; public static CompatibilityMgr compat = new CompatibilityMgr(); public static Logger logger = LogManager.getLogger(Constants.modId); private static Configuration config; private static final String BIOMECATETORY = "Biomes"; private boolean resetFromXml; String[] sealableBlockWhiteList, breakableTorches, harvestableGasses, entityList, asteriodOres, geodeOres, orbitalLaserOres; //static { // FluidRegistry.enableUniversalBucket(); // Must be called before preInit public static MaterialRegistry materialRegistry = new MaterialRegistry(); private HashMap<AllowedProducts, HashSet<String>> modProducts = new HashMap<AllowedProducts, HashSet<String>>(); private static CreativeTabs tabAdvRocketry = new CreativeTabs("advancedRocketry") { @Override public Item getTabIconItem() { return AdvancedRocketryItems.itemSatelliteIdChip; } }; @EventHandler public void preInit(FMLPreInitializationEvent event) { //Init API DimensionManager.planetWorldProvider = WorldProviderPlanet.class; AdvancedRocketryAPI.atomsphereSealHandler = SealableBlockHandler.INSTANCE; ((SealableBlockHandler)AdvancedRocketryAPI.atomsphereSealHandler).loadDefaultData(); config = new Configuration(new File(event.getModConfigurationDirectory(), "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/advancedRocketry.cfg")); config.load(); final String oreGen = "Ore Generation"; final String ROCKET = "Rockets"; final String MOD_INTERACTION = "Mod Interaction"; final String PLANET = "Planet"; final String ASTEROID = "Asteroid"; final String GAS_MINING = "GasMining"; final String PERFORMANCE = "Performance"; AtmosphereVacuum.damageValue = (int) config.get(Configuration.CATEGORY_GENERAL, "vacuumDamage", 1, "Amount of damage taken every second in a vacuum").getInt(); zmaster587.advancedRocketry.api.Configuration.buildSpeedMultiplier = (float) config.get(Configuration.CATEGORY_GENERAL, "buildSpeedMultiplier", 1f, "Multiplier for the build speed of the Rocket Builder (0.5 is twice as fast 2 is half as fast").getDouble(); zmaster587.advancedRocketry.api.Configuration.spaceDimId = config.get(Configuration.CATEGORY_GENERAL,"spaceStationId" , -2,"Dimension ID to use for space stations").getInt(); zmaster587.advancedRocketry.api.Configuration.enableOxygen = config.get(Configuration.CATEGORY_GENERAL, "EnableAtmosphericEffects", true, "If true, allows players being hurt due to lack of oxygen and allows effects from non-standard atmosphere types").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods = config.get(Configuration.CATEGORY_GENERAL, "makeMaterialsForOtherMods", true, "If true the machines from AdvancedRocketry will produce things like plates/rods for other mods even if Advanced Rocketry itself does not use the material (This can increase load time)").getBoolean(); zmaster587.advancedRocketry.api.Configuration.scrubberRequiresCartrige = config.get(Configuration.CATEGORY_GENERAL, "scrubberRequiresCartrige", true, "If true the Oxygen scrubbers require a consumable carbon collection cartridge").getBoolean(); zmaster587.advancedRocketry.api.Configuration.enableLaserDrill = config.get(Configuration.CATEGORY_GENERAL, "EnableLaserDrill", true, "Enables the laser drill machine").getBoolean(); zmaster587.advancedRocketry.api.Configuration.spaceLaserPowerMult = (float)config.get(Configuration.CATEGORY_GENERAL, "LaserDrillPowerMultiplier", 1d, "Power multiplier for the laser drill machine").getDouble(); zmaster587.advancedRocketry.api.Configuration.lowGravityBoots = config.get(Configuration.CATEGORY_GENERAL, "lowGravityBoots", false, "If true the boots only protect the player on planets with low gravity").getBoolean(); zmaster587.advancedRocketry.api.Configuration.jetPackThrust = (float)config.get(Configuration.CATEGORY_GENERAL, "jetPackForce", 1.3, "Amount of force the jetpack provides with respect to gravity, 1 is the same acceleration as caused by Earth's gravity, 2 is 2x the acceleration caused by Earth's gravity, etc. To make jetpack only work on low gravity planets, simply set it to a value less than 1").getDouble(); zmaster587.advancedRocketry.api.Configuration.enableTerraforming = config.get(Configuration.CATEGORY_GENERAL, "EnableTerraforming", true,"Enables terraforming items and blocks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.spaceSuitOxygenTime = config.get(Configuration.CATEGORY_GENERAL, "spaceSuitO2Buffer", 30, "Maximum time in minutes that the spacesuit's internal buffer can store O2 for").getInt(); zmaster587.advancedRocketry.api.Configuration.travelTimeMultiplier = (float)config.get(Configuration.CATEGORY_GENERAL, "warpTravelTime", 1f, "Multiplier for warp travel time").getDouble(); zmaster587.advancedRocketry.api.Configuration.maxBiomesPerPlanet = config.get(Configuration.CATEGORY_GENERAL, "maxBiomesPerPlanet", 5, "Maximum unique biomes per planet, -1 to disable").getInt(); zmaster587.advancedRocketry.api.Configuration.allowTerraforming = config.get(Configuration.CATEGORY_GENERAL, "allowTerraforming", false, "EXPERIMENTAL: If set to true allows contruction and usage of the terraformer. This is known to cause strange world generation after successful terraform").getBoolean(); zmaster587.advancedRocketry.api.Configuration.terraformingBlockSpeed = config.get(Configuration.CATEGORY_GENERAL, "biomeUpdateSpeed", 1, "How many blocks have the biome changed per tick. Large numbers can slow the server down", Integer.MAX_VALUE, 1).getInt(); zmaster587.advancedRocketry.api.Configuration.terraformSpeed = config.get(Configuration.CATEGORY_GENERAL, "terraformMult", 1f, "Multplier for terraforming speed").getDouble(); zmaster587.advancedRocketry.api.Configuration.terraformRequiresFluid = config.get(Configuration.CATEGORY_GENERAL, "TerraformerRequiresFluids", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.canPlayerRespawnInSpace = config.get(Configuration.CATEGORY_GENERAL, "allowPlanetRespawn", false, "If true players will respawn near beds on planets IF the spawn location is in a breathable atmosphere").getBoolean(); zmaster587.advancedRocketry.api.Configuration.solarGeneratorMult = config.get(Configuration.CATEGORY_GENERAL, "solarGeneratorMultiplier", 1, "Amount of power per tick the solar generator should produce").getInt(); DimensionManager.dimOffset = config.getInt("minDimension", PLANET, 2, -127, 8000, "Dimensions including and after this number are allowed to be made into planets"); zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes = config.getBoolean("blackListVanillaBiomes", PLANET, false, "Prevents any vanilla biomes from spawning on planets"); zmaster587.advancedRocketry.api.Configuration.overrideGCAir = config.get(MOD_INTERACTION, "OverrideGCAir", true, "If true Galaciticcraft's air will be disabled entirely requiring use of Advanced Rocketry's Oxygen system on GC planets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.fuelPointsPerDilithium = config.get(Configuration.CATEGORY_GENERAL, "pointsPerDilithium", 500, "How many units of fuel should each Dilithium Crystal give to warp ships", 1, 1000).getInt(); zmaster587.advancedRocketry.api.Configuration.electricPlantsSpawnLightning = config.get(Configuration.CATEGORY_GENERAL, "electricPlantsSpawnLightning", true, "Should Electric Mushrooms be able to spawn lightning").getBoolean(); zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood = config.get(Configuration.CATEGORY_GENERAL, "sawMillCutVanillaWood", true, "Should the cutting machine be able to cut vanilla wood into planks").getBoolean(); zmaster587.advancedRocketry.api.Configuration.automaticRetroRockets = config.get(ROCKET, "autoRetroRockets", true, "Setting to false will disable the retrorockets that fire automatically on reentry on both player and automated rockets").getBoolean(); zmaster587.advancedRocketry.api.Configuration.atmosphereHandleBitMask = config.get(PERFORMANCE, "atmosphereCalculationMethod", 0, "BitMask: 0: no threading, radius based; 1: threading, radius based (EXP); 2: no threading volume based; 3: threading volume based (EXP)").getInt(); zmaster587.advancedRocketry.api.Configuration.oxygenVentSize = config.get(PERFORMANCE, "oxygenVentSize", 32, "Radius of the O2 vent. if atmosphereCalculationMethod is 2 or 3 then max volume is calculated from this radius. WARNING: larger numbers can lead to lag").getInt(); zmaster587.advancedRocketry.api.Configuration.advancedVFX = config.get(PERFORMANCE, "advancedVFX", true, "Advanced visual effects").getBoolean(); zmaster587.advancedRocketry.api.Configuration.gasCollectionMult = config.get(GAS_MINING, "gasMissionMultiplier", 1.0, "Multiplier for the amount of time gas collection missions take").getDouble(); zmaster587.advancedRocketry.api.Configuration.asteroidMiningMult = config.get(ASTEROID, "miningMissionMultiplier", 1.0, "Multiplier changing how much total material is brought back from a mining mission").getDouble(); zmaster587.advancedRocketry.api.Configuration.asteroidMiningTimeMult = config.get(ASTEROID, "miningMissionTmeMultiplier", 1.0, "Multiplier changing how long a mining mission takes").getDouble(); asteriodOres = config.get(ASTEROID, "standardOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone"}, "List of oredictionary names of ores allowed to spawn in asteriods").getStringList(); zmaster587.advancedRocketry.api.Configuration.asteriodOresBlackList = config.get(ASTEROID, "standardOres_blacklist", false, "True if the ores in standardOres should a be blacklist, false for whitelist").getBoolean(); geodeOres = config.get(oreGen, "geodeOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone"}, "List of oredictionary names of ores allowed to spawn in geodes").getStringList(); zmaster587.advancedRocketry.api.Configuration.geodeOresBlackList = config.get(oreGen, "geodeOres_blacklist", false, "True if the ores in geodeOres should be a blacklist, false for whitelist").getBoolean(); orbitalLaserOres = config.get(Configuration.CATEGORY_GENERAL, "laserDrillOres", new String[] {"oreIron", "oreGold", "oreCopper", "oreTin", "oreRedstone", "oreDiamond"}, "List of oredictionary names of ores allowed to be mined by the laser drill if surface drilling is disabled").getStringList(); zmaster587.advancedRocketry.api.Configuration.laserDrillOresBlackList = config.get(Configuration.CATEGORY_GENERAL, "laserDrillOres_blacklist", false, "True if the ores in laserDrillOres should be a blacklist, false for whitelist").getBoolean(); zmaster587.advancedRocketry.api.Configuration.laserDrillPlanet = config.get(Configuration.CATEGORY_GENERAL, "laserDrillPlanet", false, "If true the orbital laser will actually mine blocks on the planet below").getBoolean(); resetFromXml = config.getBoolean("resetPlanetsFromXML", Configuration.CATEGORY_GENERAL, false, "setting this to true will DELETE existing advancedrocketry planets and regen the solar system from the advanced planet XML file, satellites orbiting the overworld will remain intact and stations will be moved to the overworld."); //Reset to false config.get(Configuration.CATEGORY_GENERAL, "resetPlanetsFromXML",false).set(false); //Client zmaster587.advancedRocketry.api.Configuration.rocketRequireFuel = config.get(ROCKET, "rocketsRequireFuel", true, "Set to false if rockets should not require fuel to fly").getBoolean(); zmaster587.advancedRocketry.api.Configuration.rocketThrustMultiplier = config.get(ROCKET, "thrustMultiplier", 1f, "Multiplier for per-engine thrust").getDouble(); zmaster587.advancedRocketry.api.Configuration.fuelCapacityMultiplier = config.get(ROCKET, "fuelCapacityMultiplier", 1f, "Multiplier for per-tank capacity").getDouble(); //Copper Config zmaster587.advancedRocketry.api.Configuration.generateCopper = config.get(oreGen, "GenerateCopper", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.copperClumpSize = config.get(oreGen, "CopperPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.copperPerChunk = config.get(oreGen, "CopperPerChunk", 10).getInt(); //Tin Config zmaster587.advancedRocketry.api.Configuration.generateTin = config.get(oreGen, "GenerateTin", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.tinClumpSize = config.get(oreGen, "TinPerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.tinPerChunk = config.get(oreGen, "TinPerChunk", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateDilithium = config.get(oreGen, "generateDilithium", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.dilithiumClumpSize = config.get(oreGen, "DilithiumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunk = config.get(oreGen, "DilithiumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.dilithiumPerChunkMoon = config.get(oreGen, "DilithiumPerChunkLuna", 10).getInt(); zmaster587.advancedRocketry.api.Configuration.generateAluminum = config.get(oreGen, "generateAluminum", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.aluminumClumpSize = config.get(oreGen, "AluminumPerClump", 16).getInt(); zmaster587.advancedRocketry.api.Configuration.aluminumPerChunk = config.get(oreGen, "AluminumPerChunk", 1).getInt(); zmaster587.advancedRocketry.api.Configuration.generateRutile = config.get(oreGen, "GenerateRutile", true).getBoolean(); zmaster587.advancedRocketry.api.Configuration.rutileClumpSize = config.get(oreGen, "RutilePerClump", 6).getInt(); zmaster587.advancedRocketry.api.Configuration.rutilePerChunk = config.get(oreGen, "RutilePerChunk", 6).getInt(); sealableBlockWhiteList = config.getStringList(Configuration.CATEGORY_GENERAL, "sealableBlockWhiteList", new String[] {}, "Mod:Blockname for example \"minecraft:chest\""); breakableTorches = config.getStringList("torchBlocks", Configuration.CATEGORY_GENERAL, new String[] {}, "Mod:Blockname for example \"minecraft:chest\""); harvestableGasses = config.getStringList("harvestableGasses", GAS_MINING, new String[] {}, "list of fluid names that can be harvested as Gas"); entityList = config.getStringList("entityAtmBypass", Configuration.CATEGORY_GENERAL, new String[] {}, "list entities which should not be affected by atmosphere properties"); //Satellite config zmaster587.advancedRocketry.api.Configuration.microwaveRecieverMulitplier = 10*(float)config.get(Configuration.CATEGORY_GENERAL, "MicrowaveRecieverMulitplier", 1f, "Multiplier for the amount of energy produced by the microwave reciever").getDouble(); String str[] = config.getStringList("spaceLaserDimIdBlackList", Configuration.CATEGORY_GENERAL, new String[] {}, "Laser drill will not mine these dimension"); //Load laser dimid blacklists for(String s : str) { try { zmaster587.advancedRocketry.api.Configuration.laserBlackListDims.add(Integer.parseInt(s)); } catch (NumberFormatException e) { logger.warn("Invalid number \"" + s + "\" for laser dimid blacklist"); } } //Load client and UI positioning stuff proxy.loadUILayout(config); config.save(); //Register cap events MinecraftForge.EVENT_BUS.register(new CapabilityProtectiveArmor()); //Register Packets PacketHandler.INSTANCE.addDiscriminator(PacketDimInfo.class); PacketHandler.INSTANCE.addDiscriminator(PacketSatellite.class); PacketHandler.INSTANCE.addDiscriminator(PacketStellarInfo.class); PacketHandler.INSTANCE.addDiscriminator(PacketItemModifcation.class); PacketHandler.INSTANCE.addDiscriminator(PacketOxygenState.class); PacketHandler.INSTANCE.addDiscriminator(PacketStationUpdate.class); PacketHandler.INSTANCE.addDiscriminator(PacketSpaceStationInfo.class); PacketHandler.INSTANCE.addDiscriminator(PacketAtmSync.class); PacketHandler.INSTANCE.addDiscriminator(PacketBiomeIDChange.class); PacketHandler.INSTANCE.addDiscriminator(PacketStorageTileUpdate.class); PacketHandler.INSTANCE.addDiscriminator(PacketLaserGun.class); //if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) MinecraftForge.EVENT_BUS.register(this); SatelliteRegistry.registerSatellite("optical", SatelliteOptical.class); SatelliteRegistry.registerSatellite("solar", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("density", SatelliteDensity.class); SatelliteRegistry.registerSatellite("composition", SatelliteComposition.class); SatelliteRegistry.registerSatellite("mass", SatelliteMassScanner.class); SatelliteRegistry.registerSatellite("asteroidMiner", MissionOreMining.class); SatelliteRegistry.registerSatellite("gasMining", MissionGasCollection.class); SatelliteRegistry.registerSatellite("solarEnergy", SatelliteEnergy.class); SatelliteRegistry.registerSatellite("oreScanner", SatelliteOreMapping.class); SatelliteRegistry.registerSatellite("biomeChanger", SatelliteBiomeChanger.class); AdvancedRocketryBlocks.blocksGeode = new Block(MaterialGeode.geode).setUnlocalizedName("geode").setCreativeTab(LibVulpes.tabLibVulpesOres).setHardness(6f).setResistance(2000F); AdvancedRocketryBlocks.blocksGeode.setHarvestLevel("jackhammer", 2); AdvancedRocketryBlocks.blockLaunchpad = new BlockLinkedHorizontalTexture(Material.ROCK).setUnlocalizedName("pad").setCreativeTab(tabAdvRocketry).setHardness(2f).setResistance(10f); AdvancedRocketryBlocks.blockStructureTower = new BlockAlphaTexture(Material.ROCK).setUnlocalizedName("structuretower").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockGenericSeat = new BlockSeat(Material.CLOTH).setUnlocalizedName("seat").setCreativeTab(tabAdvRocketry).setHardness(0.5f); AdvancedRocketryBlocks.blockEngine = new BlockRocketMotor(Material.ROCK).setUnlocalizedName("rocket").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockAdvEngine = new BlockRocketMotor(Material.ROCK).setUnlocalizedName("advRocket").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockFuelTank = new BlockFuelTank(Material.ROCK).setUnlocalizedName("fuelTank").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockSawBlade = new BlockRotatableModel(Material.ROCK).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sawBlade").setHardness(2f); AdvancedRocketryBlocks.blockMotor = new BlockRotatableModel(Material.ROCK).setCreativeTab(tabAdvRocketry).setUnlocalizedName("motor").setHardness(2f); AdvancedRocketryBlocks.blockConcrete = new Block(Material.ROCK).setUnlocalizedName("concrete").setCreativeTab(tabAdvRocketry).setHardness(3f).setResistance(16f); AdvancedRocketryBlocks.blockPlatePress = new BlockPress().setUnlocalizedName("blockHandPress").setCreativeTab(tabAdvRocketry).setHardness(2f); AdvancedRocketryBlocks.blockAirLock = new BlockDoor2(Material.ROCK).setUnlocalizedName("smallAirlockDoor").setHardness(3f).setResistance(8f); AdvancedRocketryBlocks.blockLandingPad = new BlockLandingPad(Material.ROCK).setUnlocalizedName("dockingPad").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenDetection = new BlockRedstoneEmitter(Material.ROCK,"advancedrocketry:atmosphereDetector_active").setUnlocalizedName("atmosphereDetector").setHardness(3f).setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockOxygenScrubber = new BlockTile(TileCO2Scrubber.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("scrubber").setHardness(3f); AdvancedRocketryBlocks.blockUnlitTorch = new BlockTorchUnlit().setHardness(0.0F).setUnlocalizedName("unlittorch"); AdvancedRocketryBlocks.blockVitrifiedSand = new Block(Material.SAND).setUnlocalizedName("vitrifiedSand").setCreativeTab(CreativeTabs.BUILDING_BLOCKS).setHardness(0.5F); AdvancedRocketryBlocks.blockCharcoalLog = new BlockCharcoalLog().setUnlocalizedName("charcoallog").setCreativeTab(CreativeTabs.BUILDING_BLOCKS); AdvancedRocketryBlocks.blockElectricMushroom = new BlockElectricMushroom().setUnlocalizedName("electricMushroom").setCreativeTab(tabAdvRocketry).setHardness(0.0F); AdvancedRocketryBlocks.blockCrystal = new BlockCrystal().setUnlocalizedName("crystal").setCreativeTab(LibVulpes.tabLibVulpesOres).setHardness(2f); AdvancedRocketryBlocks.blockOrientationController = new BlockTile(TileStationOrientationControl.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("orientationControl").setHardness(3f); AdvancedRocketryBlocks.blockGravityController = new BlockTile(TileStationGravityController.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("gravityControl").setHardness(3f); AdvancedRocketryBlocks.blockAltitudeController = new BlockTile(TileStationAltitudeController.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setUnlocalizedName("altitudeController").setHardness(3f); AdvancedRocketryBlocks.blockOxygenCharger = new BlockHalfTile(TileOxygenCharger.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("oxygenCharger").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockOxygenVent = new BlockTile(TileOxygenVent.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("oxygenVent").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCircleLight = new Block(Material.IRON).setUnlocalizedName("circleLight").setCreativeTab(tabAdvRocketry).setHardness(2f).setLightLevel(1f); AdvancedRocketryBlocks.blockRocketBuilder = new BlockTile(TileRocketBuilder.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("rocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockDeployableRocketBuilder = new BlockTile(TileStationDeployedAssembler.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("deployableRocketAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockStationBuilder = new BlockTile(TileStationBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("stationAssembler").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockFuelingStation = new BlockTileRedstoneEmitter(TileEntityFuelingStation.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("fuelStation").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMonitoringStation = new BlockTileNeighborUpdate(TileEntityMoniteringStation.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMonitoringStation.setUnlocalizedName("monitoringstation"); AdvancedRocketryBlocks.blockWarpShipMonitor = new BlockWarpShipMonitor(TileWarpShipMonitor.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockWarpShipMonitor.setUnlocalizedName("stationmonitor"); AdvancedRocketryBlocks.blockSatelliteBuilder = new BlockMultiblockMachine(TileSatelliteBuilder.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSatelliteBuilder.setUnlocalizedName("satelliteBuilder"); AdvancedRocketryBlocks.blockSatelliteControlCenter = new BlockTile(TileEntitySatelliteControlCenter.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSatelliteControlCenter.setUnlocalizedName("satelliteMonitor"); AdvancedRocketryBlocks.blockMicrowaveReciever = new BlockMultiblockMachine(TileMicrowaveReciever.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMicrowaveReciever.setUnlocalizedName("microwaveReciever"); //Arcfurnace AdvancedRocketryBlocks.blockArcFurnace = new BlockMultiblockMachine(TileElectricArcFurnace.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("electricArcFurnace").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockMoonTurf = new BlockPlanetSoil().setMapColor(MapColor.SNOW).setHardness(0.5F).setUnlocalizedName("turf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockHotTurf = new BlockPlanetSoil().setMapColor(MapColor.NETHERRACK).setHardness(0.5F).setUnlocalizedName("hotDryturf").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockLoader = new BlockARHatch(Material.ROCK).setUnlocalizedName("loader").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienWood = new BlockAlienWood().setUnlocalizedName("log").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienLeaves = new BlockAlienLeaves().setUnlocalizedName("leaves2").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAlienSapling = new BlockAlienSapling().setUnlocalizedName("sapling").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockLightSource = new BlockLightSource(); AdvancedRocketryBlocks.blockBlastBrick = new BlockMultiBlockComponentVisible(Material.ROCK).setCreativeTab(tabAdvRocketry).setUnlocalizedName("blastBrick").setHardness(3F).setResistance(15F); AdvancedRocketryBlocks.blockQuartzCrucible = new BlockQuartzCrucible().setUnlocalizedName("qcrucible"); AdvancedRocketryBlocks.blockAstroBed = new BlockAstroBed().setHardness(0.2F).setUnlocalizedName("astroBed"); AdvancedRocketryBlocks.blockPrecisionAssembler = new BlockMultiblockMachine(TilePrecisionAssembler.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("precisionAssemblingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCuttingMachine = new BlockMultiblockMachine(TileCuttingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("cuttingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockCrystallizer = new BlockMultiblockMachine(TileCrystallizer.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("Crystallizer").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockWarpCore = new BlockWarpCore(TileWarpCore.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("warpCore").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockChemicalReactor = new BlockMultiblockMachine(TileChemicalReactor.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("chemreactor").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockLathe = new BlockMultiblockMachine(TileLathe.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("lathe").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockRollingMachine = new BlockMultiblockMachine(TileRollingMachine.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("rollingMachine").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockElectrolyser = new BlockMultiblockMachine(TileElectrolyser.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("electrolyser").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockAtmosphereTerraformer = new BlockMultiblockMachine(TileAtmosphereTerraformer.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("atmosphereTerraformer").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPlanetAnalyser = new BlockMultiblockMachine(TileAstrobodyDataProcessor.class, GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("planetanalyser").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockObservatory = (BlockMultiblockMachine) new BlockMultiblockMachine(TileObservatory.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("observatory").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockGuidanceComputer = new BlockTile(TileGuidanceComputer.class,GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("guidanceComputer").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPlanetSelector = new BlockTile(TilePlanetSelector.class,GuiHandler.guiId.MODULARFULLSCREEN.ordinal()).setUnlocalizedName("planetSelector").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockBiomeScanner = new BlockMultiblockMachine(TileBiomeScanner.class,GuiHandler.guiId.MODULARNOINV.ordinal()).setUnlocalizedName("biomeScanner").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockDrill = new BlockMiningDrill().setUnlocalizedName("drill").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSuitWorkStation = new BlockTile(TileSuitWorkStation.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("suitWorkStation").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockRailgun = new BlockMultiblockMachine(TileRailgun.class, GuiHandler.guiId.MODULAR.ordinal()).setUnlocalizedName("railgun").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockIntake = new BlockIntake(Material.IRON).setUnlocalizedName("gasIntake").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockPressureTank = new BlockPressurizedFluidTank(Material.IRON).setUnlocalizedName("pressurizedTank").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSolarPanel = new Block(Material.IRON).setUnlocalizedName("solarPanel").setCreativeTab(tabAdvRocketry).setHardness(3f); AdvancedRocketryBlocks.blockSolarGenerator = new BlockSolarGenerator(TileSolarPanel.class, GuiHandler.guiId.MODULAR.ordinal()).setCreativeTab(tabAdvRocketry).setHardness(3f).setUnlocalizedName("solarGenerator"); AdvancedRocketryBlocks.blockDockingPort = new BlockStationModuleDockingPort(Material.IRON).setUnlocalizedName("stationMarker").setCreativeTab(tabAdvRocketry).setHardness(3f); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { AdvancedRocketryBlocks.blockSpaceLaser = new BlockLaser(); AdvancedRocketryBlocks.blockSpaceLaser.setCreativeTab(tabAdvRocketry); } //Fluid Registration AdvancedRocketryFluids.fluidOxygen = new FluidColored("oxygen",0x8f94b9).setUnlocalizedName("oxygen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidOxygen)) { AdvancedRocketryFluids.fluidOxygen = FluidRegistry.getFluid("oxygen"); } AdvancedRocketryFluids.fluidHydrogen = new FluidColored("hydrogen",0xdbc1c1).setUnlocalizedName("hydrogen").setGaseous(true); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidHydrogen)) { AdvancedRocketryFluids.fluidHydrogen = FluidRegistry.getFluid("hydrogen"); } AdvancedRocketryFluids.fluidRocketFuel = new FluidColored("rocketFuel", 0xe5d884).setUnlocalizedName("rocketFuel").setGaseous(false); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidRocketFuel)) { AdvancedRocketryFluids.fluidRocketFuel = FluidRegistry.getFluid("rocketFuel"); } AdvancedRocketryFluids.fluidNitrogen = new FluidColored("nitrogen", 0x97a7e7); if(!FluidRegistry.registerFluid(AdvancedRocketryFluids.fluidNitrogen)) { AdvancedRocketryFluids.fluidNitrogen = FluidRegistry.getFluid("nitrogen"); } AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidNitrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidHydrogen); AtmosphereRegister.getInstance().registerHarvestableFluid(AdvancedRocketryFluids.fluidOxygen); AdvancedRocketryBlocks.blockOxygenFluid = new BlockFluid(AdvancedRocketryFluids.fluidOxygen, Material.WATER).setUnlocalizedName("oxygenFluidBlock").setCreativeTab(CreativeTabs.MISC); AdvancedRocketryBlocks.blockHydrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidHydrogen, Material.WATER).setUnlocalizedName("hydrogenFluidBlock").setCreativeTab(CreativeTabs.MISC); AdvancedRocketryBlocks.blockFuelFluid = new BlockFluid(AdvancedRocketryFluids.fluidRocketFuel, new MaterialLiquid(MapColor.YELLOW)).setUnlocalizedName("rocketFuelBlock").setCreativeTab(CreativeTabs.MISC); AdvancedRocketryBlocks.blockNitrogenFluid = new BlockFluid(AdvancedRocketryFluids.fluidNitrogen, Material.WATER).setUnlocalizedName("nitrogenFluidBlock").setCreativeTab(CreativeTabs.MISC); //Cables AdvancedRocketryBlocks.blockFluidPipe = new BlockLiquidPipe(Material.IRON).setUnlocalizedName("liquidPipe").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockDataPipe = new BlockDataCable(Material.IRON).setUnlocalizedName("dataPipe").setCreativeTab(tabAdvRocketry); AdvancedRocketryBlocks.blockEnergyPipe = new BlockEnergyCable(Material.IRON).setUnlocalizedName("energyPipe").setCreativeTab(tabAdvRocketry); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDataPipe.setRegistryName("dataPipe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockEnergyPipe.setRegistryName("energyPipe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFluidPipe.setRegistryName("liquidPipe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLaunchpad.setRegistryName("launchpad")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRocketBuilder.setRegistryName("rocketBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockStructureTower.setRegistryName("structureTower")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGenericSeat.setRegistryName("seat")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockEngine.setRegistryName("rocketmotor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAdvEngine.setRegistryName("advRocketmotor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelTank.setRegistryName("fuelTank")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelingStation.setRegistryName("fuelingStation")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMonitoringStation.setRegistryName("monitoringStation")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSatelliteBuilder.setRegistryName("satelliteBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMoonTurf.setRegistryName("moonTurf")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockHotTurf.setRegistryName("hotTurf")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLoader.setRegistryName("loader"), ItemBlockMeta.class, false); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPrecisionAssembler.setRegistryName("precisionassemblingmachine")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockBlastBrick.setRegistryName("blastBrick")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockQuartzCrucible.setRegistryName("quartzcrucible")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCrystallizer.setRegistryName("crystallizer")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCuttingMachine.setRegistryName("cuttingMachine")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienWood.setRegistryName("alienWood")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienLeaves.setRegistryName("alienLeaves")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAlienSapling.setRegistryName("alienSapling")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockObservatory.setRegistryName("observatory")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockConcrete.setRegistryName("concrete")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlanetSelector.setRegistryName("planetSelector")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSatelliteControlCenter.setRegistryName("satelliteControlCenter")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlanetAnalyser.setRegistryName("planetAnalyser")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGuidanceComputer.setRegistryName("guidanceComputer")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockArcFurnace.setRegistryName("arcFurnace")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSawBlade.setRegistryName("sawBlade")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMotor.setRegistryName("motor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLathe.setRegistryName("lathe")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRollingMachine.setRegistryName("rollingMachine")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPlatePress.setRegistryName("platePress")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockStationBuilder.setRegistryName("stationBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockElectrolyser.setRegistryName("electrolyser")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockChemicalReactor.setRegistryName("chemicalReactor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenScrubber.setRegistryName("oxygenScrubber")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenVent.setRegistryName("oxygenVent")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenCharger.setRegistryName("oxygenCharger")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAirLock.setRegistryName("airlock_door")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLandingPad.setRegistryName("landingPad")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockWarpCore.setRegistryName("warpCore")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockWarpShipMonitor.setRegistryName("warpMonitor")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenDetection.setRegistryName("oxygenDetection")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockUnlitTorch.setRegistryName("unlitTorch")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blocksGeode.setRegistryName("geode")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOxygenFluid.setRegistryName("oxygenFluid")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockHydrogenFluid.setRegistryName("hydrogenFluid")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockFuelFluid.setRegistryName("rocketFuel")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockNitrogenFluid.setRegistryName("nitrogenFluid")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockVitrifiedSand.setRegistryName("vitrifiedSand")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCharcoalLog.setRegistryName("charcoalLog")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockElectricMushroom.setRegistryName("electricMushroom")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCrystal.setRegistryName("crystal"), ItemBlockCrystal.class, true ); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockOrientationController.setRegistryName("orientationController")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockGravityController.setRegistryName("gravityController")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDrill.setRegistryName("drill")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockMicrowaveReciever.setRegistryName("microwaveReciever")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockLightSource.setRegistryName("lightSource")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSolarPanel.setRegistryName("solarPanel")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSuitWorkStation.setRegistryName("suitWorkStation")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockBiomeScanner.setRegistryName("biomeScanner")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAtmosphereTerraformer.setRegistryName("terraformer")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDeployableRocketBuilder.setRegistryName("deployableRocketBuilder")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockPressureTank.setRegistryName("liquidTank")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockIntake.setRegistryName("intake")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockCircleLight.setRegistryName("circleLight")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSolarGenerator.setRegistryName("solarGenerator")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockDockingPort.setRegistryName("stationMarker")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAltitudeController.setRegistryName("altitudeController")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockRailgun .setRegistryName("railgun")); LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockAstroBed .setRegistryName("astroBed")); //TODO, use different mechanism to enable/disable drill if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) LibVulpesBlocks.registerBlock(AdvancedRocketryBlocks.blockSpaceLaser.setRegistryName("spaceLaser")); AdvancedRocketryItems.itemWafer = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:wafer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCircuitPlate = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:circuitplate").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemIC = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:circuitIC").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemMisc = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:miscpart").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSawBlade = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:sawBlade").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStationChip = new ItemStationChip().setUnlocalizedName("stationChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemAsteroidChip = new ItemAsteroidChip().setUnlocalizedName("asteroidChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSpaceStation = new ItemPackedStructure().setUnlocalizedName("station"); AdvancedRocketryItems.itemSmallAirlockDoor = new ItemDoor(AdvancedRocketryBlocks.blockAirLock).setUnlocalizedName("smallAirlock").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemCarbonScrubberCartridge = new Item().setMaxDamage(172800).setUnlocalizedName("carbonScrubberCartridge").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemLens = new ItemIngredient(1).setUnlocalizedName("advancedrocketry:lens").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePowerSource = new ItemIngredient(2).setUnlocalizedName("advancedrocketry:satellitePowerSource").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellitePrimaryFunction = new ItemIngredient(6).setUnlocalizedName("advancedrocketry:satellitePrimaryFunction").setCreativeTab(tabAdvRocketry); //TODO: move registration in the case we have more than one chip type AdvancedRocketryItems.itemDataUnit = new ItemData().setUnlocalizedName("advancedrocketry:dataUnit").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemOreScanner = new ItemOreScanner().setUnlocalizedName("OreScanner").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemQuartzCrucible = new ItemBlock(AdvancedRocketryBlocks.blockQuartzCrucible).setUnlocalizedName("qcrucible").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemSatellite = new ItemSatellite().setUnlocalizedName("satellite"); AdvancedRocketryItems.itemSatelliteIdChip = new ItemSatelliteIdentificationChip().setUnlocalizedName("satelliteIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemPlanetIdChip = new ItemPlanetIdentificationChip().setUnlocalizedName("planetIdChip").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemBiomeChanger = new ItemBiomeChanger().setUnlocalizedName("biomeChanger").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemBasicLaserGun = new ItemBasicLaserGun().setUnlocalizedName("basicLaserGun").setCreativeTab(tabAdvRocketry); //Fluids AdvancedRocketryItems.itemBucketRocketFuel = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketRocketFuel").setContainerItem(Items.BUCKET); AdvancedRocketryItems.itemBucketNitrogen = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketNitrogen").setContainerItem(Items.BUCKET); AdvancedRocketryItems.itemBucketHydrogen = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketHydrogen").setContainerItem(Items.BUCKET); AdvancedRocketryItems.itemBucketOxygen = new Item().setCreativeTab(LibVulpes.tabLibVulpesOres).setUnlocalizedName("bucketOxygen").setContainerItem(Items.BUCKET); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidHydrogen); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidNitrogen); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidOxygen); //FluidRegistry.addBucketForFluid(AdvancedRocketryFluids.fluidRocketFuel); //Suit Component Registration AdvancedRocketryItems.itemJetpack = new ItemJetpack().setCreativeTab(tabAdvRocketry).setUnlocalizedName("jetPack"); AdvancedRocketryItems.itemPressureTank = new ItemPressureTank(4, 1000).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:pressureTank"); AdvancedRocketryItems.itemUpgrade = new ItemUpgrade(5).setCreativeTab(tabAdvRocketry).setUnlocalizedName("advancedrocketry:itemUpgrade"); AdvancedRocketryItems.itemAtmAnalyser = new ItemAtmosphereAnalzer().setCreativeTab(tabAdvRocketry).setUnlocalizedName("atmAnalyser"); //Armor registration AdvancedRocketryItems.itemSpaceSuit_Helmet = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.HEAD).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceHelmet"); AdvancedRocketryItems.itemSpaceSuit_Chest = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.CHEST).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceChest"); AdvancedRocketryItems.itemSpaceSuit_Leggings = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.LEGS).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceLeggings"); AdvancedRocketryItems.itemSpaceSuit_Boots = new ItemSpaceArmor(AdvancedRocketryItems.spaceSuit, EntityEquipmentSlot.FEET).setCreativeTab(tabAdvRocketry).setUnlocalizedName("spaceBoots"); AdvancedRocketryItems.itemSealDetector = new ItemSealDetector().setMaxStackSize(1).setCreativeTab(tabAdvRocketry).setUnlocalizedName("sealDetector"); //Tools AdvancedRocketryItems.itemJackhammer = new ItemJackHammer(ToolMaterial.DIAMOND).setUnlocalizedName("jackhammer").setCreativeTab(tabAdvRocketry); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("jackhammer", 3); AdvancedRocketryItems.itemJackhammer.setHarvestLevel("pickaxe", 3); //Note: not registered AdvancedRocketryItems.itemAstroBed = new ItemAstroBed(); //Register Satellite Properties SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOptical.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteComposition.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteMassScanner.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteEnergy.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteOreMapping.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5), new SatelliteProperties().setSatelliteType(SatelliteRegistry.getKey(SatelliteBiomeChanger.class))); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), new SatelliteProperties().setPowerGeneration(1)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1), new SatelliteProperties().setPowerGeneration(10)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 0), new SatelliteProperties().setPowerStorage(100)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(LibVulpesItems.itemBattery, 1, 1), new SatelliteProperties().setPowerStorage(400)); SatelliteRegistry.registerSatelliteProperty(new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), new SatelliteProperties().setMaxData(1000)); //Item Registration LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemQuartzCrucible.setRegistryName("iquartzcrucible")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemOreScanner.setRegistryName("oreScanner")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellitePowerSource.setRegistryName("satellitePowerSource")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellitePrimaryFunction.setRegistryName("satellitePrimaryFunction")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemCircuitPlate.setRegistryName("itemCircuitPlate")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemIC.setRegistryName("ic")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemWafer.setRegistryName("wafer")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemDataUnit.setRegistryName("dataUnit")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatellite.setRegistryName("satellite")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSatelliteIdChip.setRegistryName("satelliteIdChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemPlanetIdChip.setRegistryName("planetIdChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemMisc.setRegistryName("misc")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSawBlade.setRegistryName("sawBladeIron")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceStationChip.setRegistryName("spaceStationChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceStation.setRegistryName("spaceStation")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Helmet.setRegistryName("spaceHelmet")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Boots.setRegistryName("spaceBoots")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Chest.setRegistryName("spaceChestplate")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSpaceSuit_Leggings.setRegistryName("spaceLeggings")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketRocketFuel.setRegistryName("bucketRocketFuel")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketNitrogen.setRegistryName("bucketNitrogen")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketHydrogen.setRegistryName("bucketHydrogen")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBucketOxygen.setRegistryName("bucketOxygen")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSmallAirlockDoor.setRegistryName("smallAirlockDoor")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemCarbonScrubberCartridge.setRegistryName("carbonScrubberCartridge")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemSealDetector.setRegistryName("sealDetector")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemJackhammer.setRegistryName("jackHammer")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemAsteroidChip.setRegistryName("asteroidChip")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemLens.setRegistryName("lens")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemJetpack.setRegistryName("jetPack")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemPressureTank.setRegistryName("pressureTank")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemUpgrade.setRegistryName("itemUpgrade")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemAtmAnalyser.setRegistryName("atmAnalyser")); LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBasicLaserGun.setRegistryName("basicLaserGun")); if(zmaster587.advancedRocketry.api.Configuration.enableTerraforming) LibVulpesBlocks.registerItem(AdvancedRocketryItems.itemBiomeChanger.setRegistryName("biomeChanger")); //End Items EntityRegistry.registerModEntity(EntityDummy.class, "mountDummy", 0, this, 16, 20, false); EntityRegistry.registerModEntity(EntityRocket.class, "rocket", 1, this, 64, 3, true); EntityRegistry.registerModEntity(EntityLaserNode.class, "laserNode", 2, instance, 256, 20, false); EntityRegistry.registerModEntity(EntityStationDeployedRocket.class, "deployedRocket", 3, this, 256, 600, true); EntityRegistry.registerModEntity(EntityItemAbducted.class, "ARAbductedItem", 4, this, 127, 600, false); GameRegistry.registerTileEntity(TileRocketBuilder.class, "ARrocketBuilder"); GameRegistry.registerTileEntity(TileWarpCore.class, "ARwarpCore"); //GameRegistry.registerTileEntity(TileModelRender.class, "ARmodelRenderer"); GameRegistry.registerTileEntity(TileEntityFuelingStation.class, "ARfuelingStation"); GameRegistry.registerTileEntity(TileEntityMoniteringStation.class, "ARmonitoringStation"); //GameRegistry.registerTileEntity(TileMissionController.class, "ARmissionControlComp"); GameRegistry.registerTileEntity(TileSpaceLaser.class, "ARspaceLaser"); GameRegistry.registerTileEntity(TilePrecisionAssembler.class, "ARprecisionAssembler"); GameRegistry.registerTileEntity(TileObservatory.class, "ARobservatory"); GameRegistry.registerTileEntity(TileCrystallizer.class, "ARcrystallizer"); GameRegistry.registerTileEntity(TileCuttingMachine.class, "ARcuttingmachine"); GameRegistry.registerTileEntity(TileDataBus.class, "ARdataBus"); GameRegistry.registerTileEntity(TileSatelliteHatch.class, "ARsatelliteHatch"); GameRegistry.registerTileEntity(TileSatelliteBuilder.class, "ARsatelliteBuilder"); GameRegistry.registerTileEntity(TileEntitySatelliteControlCenter.class, "ARTileEntitySatelliteControlCenter"); GameRegistry.registerTileEntity(TileAstrobodyDataProcessor.class, "ARplanetAnalyser"); GameRegistry.registerTileEntity(TileGuidanceComputer.class, "ARguidanceComputer"); GameRegistry.registerTileEntity(TileElectricArcFurnace.class, "ARelectricArcFurnace"); GameRegistry.registerTileEntity(TilePlanetSelector.class, "ARTilePlanetSelector"); //GameRegistry.registerTileEntity(TileModelRenderRotatable.class, "ARTileModelRenderRotatable"); GameRegistry.registerTileEntity(TileMaterial.class, "ARTileMaterial"); GameRegistry.registerTileEntity(TileLathe.class, "ARTileLathe"); GameRegistry.registerTileEntity(TileRollingMachine.class, "ARTileMetalBender"); GameRegistry.registerTileEntity(TileStationBuilder.class, "ARStationBuilder"); GameRegistry.registerTileEntity(TileElectrolyser.class, "ARElectrolyser"); GameRegistry.registerTileEntity(TileChemicalReactor.class, "ARChemicalReactor"); GameRegistry.registerTileEntity(TileOxygenVent.class, "AROxygenVent"); GameRegistry.registerTileEntity(TileOxygenCharger.class, "AROxygenCharger"); GameRegistry.registerTileEntity(TileCO2Scrubber.class, "ARCO2Scrubber"); GameRegistry.registerTileEntity(TileWarpShipMonitor.class, "ARStationMonitor"); GameRegistry.registerTileEntity(TileAtmosphereDetector.class, "AROxygenDetector"); GameRegistry.registerTileEntity(TileStationOrientationControl.class, "AROrientationControl"); GameRegistry.registerTileEntity(TileStationGravityController.class, "ARGravityControl"); GameRegistry.registerTileEntity(TileLiquidPipe.class, "ARLiquidPipe"); GameRegistry.registerTileEntity(TileDataPipe.class, "ARDataPipe"); GameRegistry.registerTileEntity(TileEnergyPipe.class, "AREnergyPipe"); GameRegistry.registerTileEntity(TileDrill.class, "ARDrill"); GameRegistry.registerTileEntity(TileMicrowaveReciever.class, "ARMicrowaveReciever"); GameRegistry.registerTileEntity(TileSuitWorkStation.class, "ARSuitWorkStation"); GameRegistry.registerTileEntity(TileRocketLoader.class, "ARRocketLoader"); GameRegistry.registerTileEntity(TileRocketUnloader.class, "ARRocketUnloader"); GameRegistry.registerTileEntity(TileBiomeScanner.class, "ARBiomeScanner"); GameRegistry.registerTileEntity(TileAtmosphereTerraformer.class, "ARAttTerraformer"); GameRegistry.registerTileEntity(TileLandingPad.class, "ARLandingPad"); GameRegistry.registerTileEntity(TileStationDeployedAssembler.class, "ARStationDeployableRocketAssembler"); GameRegistry.registerTileEntity(TileFluidTank.class, "ARFluidTank"); GameRegistry.registerTileEntity(TileRocketFluidUnloader.class, "ARFluidUnloader"); GameRegistry.registerTileEntity(TileRocketFluidLoader.class, "ARFluidLoader"); GameRegistry.registerTileEntity(TileSolarPanel.class, "ARSolarGenerator"); GameRegistry.registerTileEntity(TileDockingPort.class, "ARDockingPort"); GameRegistry.registerTileEntity(TileStationAltitudeController.class, "ARStationAltitudeController"); GameRegistry.registerTileEntity(TileRailgun.class, "ARRailgun"); //Register machine recipes LibVulpes.registerRecipeHandler(TileCuttingMachine.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/CuttingMachine.xml"); LibVulpes.registerRecipeHandler(TilePrecisionAssembler.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/PrecisionAssembler.xml"); LibVulpes.registerRecipeHandler(TileChemicalReactor.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/ChemicalReactor.xml"); LibVulpes.registerRecipeHandler(TileCrystallizer.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Crystallizer.xml"); LibVulpes.registerRecipeHandler(TileElectrolyser.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Electrolyser.xml"); LibVulpes.registerRecipeHandler(TileElectricArcFurnace.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/ElectricArcFurnace.xml"); LibVulpes.registerRecipeHandler(TileLathe.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/Lathe.xml"); LibVulpes.registerRecipeHandler(TileRollingMachine.class, event.getModConfigurationDirectory().getAbsolutePath() + "/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/RollingMachine.xml"); //AUDIO //Register Space Objects SpaceObjectManager.getSpaceManager().registerSpaceObjectType("genericObject", SpaceObject.class); //Register Allowed Products materialRegistry.registerMaterial(new zmaster587.libVulpes.api.material.Material("TitaniumAluminide", "pickaxe", 1, 0xaec2de, AllowedProducts.getProductByName("PLATE").getFlagValue() | AllowedProducts.getProductByName("INGOT").getFlagValue() | AllowedProducts.getProductByName("NUGGET").getFlagValue() | AllowedProducts.getProductByName("DUST").getFlagValue() | AllowedProducts.getProductByName("STICK").getFlagValue() | AllowedProducts.getProductByName("BLOCK").getFlagValue() | AllowedProducts.getProductByName("GEAR").getFlagValue() | AllowedProducts.getProductByName("SHEET").getFlagValue(), false)); materialRegistry.registerMaterial(new zmaster587.libVulpes.api.material.Material("TitaniumIridium", "pickaxe", 1, 0xd7dfe4, AllowedProducts.getProductByName("PLATE").getFlagValue() | AllowedProducts.getProductByName("INGOT").getFlagValue() | AllowedProducts.getProductByName("NUGGET").getFlagValue() | AllowedProducts.getProductByName("DUST").getFlagValue() | AllowedProducts.getProductByName("STICK").getFlagValue() | AllowedProducts.getProductByName("BLOCK").getFlagValue() | AllowedProducts.getProductByName("GEAR").getFlagValue() | AllowedProducts.getProductByName("SHEET").getFlagValue(), false)); materialRegistry.registerOres(LibVulpes.tabLibVulpesOres); //OreDict stuff OreDictionary.registerOre("waferSilicon", new ItemStack(AdvancedRocketryItems.itemWafer,1,0)); OreDictionary.registerOre("ingotCarbon", new ItemStack(AdvancedRocketryItems.itemMisc, 1, 1)); OreDictionary.registerOre("concrete", new ItemStack(AdvancedRocketryBlocks.blockConcrete)); OreDictionary.registerOre("itemSilicon", MaterialRegistry.getItemStackFromMaterialAndType("Silicon", AllowedProducts.getProductByName("INGOT"))); //Regiser item/block crap proxy.preinit(); } @EventHandler public void load(FMLInitializationEvent event) { //TODO: move to proxy //Minecraft.getMinecraft().getBlockColors().registerBlockColorHandler((IBlockColor) AdvancedRocketryBlocks.blockFuelFluid, new Block[] {AdvancedRocketryBlocks.blockFuelFluid}); proxy.init(); zmaster587.advancedRocketry.cable.NetworkRegistry.registerFluidNetwork(); ItemStack userInterface = new ItemStack(AdvancedRocketryItems.itemMisc, 1,0); ItemStack basicCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,0); ItemStack advancedCircuit = new ItemStack(AdvancedRocketryItems.itemIC, 1,2); ItemStack controlCircuitBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,3); ItemStack itemIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,4); ItemStack liquidIOBoard = new ItemStack(AdvancedRocketryItems.itemIC,1,5); ItemStack trackingCircuit = new ItemStack(AdvancedRocketryItems.itemIC,1,1); ItemStack opticalSensor = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0); ItemStack biomeChanger = new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 5); ItemStack smallSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0); ItemStack largeSolarPanel = new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,1); ItemStack smallBattery = new ItemStack(LibVulpesItems.itemBattery,1,0); ItemStack battery2x = new ItemStack(LibVulpesItems.itemBattery,1,1); ItemStack superHighPressureTime = new ItemStack(AdvancedRocketryItems.itemPressureTank,1,3); ItemStack charcoal = new ItemStack(Items.COAL,1,1); //Register Alloys MaterialRegistry.registerMixedMaterial(new MixedMaterial(TileElectricArcFurnace.class, "oreRutile", new ItemStack[] {MaterialRegistry.getMaterialFromName("Titanium").getProduct(AllowedProducts.getProductByName("INGOT"))})); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockBlastBrick,16), new ItemStack(Items.MAGMA_CREAM,1), new ItemStack(Items.MAGMA_CREAM,1), Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK, Blocks.BRICK_BLOCK); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockArcFurnace), "aga","ice", "aba", 'a', Items.NETHERBRICK, 'g', userInterface, 'i', itemIOBoard, 'e',controlCircuitBoard, 'c', AdvancedRocketryBlocks.blockBlastBrick, 'b', "ingotCopper")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemQuartzCrucible), " a ", "aba", " a ", Character.valueOf('a'), Items.QUARTZ, Character.valueOf('b'), Items.CAULDRON); GameRegistry.addRecipe(new ShapedOreRecipe(MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK"), 4), "x ", " x ", " x", 'x', "ingotIron")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockPlatePress, " ", " a ", "iii", 'a', Blocks.PISTON, 'i', "ingotIron")); GameRegistry.addSmelting(MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("ORE")), MaterialRegistry.getMaterialFromName("Dilithium").getProduct(AllowedProducts.getProductByName("DUST")), 0); //Supporting Materials GameRegistry.addRecipe(new ShapedOreRecipe(userInterface, "lrl", "fgf", 'l', "dyeLime", 'r', Items.REDSTONE, 'g', Blocks.GLASS_PANE, 'f', Items.GLOWSTONE_DUST)); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockGenericSeat), "xxx", 'x', Blocks.WOOL); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockConcrete, 16), Blocks.SAND, Blocks.GRAVEL, Items.WATER_BUCKET); GameRegistry.addRecipe(new ShapelessOreRecipe(AdvancedRocketryBlocks.blockLaunchpad, "concrete", "dyeBlack", "dyeYellow")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockStructureTower, "ooo", " o ", "ooo", 'o', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockEngine, "sss", " t ","t t", 's', "ingotSteel", 't', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockAdvEngine, "sss", " t ","t t", 's', "TitaniumAluminide", 't', "plateTitaniumIridium")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockFuelTank, "s s", "p p", "s s", 'p', "plateSteel", 's', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemBattery,4,0), " c ","prp", "prp", 'c', "stickIron", 'r', Items.REDSTONE, 'p', "plateTin")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemBattery,1,1), "bpb", "bpb", 'b', smallBattery, 'p', "plateCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), "ppp", " g ", " l ", 'p', Blocks.GLASS_PANE, 'g', Items.GLOWSTONE_DUST, 'l', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockObservatory), "gug", "pbp", "rrr", 'g', "paneGlass", 'u', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'r', "stickIron")); //Hatches GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,0), "c", "m"," ", 'c', Blocks.CHEST, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,1), "m", "c"," ", 'c', Blocks.CHEST, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,2), "c", "m", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(LibVulpesBlocks.blockHatch,1,3), "m", "c", " ", 'c', AdvancedRocketryBlocks.blockFuelTank, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,0), "m", "c"," ", 'c', AdvancedRocketryItems.itemDataUnit, 'm', LibVulpesBlocks.blockStructureBlock); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,1), " x ", "xmx"," x ", 'x', "stickTitanium", 'm', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,2), new ItemStack(LibVulpesBlocks.blockHatch,1,1), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,3), new ItemStack(LibVulpesBlocks.blockHatch,1,0), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,4), new ItemStack(LibVulpesBlocks.blockHatch,1,3), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLoader,1,5), new ItemStack(LibVulpesBlocks.blockHatch,1,2), trackingCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMotor), " cp", "rrp"," cp", 'c', "coilCopper", 'p', "plateSteel", 'r', "stickSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePowerSource,1,0), "rrr", "ggg","ppp", 'r', Items.REDSTONE, 'g', Items.GLOWSTONE_DUST, 'p', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(LibVulpesItems.itemHoloProjector), "oro", "rpr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'r', Items.REDSTONE, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 2), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', "crystalDilithium")); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 1), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 3), "odo", "pcp", 'o', new ItemStack(AdvancedRocketryItems.itemLens, 1, 0), 'p', new ItemStack(AdvancedRocketryItems.itemWafer,1,0), 'c', basicCircuit, 'd', trackingCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0), " x ","xox", " x ", 'x', "plateIron", 'o', "stickIron")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSawBlade,1,0), "r r","xox", "x x", 'r', "stickIron", 'x', "plateIron", 'o', new ItemStack(AdvancedRocketryItems.itemSawBlade,1,0))); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSpaceStationChip), LibVulpesItems.itemLinker , basicCircuit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge), "xix", "xix", "xix", 'x', "sheetIron", 'i', Blocks.IRON_BARS)); //O2 Support GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenVent), "bfb", "bmb", "btb", 'b', Blocks.IRON_BARS, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', AdvancedRocketryBlocks.blockFuelTank)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenScrubber), "bfb", "bmb", "btb", 'b', Blocks.IRON_BARS, 'f', "fanSteel", 'm', AdvancedRocketryBlocks.blockMotor, 't', "ingotCarbon")); //MACHINES GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPrecisionAssembler), "abc", "def", "ghi", 'a', Items.REPEATER, 'b', userInterface, 'c', Items.DIAMOND, 'd', itemIOBoard, 'e', LibVulpesBlocks.blockStructureBlock, 'f', controlCircuitBoard, 'g', Blocks.FURNACE, 'h', "gearSteel", 'i', Blocks.DROPPER)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCrystallizer), "ada", "ecf","bgb", 'a', Items.QUARTZ, 'b', Items.REPEATER, 'c', LibVulpesBlocks.blockStructureBlock, 'd', userInterface, 'e', itemIOBoard, 'f', controlCircuitBoard, 'g', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCuttingMachine), "aba", "cde", "opo", 'a', "gearSteel", 'b', userInterface, 'c', itemIOBoard, 'e', controlCircuitBoard, 'p', "plateSteel", 'o', Blocks.OBSIDIAN, 'd', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockLathe), "rsr", "abc", "pgp", 'r', "stickIron",'a', itemIOBoard, 'c', controlCircuitBoard, 'g', "gearSteel", 'p', "plateSteel", 'b', LibVulpesBlocks.blockStructureBlock, 's', userInterface)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRollingMachine), "psp", "abc", "iti", 'a', itemIOBoard, 'c', controlCircuitBoard, 'p', "gearSteel", 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'i', "blockIron",'t', liquidIOBoard)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMonitoringStation), "coc", "cbc", "cpc", 'c', "stickCopper", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'b', LibVulpesBlocks.blockStructureBlock, 'p', LibVulpesItems.itemBattery)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockFuelingStation), "bgb", "lbf", "ppp", 'p', "plateTin", 'f', "fanSteel", 'l', liquidIOBoard, 'g', AdvancedRocketryItems.itemMisc, 'x', AdvancedRocketryBlocks.blockFuelTank, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteControlCenter), "oso", "cbc", "rtr", 'o', new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 's', userInterface, 'c', "stickCopper", 'b', LibVulpesBlocks.blockStructureBlock, 'r', Items.REPEATER, 't', LibVulpesItems.itemBattery)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockSatelliteBuilder), "dht", "cbc", "mas", 'd', AdvancedRocketryItems.itemDataUnit, 'h', Blocks.HOPPER, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'm', AdvancedRocketryBlocks.blockMotor, 'a', Blocks.ANVIL, 's', AdvancedRocketryBlocks.blockSawBlade, 't', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetAnalyser), "tst", "pbp", "cpc", 't', trackingCircuit, 's', userInterface, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateTin", 'c', AdvancedRocketryItems.itemPlanetIdChip)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockGuidanceComputer), "ctc", "rbr", "crc", 'c', trackingCircuit, 't', "plateTitanium", 'r', Items.REDSTONE, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPlanetSelector), "cpc", "lbl", "coc", 'c', trackingCircuit, 'o',new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 0), 'l', Blocks.LEVER, 'b', AdvancedRocketryBlocks.blockGuidanceComputer, 'p', Blocks.STONE_BUTTON)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder), "sgs", "cbc", "tdt", 's', "stickTitanium", 'g', AdvancedRocketryItems.itemMisc, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 't', "gearTitanium", 'd', AdvancedRocketryBlocks.blockConcrete)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockStationBuilder), "gdg", "dsd", "ada", 'g', "gearTitanium", 'a', advancedCircuit, 'd', "dustDilithium", 's', new ItemStack(AdvancedRocketryBlocks.blockRocketBuilder))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockElectrolyser), "pip", "abc", "ded", 'd', basicCircuit, 'p', "plateSteel", 'i', userInterface, 'a', liquidIOBoard, 'c', controlCircuitBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'e', Blocks.REDSTONE_TORCH)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenCharger), "fif", "tbt", "pcp", 'p', "plateSteel", 'f', "fanSteel", 'c', Blocks.HEAVY_WEIGHTED_PRESSURE_PLATE, 'i', AdvancedRocketryItems.itemMisc, 'b', LibVulpesBlocks.blockStructureBlock, 't', AdvancedRocketryBlocks.blockFuelTank)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockChemicalReactor), "pip", "abd", "rcr", 'a', itemIOBoard, 'd', controlCircuitBoard, 'r', basicCircuit, 'p', "plateGold", 'i', userInterface, 'c', liquidIOBoard, 'b', LibVulpesBlocks.blockStructureBlock, 'g', "plateGold")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpCore), "gcg", "pbp", "gcg", 'p', "plateSteel", 'c', advancedCircuit, 'b', "coilCopper", 'g', "plateTitanium")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockOxygenDetection), "pip", "gbf", "pcp", 'p', "plateSteel",'f', "fanSteel", 'i', userInterface, 'c', basicCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'g', Blocks.IRON_BARS)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockWarpShipMonitor), "pip", "obo", "pcp", 'o', controlCircuitBoard, 'p', "plateSteel", 'i', userInterface, 'c', advancedCircuit, 'b', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockBiomeScanner), "plp", "bsb","ppp", 'p', "plateTin", 'l', biomeChanger, 'b', smallBattery, 's', LibVulpesBlocks.blockStructureBlock)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockDeployableRocketBuilder), "gdg", "dad", "rdr", 'g', "gearTitaniumAluminide", 'd', "dustDilithium", 'r', "stickTitaniumAluminide", 'a', AdvancedRocketryBlocks.blockRocketBuilder)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockPressureTank), "tgt","tgt","tgt", 't', superHighPressureTime, 'g', Blocks.GLASS_PANE)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockIntake), "rhr", "hbh", "rhr", 'r', "stickTitanium", 'h', Blocks.HOPPER, 'b', LibVulpesBlocks.blockStructureBlock)); //Armor recipes GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Boots, " r ", "w w", "p p", 'r', "stickIron", 'w', Blocks.WOOL, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Leggings, "wrw", "w w", "w w", 'w', Blocks.WOOL, 'r', "stickIron")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Chest, "wrw", "wtw", "wfw", 'w', Blocks.WOOL, 'r', "stickIron", 't', AdvancedRocketryBlocks.blockFuelTank, 'f', "fanSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSpaceSuit_Helmet, "prp", "rgr", "www", 'w', Blocks.WOOL, 'r', "stickIron", 'p', "plateIron", 'g', Blocks.GLASS_PANE)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJetpack, "cpc", "lsl", "f f", 'c', AdvancedRocketryItems.itemPressureTank, 'f', Items.FIRE_CHARGE, 's', Items.STRING, 'l', Blocks.LEVER, 'p', "plateSteel")); //Tool Recipes GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemJackhammer, " pt","imp","di ",'d', Items.DIAMOND, 'm', AdvancedRocketryBlocks.blockMotor, 'p', "plateAluminum", 't', "stickTitanium", 'i', "stickIron")); //Other blocks GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemSmallAirlockDoor, "pp", "pp","pp", 'p', "plateSteel")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockCircleLight), "p ", " l ", " ", 'p', "sheetIron", 'l', Blocks.GLOWSTONE)); //TEMP RECIPES GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemPlanetIdChip), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemIC, 1, 0), new ItemStack(AdvancedRocketryItems.itemSatelliteIdChip)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemMisc,1,1), charcoal, charcoal, charcoal, charcoal ,charcoal ,charcoal); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockLandingPad), new ItemStack(AdvancedRocketryBlocks.blockConcrete), trackingCircuit); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryItems.itemAsteroidChip), trackingCircuit.copy(), AdvancedRocketryItems.itemDataUnit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockDataPipe, 8), "ggg", " d ", "ggg", 'g', Blocks.GLASS_PANE, 'd', AdvancedRocketryItems.itemDataUnit); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockEnergyPipe, 32), "ggg", " d ", "ggg", 'g', Items.CLAY_BALL, 'd', "stickCopper")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockFluidPipe, 32), "ggg", " d ", "ggg", 'g', Items.CLAY_BALL, 'd', "sheetCopper")); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockDrill), LibVulpesBlocks.blockStructureBlock, Items.IRON_PICKAXE); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockOrientationController), LibVulpesBlocks.blockStructureBlock, Items.COMPASS, userInterface); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockGravityController), LibVulpesBlocks.blockStructureBlock, Blocks.PISTON, Blocks.REDSTONE_BLOCK); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockAltitudeController), LibVulpesBlocks.blockStructureBlock, userInterface, basicCircuit); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryItems.itemLens), " g ", "g g", 'g', Blocks.GLASS_PANE); GameRegistry.addShapelessRecipe(largeSolarPanel.copy(), smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel, smallSolarPanel); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockMicrowaveReciever), "ggg", "tbc", "aoa", 'g', "plateGold", 't', trackingCircuit, 'b', LibVulpesBlocks.blockStructureBlock, 'c', controlCircuitBoard, 'a', advancedCircuit, 'o', opticalSensor)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSolarPanel, "rrr", "gbg", "ppp", 'r' , Items.REDSTONE, 'g', Items.GLOWSTONE_DUST, 'b', LibVulpesBlocks.blockStructureBlock, 'p', "plateGold")); GameRegistry.addRecipe(new ShapelessOreRecipe(AdvancedRocketryBlocks.blockSolarGenerator, "itemBattery", LibVulpesBlocks.blockForgeOutputPlug, AdvancedRocketryBlocks.blockSolarPanel)); GameRegistry.addShapelessRecipe(new ItemStack(AdvancedRocketryBlocks.blockDockingPort), trackingCircuit, new ItemStack(AdvancedRocketryBlocks.blockLoader, 1,1)); GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryItems.itemOreScanner, "lwl", "bgb", " ", 'l', Blocks.LEVER, 'g', userInterface, 'b', "itemBattery", 'w', advancedCircuit)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryItems.itemSatellitePrimaryFunction, 1, 4), " c ","sss", "tot", 'c', "stickCopper", 's', "sheetIron", 'o', AdvancedRocketryItems.itemOreScanner, 't', trackingCircuit)); GameRegistry.addShapedRecipe(new ItemStack(AdvancedRocketryBlocks.blockSuitWorkStation), "c","b", 'c', Blocks.CRAFTING_TABLE, 'b', LibVulpesBlocks.blockStructureBlock); RecipesMachine.getInstance().addRecipe(TileElectrolyser.class, new Object[] {new FluidStack(AdvancedRocketryFluids.fluidOxygen, 100), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 100)}, 100, 20, new FluidStack(FluidRegistry.WATER, 10)); RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new FluidStack(AdvancedRocketryFluids.fluidRocketFuel, 20), 100, 10, new FluidStack(AdvancedRocketryFluids.fluidOxygen, 10), new FluidStack(AdvancedRocketryFluids.fluidHydrogen, 10)); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) { GameRegistry.addRecipe(new ShapedOreRecipe(AdvancedRocketryBlocks.blockSpaceLaser, "ata", "bec", "gpg", 'a', advancedCircuit, 't', trackingCircuit, 'b', LibVulpesItems.itemBattery, 'e', Items.EMERALD, 'c', controlCircuitBoard, 'g', "gearTitanium", 'p', LibVulpesBlocks.blockStructureBlock)); } if(zmaster587.advancedRocketry.api.Configuration.allowTerraforming) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(AdvancedRocketryBlocks.blockAtmosphereTerraformer), "gdg", "lac", "gbg", 'g', "gearTitaniumAluminide", 'd', "crystalDilithium", 'l', liquidIOBoard, 'a', LibVulpesBlocks.blockAdvStructureBlock, 'c', controlCircuitBoard, 'b', battery2x)); } //Control boards GameRegistry.addRecipe(new ShapedOreRecipe(itemIOBoard, "rvr", "dwd", "dpd", 'r', Items.REDSTONE, 'v', Items.DIAMOND, 'd', "dustGold", 'w', Blocks.WOODEN_SLAB, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(controlCircuitBoard, "rvr", "dwd", "dpd", 'r', Items.REDSTONE, 'v', Items.DIAMOND, 'd', "dustCopper", 'w', Blocks.WOODEN_SLAB, 'p', "plateIron")); GameRegistry.addRecipe(new ShapedOreRecipe(liquidIOBoard, "rvr", "dwd", "dpd", 'r', Items.REDSTONE, 'v', Items.DIAMOND, 'd', new ItemStack(Items.DYE, 1, 4), 'w', Blocks.WOODEN_SLAB, 'p', "plateIron")); //Cutting Machine RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 0), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0)); RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemIC, 4, 2), 300, 100, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1)); RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(AdvancedRocketryItems.itemWafer, 4, 0), 300, 100, "bouleSilicon"); //Lathe RecipesMachine.getInstance().addRecipe(TileLathe.class, MaterialRegistry.getItemStackFromMaterialAndType("Iron", AllowedProducts.getProductByName("STICK"), 2), 300, 100, "ingotIron"); //Precision Assembler recipes RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), 900, 100, Items.GOLD_INGOT, Items.REDSTONE, "waferSilicon"); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,1), 900, 100, Items.GOLD_INGOT, Blocks.REDSTONE_BLOCK, "waferSilicon"); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemDataUnit, 1, 0), 500, 60, Items.EMERALD, basicCircuit, Items.REDSTONE); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, trackingCircuit, 900, 50, new ItemStack(AdvancedRocketryItems.itemCircuitPlate,1,0), Items.ENDER_EYE, Items.REDSTONE); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, itemIOBoard, 200, 10, "plateSilicon", "plateGold", basicCircuit, Items.REDSTONE); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, controlCircuitBoard, 200, 10, "plateSilicon", "plateCopper", basicCircuit, Items.REDSTONE); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, liquidIOBoard, 200, 10, "plateSilicon", new ItemStack(Items.DYE, 1, 4), basicCircuit, Items.REDSTONE); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,0), 400, 1, Items.REDSTONE, Blocks.REDSTONE_TORCH, basicCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,1), 400, 1, Items.FIRE_CHARGE, Items.DIAMOND, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,2), 400, 1, AdvancedRocketryBlocks.blockMotor, "rodTitanium", advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,3), 400, 1, Items.LEATHER_BOOTS, Items.FEATHER, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemUpgrade,1,4), 400, 1, LibVulpesItems.itemBattery, AdvancedRocketryItems.itemLens, advancedCircuit, controlCircuitBoard); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemAtmAnalyser), 1000, 1, smallBattery, advancedCircuit, "plateTin", AdvancedRocketryItems.itemLens, userInterface); RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, biomeChanger, 1000, 1, new NumberedOreDictStack("stickCopper", 2), "stickTitanium", new NumberedOreDictStack("waferSilicon", 2), advancedCircuit); if(zmaster587.advancedRocketry.api.Configuration.enableTerraforming) { RecipesMachine.getInstance().addRecipe(TilePrecisionAssembler.class, new ItemStack(AdvancedRocketryItems.itemBiomeChanger), 1000, 1, smallBattery, advancedCircuit, "plateTin", trackingCircuit, userInterface); } //BlastFurnace RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Silicon").getProduct(AllowedProducts.getProductByName("INGOT")), 12000, 1, Blocks.SAND); RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("Steel").getProduct(AllowedProducts.getProductByName("INGOT")), 6000, 1, "ingotIron", charcoal); //TODO add 2Al2O3 as output RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("TitaniumAluminide").getProduct(AllowedProducts.getProductByName("INGOT"), 3), 9000, 20, new NumberedOreDictStack("ingotAluminum", 7), new NumberedOreDictStack("ingotTitanium", 3)); //TODO titanium dioxide RecipesMachine.getInstance().addRecipe(TileElectricArcFurnace.class, MaterialRegistry.getMaterialFromName("TitaniumIridium").getProduct(AllowedProducts.getProductByName("INGOT"),2), 3000, 20, "ingotTitanium", "ingotIridium"); //Chemical Reactor RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new Object[] {new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge,1, 0), new ItemStack(Items.COAL, 1, 1)}, 40, 20, new ItemStack(AdvancedRocketryItems.itemCarbonScrubberCartridge, 1, AdvancedRocketryItems.itemCarbonScrubberCartridge.getMaxDamage())); RecipesMachine.getInstance().addRecipe(TileChemicalReactor.class, new ItemStack(Items.DYE,5,0xF), 100, 1, Items.BONE, new FluidStack(AdvancedRocketryFluids.fluidNitrogen, 10)); //Rolling Machine RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 0), 100, 1, "sheetIron", "sheetIron"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 1), 200, 2, "sheetSteel", "sheetSteel"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 2), 100, 1, "sheetAluminum", "sheetAluminum"); RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, new ItemStack(AdvancedRocketryItems.itemPressureTank, 1, 3), 1000, 8, "sheetTitanium", "sheetTitanium"); NetworkRegistry.INSTANCE.registerGuiHandler(this, new zmaster587.advancedRocketry.inventory.GuiHandler()); planetWorldType = new WorldTypePlanetGen("PlanetCold"); spaceWorldType = new WorldTypeSpace("Space"); AdvancedRocketryBiomes.moonBiome = new BiomeGenMoon(config.get(BIOMECATETORY, "moonBiomeId", 90).getInt(), true); AdvancedRocketryBiomes.alienForest = new BiomeGenAlienForest(config.get(BIOMECATETORY, "alienForestBiomeId", 91).getInt(), true); AdvancedRocketryBiomes.hotDryBiome = new BiomeGenHotDryRock(config.get(BIOMECATETORY, "hotDryBiome", 92).getInt(), true); AdvancedRocketryBiomes.spaceBiome = new BiomeGenSpace(config.get(BIOMECATETORY, "spaceBiomeId", 93).getInt(), true); AdvancedRocketryBiomes.stormLandsBiome = new BiomeGenStormland(config.get(BIOMECATETORY, "stormLandsBiomeId", 94).getInt(), true); AdvancedRocketryBiomes.crystalChasms = new BiomeGenCrystal(config.get(BIOMECATETORY, "crystalChasmsBiomeId", 95).getInt(), true); AdvancedRocketryBiomes.swampDeepBiome = new BiomeGenDeepSwamp(config.get(BIOMECATETORY, "deepSwampBiomeId", 96).getInt(), true); AdvancedRocketryBiomes.marsh = new BiomeGenMarsh(config.get(BIOMECATETORY, "marsh", 97).getInt(), true); AdvancedRocketryBiomes.oceanSpires = new BiomeGenOceanSpires(config.get(BIOMECATETORY, "oceanSpires", 98).getInt(), true); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.moonBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.alienForest); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.hotDryBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.spaceBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.stormLandsBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.crystalChasms); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.swampDeepBiome); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.marsh); AdvancedRocketryBiomes.instance.registerBiome(AdvancedRocketryBiomes.oceanSpires); String[] biomeBlackList = config.getStringList("BlacklistedBiomes", "Planet", new String[] {"7", "8", "9", "127", String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.alienForest))}, "List of Biomes to be blacklisted from spawning as BiomeIds, default is: river, sky, hell, void, alienForest"); String[] biomeHighPressure = config.getStringList("HighPressureBiomes", "Planet", new String[] { String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.swampDeepBiome)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.stormLandsBiome)) }, "Biomes that only spawn on worlds with pressures over 125, will override blacklist. Defaults: StormLands, DeepSwamp"); String[] biomeSingle = config.getStringList("SingleBiomes", "Planet", new String[] { String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.swampDeepBiome)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.crystalChasms)), String.valueOf(Biome.getIdForBiome(AdvancedRocketryBiomes.alienForest)), String.valueOf(Biome.getIdForBiome(Biomes.DESERT_HILLS)), String.valueOf(Biome.getIdForBiome(Biomes.MUSHROOM_ISLAND)), String.valueOf(Biome.getIdForBiome(Biomes.EXTREME_HILLS)), String.valueOf(Biome.getIdForBiome(Biomes.ICE_PLAINS)) }, "Some worlds have a chance of spawning single biomes contained in this list. Defaults: deepSwamp, crystalChasms, alienForest, desert hills, mushroom island, extreme hills, ice plains"); config.save(); //Prevent these biomes from spawning normally AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.moonBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.hotDryBiome); AdvancedRocketryBiomes.instance.registerBlackListBiome(AdvancedRocketryBiomes.spaceBiome); //Read BlackList from config and register Blacklisted biomes for(String string : biomeBlackList) { try { int id = Integer.parseInt(string); Biome biome = Biome.getBiome(id, null); if(biome == null) logger.warn(String.format("Error blackListing biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerBlackListBiome(biome); } catch (NumberFormatException e) { logger.warn("Error blackListing \"" + string + "\". It is not a valid number"); } } if(zmaster587.advancedRocketry.api.Configuration.blackListAllVanillaBiomes) { AdvancedRocketryBiomes.instance.blackListVanillaBiomes(); } //Read and Register High Pressure biomes from config for(String string : biomeHighPressure) { try { int id = Integer.parseInt(string); Biome biome = Biome.getBiome(id, null); if(biome == null) logger.warn(String.format("Error registering high pressure biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerHighPressureBiome(biome); } catch (NumberFormatException e) { logger.warn("Error registering high pressure biome \"" + string + "\". It is not a valid number"); } } //Read and Register Single biomes from config for(String string : biomeSingle) { try { int id = Integer.parseInt(string); Biome biome = Biome.getBiome(id, null); if(biome == null) logger.warn(String.format("Error registering single biome id \"%d\", a biome with that ID does not exist!", id)); else AdvancedRocketryBiomes.instance.registerSingleBiome(biome); } catch (NumberFormatException e) { logger.warn("Error registering single biome \"" + string + "\". It is not a valid number"); } } //Data mapping 'D' List<BlockMeta> list = new LinkedList<BlockMeta>(); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 0)); list.add(new BlockMeta(AdvancedRocketryBlocks.blockLoader, 8)); TileMultiBlock.addMapping('D', list); } @EventHandler public void postInit(FMLPostInitializationEvent event) { CapabilitySpaceArmor.register(); //Need to raise the Max Entity Radius to allow player interaction with rockets World.MAX_ENTITY_RADIUS = 20; //Register multiblock items with the projector ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCuttingMachine(), (BlockTile)AdvancedRocketryBlocks.blockCuttingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileLathe(), (BlockTile)AdvancedRocketryBlocks.blockLathe); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileCrystallizer(), (BlockTile)AdvancedRocketryBlocks.blockCrystallizer); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TilePrecisionAssembler(), (BlockTile)AdvancedRocketryBlocks.blockPrecisionAssembler); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileObservatory(), (BlockTile)AdvancedRocketryBlocks.blockObservatory); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileAstrobodyDataProcessor(), (BlockTile)AdvancedRocketryBlocks.blockPlanetAnalyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileRollingMachine(), (BlockTile)AdvancedRocketryBlocks.blockRollingMachine); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectricArcFurnace(), (BlockTile)AdvancedRocketryBlocks.blockArcFurnace); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileElectrolyser(), (BlockTile)AdvancedRocketryBlocks.blockElectrolyser); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileChemicalReactor(), (BlockTile)AdvancedRocketryBlocks.blockChemicalReactor); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileWarpCore(), (BlockTile)AdvancedRocketryBlocks.blockWarpCore); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileMicrowaveReciever(), (BlockTile)AdvancedRocketryBlocks.blockMicrowaveReciever); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileBiomeScanner(), (BlockTile)AdvancedRocketryBlocks.blockBiomeScanner); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileAtmosphereTerraformer(), (BlockTile)AdvancedRocketryBlocks.blockAtmosphereTerraformer); ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileRailgun(), (BlockTile)AdvancedRocketryBlocks.blockRailgun); if(zmaster587.advancedRocketry.api.Configuration.enableLaserDrill) ((ItemProjector)LibVulpesItems.itemHoloProjector).registerMachine(new TileSpaceLaser(), (BlockTile)AdvancedRocketryBlocks.blockSpaceLaser); proxy.registerEventHandlers(); proxy.registerKeyBindings(); ARAchivements.register(); //TODO: debug //ClientCommandHandler.instance.registerCommand(new Debugger()); PlanetEventHandler handle = new PlanetEventHandler(); MinecraftForge.EVENT_BUS.register(handle); MinecraftForge.ORE_GEN_BUS.register(handle); //MinecraftForge.EVENT_BUS.register(new BucketHandler()); CableTickHandler cable = new CableTickHandler(); MinecraftForge.EVENT_BUS.register(cable); InputSyncHandler inputSync = new InputSyncHandler(); MinecraftForge.EVENT_BUS.register(inputSync); MinecraftForge.EVENT_BUS.register(new MapGenLander()); /*if(Loader.isModLoaded("GalacticraftCore") && zmaster587.advancedRocketry.api.Configuration.overrideGCAir) { GalacticCraftHandler eventHandler = new GalacticCraftHandler(); MinecraftForge.EVENT_BUS.register(eventHandler); if(event.getSide().isClient()) FMLCommonHandler.instance().bus().register(eventHandler); }*/ MinecraftForge.EVENT_BUS.register(SpaceObjectManager.getSpaceManager()); PacketHandler.init(); FuelRegistry.instance.registerFuel(FuelType.LIQUID, AdvancedRocketryFluids.fluidRocketFuel, 1); GameRegistry.registerWorldGenerator(new OreGenerator(), 100); ForgeChunkManager.setForcedChunkLoadingCallback(instance, new WorldEvents()); //AutoGenned Recipes for(zmaster587.libVulpes.api.material.Material ore : MaterialRegistry.getAllMaterials()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) GameRegistry.addSmelting(ore.getProduct(AllowedProducts.getProductByName("ORE")), ore.getProduct(AllowedProducts.getProductByName("INGOT")), 0); if(AllowedProducts.getProductByName("NUGGET").isOfType(ore.getAllowedProducts())) { ItemStack nugget = ore.getProduct(AllowedProducts.getProductByName("NUGGET")); nugget.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(nugget, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("INGOT")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("NUGGET").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("CRYSTAL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("CRYSTAL")), 300, 20, AllowedProducts.getProductByName("DUST").name().toLowerCase(Locale.ENGLISH) + str); } if(AllowedProducts.getProductByName("BOULE").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) RecipesMachine.getInstance().addRecipe(TileCrystallizer.class, ore.getProduct(AllowedProducts.getProductByName("BOULE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str, AllowedProducts.getProductByName("NUGGET").name().toLowerCase(Locale.ENGLISH) + str); } if(AllowedProducts.getProductByName("STICK").isOfType(ore.getAllowedProducts()) && AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts())) { for(String name : ore.getOreDictNames()) if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + name)) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("STICK"),4), "x ", " x ", " x", 'x', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + name)); RecipesMachine.getInstance().addRecipe(TileLathe.class, ore.getProduct(AllowedProducts.getProductByName("STICK"),2), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + name); //ore.getProduct(AllowedProducts.getProductByName("INGOT"))); } } if(AllowedProducts.getProductByName("PLATE").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { if(OreDictionary.doesOreNameExist(AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + oreDictNames)) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("PLATE")), 300, 20, AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + oreDictNames); if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) RecipesMachine.getInstance().addRecipe(BlockPress.class, ore.getProduct(AllowedProducts.getProductByName("PLATE"),4), 0, 0, AllowedProducts.getProductByName("BLOCK").name().toLowerCase(Locale.ENGLISH) + oreDictNames); } } } if(AllowedProducts.getProductByName("SHEET").isOfType(ore.getAllowedProducts())) { for(String oreDictNames : ore.getOreDictNames()) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, ore.getProduct(AllowedProducts.getProductByName("SHEET")), 300, 200, AllowedProducts.getProductByName("PLATE").name().toLowerCase(Locale.ENGLISH) + oreDictNames); } } if(AllowedProducts.getProductByName("COIL").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("COIL")), "ooo", "o o", "ooo",'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); } if(AllowedProducts.getProductByName("FAN").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("FAN")), "p p", " r ", "p p", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase(Locale.ENGLISH) + str, 'r', AllowedProducts.getProductByName("STICK").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("GEAR").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("GEAR")), "sps", " r ", "sps", 'p', AllowedProducts.getProductByName("PLATE").name().toLowerCase(Locale.ENGLISH) + str, 's', AllowedProducts.getProductByName("STICK").name().toLowerCase(Locale.ENGLISH) + str, 'r', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("BLOCK").isOfType(ore.getAllowedProducts())) { ItemStack ingot = ore.getProduct(AllowedProducts.getProductByName("INGOT")); ingot.stackSize = 9; for(String str : ore.getOreDictNames()) { GameRegistry.addRecipe(new ShapelessOreRecipe(ingot, AllowedProducts.getProductByName("BLOCK").name().toLowerCase(Locale.ENGLISH) + str)); GameRegistry.addRecipe(new ShapedOreRecipe(ore.getProduct(AllowedProducts.getProductByName("BLOCK")), "ooo", "ooo", "ooo", 'o', AllowedProducts.getProductByName("INGOT").name().toLowerCase(Locale.ENGLISH) + str)); } } if(AllowedProducts.getProductByName("DUST").isOfType(ore.getAllowedProducts())) { for(String str : ore.getOreDictNames()) { if(AllowedProducts.getProductByName("ORE").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) { ItemStack stack = ore.getProduct(AllowedProducts.getProductByName("DUST")); stack.stackSize = 2; RecipesMachine.getInstance().addRecipe(BlockPress.class, stack, 0, 0, AllowedProducts.getProductByName("ORE").name().toLowerCase(Locale.ENGLISH) + str); } if(AllowedProducts.getProductByName("INGOT").isOfType(ore.getAllowedProducts()) || ore.isVanilla()) GameRegistry.addSmelting(ore.getProduct(AllowedProducts.getProductByName("DUST")), ore.getProduct(AllowedProducts.getProductByName("INGOT")), 0); } } } //Handle vanilla integration if(zmaster587.advancedRocketry.api.Configuration.allowSawmillVanillaWood) { for(int i = 0; i < 4; i++) { RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.PLANKS, 6, i), 80, 10, new ItemStack(Blocks.LOG,1, i)); } RecipesMachine.getInstance().addRecipe(TileCuttingMachine.class, new ItemStack(Blocks.PLANKS, 6, 4), 80, 10, new ItemStack(Blocks.LOG2,1, 0)); } //Handle items from other mods if(zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) { for(Entry<AllowedProducts, HashSet<String>> entry : modProducts.entrySet()) { if(entry.getKey() == AllowedProducts.getProductByName("PLATE")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("PLATE").isOfType(material.getAllowedProducts())) ) { RecipesMachine.getInstance().addRecipe(TileRollingMachine.class, OreDictionary.getOres("plate" + str).get(0), 300, 20, "ingot" + str); } } } else if(entry.getKey() == AllowedProducts.getProductByName("STICK")) { for(String str : entry.getValue()) { zmaster587.libVulpes.api.material.Material material = zmaster587.libVulpes.api.material.Material.valueOfSafe(str.toUpperCase()); if(OreDictionary.doesOreNameExist("ingot" + str) && OreDictionary.getOres("ingot" + str).size() > 0 && (material == null || !AllowedProducts.getProductByName("STICK").isOfType(material.getAllowedProducts())) ) { //GT registers rods as sticks ItemStack stackToAdd = null; if(OreDictionary.doesOreNameExist("rod" + str) && OreDictionary.getOres("rod" + str).size() > 0) { stackToAdd = OreDictionary.getOres("rod" + str).get(0).copy(); stackToAdd.stackSize = 2; } else if(OreDictionary.doesOreNameExist("stick" + str) && OreDictionary.getOres("stick" + str).size() > 0) { stackToAdd = OreDictionary.getOres("stick" + str).get(0).copy(); stackToAdd.stackSize = 2; } else continue; RecipesMachine.getInstance().addRecipe(TileLathe.class, stackToAdd, 300, 20, "ingot" + str); } } } } } //Register buckets BucketHandler.INSTANCE.registerBucket(AdvancedRocketryBlocks.blockFuelFluid, AdvancedRocketryItems.itemBucketRocketFuel); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidRocketFuel, new ItemStack(AdvancedRocketryItems.itemBucketRocketFuel), new ItemStack(Items.BUCKET)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidNitrogen, new ItemStack(AdvancedRocketryItems.itemBucketNitrogen), new ItemStack(Items.BUCKET)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidHydrogen, new ItemStack(AdvancedRocketryItems.itemBucketHydrogen), new ItemStack(Items.BUCKET)); FluidContainerRegistry.registerFluidContainer(AdvancedRocketryFluids.fluidOxygen, new ItemStack(AdvancedRocketryItems.itemBucketOxygen), new ItemStack(Items.BUCKET)); //Register mixed material's recipes for(MixedMaterial material : MaterialRegistry.getMixedMaterialList()) { RecipesMachine.getInstance().addRecipe(material.getMachine(), material.getProducts(), 100, 10, material.getInput()); } //Register space dimension net.minecraftforge.common.DimensionManager.registerDimension(zmaster587.advancedRocketry.api.Configuration.spaceDimId, DimensionManager.spaceDimensionType); //Register Whitelisted Sealable Blocks logger.info("Start registering sealable blocks"); for(String str : sealableBlockWhiteList) { Block block = Block.getBlockFromName(str); if(block == null) logger.warn("'" + str + "' is not a valid Block"); else SealableBlockHandler.INSTANCE.addSealableBlock(block); } logger.info("End registering sealable blocks"); sealableBlockWhiteList = null; logger.info("Start registering torch blocks"); for(String str : breakableTorches) { Block block = Block.getBlockFromName(str); if(block == null) logger.warn("'" + str + "' is not a valid Block"); else zmaster587.advancedRocketry.api.Configuration.torchBlocks.add(block); } logger.info("End registering torch blocks"); breakableTorches = null; logger.info("Start registering Harvestable Gasses"); for(String str : harvestableGasses) { Fluid fluid = FluidRegistry.getFluid(str); if(fluid == null) logger.warn("'" + str + "' is not a valid Fluid"); else AtmosphereRegister.getInstance().registerHarvestableFluid(fluid); } logger.info("End registering Harvestable Gasses"); harvestableGasses = null; logger.info("Start registering entity atmosphere bypass"); //Add armor stand by default zmaster587.advancedRocketry.api.Configuration.bypassEntity.add(EntityArmorStand.class); for(String str : entityList) { Class clazz = (Class) EntityList.NAME_TO_CLASS.get(str); //If not using string name maybe it's a class name? if(clazz == null) { try { clazz = Class.forName(str); if(clazz != null && !Entity.class.isAssignableFrom(clazz)) clazz = null; } catch (Exception e) { //Fail silently } } if(clazz != null) { logger.info("Registering " + clazz.getName() + " for atmosphere bypass"); zmaster587.advancedRocketry.api.Configuration.bypassEntity.add(clazz); } else logger.warn("Cannot find " + str + " while registering entity for atmosphere bypass"); } //Free memory entityList = null; logger.info("End registering entity atmosphere bypass"); //Register asteriodOres if(!zmaster587.advancedRocketry.api.Configuration.asteriodOresBlackList) { for(String str : asteriodOres) zmaster587.advancedRocketry.api.Configuration.standardAsteroidOres.add(str); } //Register geodeOres if(!zmaster587.advancedRocketry.api.Configuration.geodeOresBlackList) { for(String str : geodeOres) zmaster587.advancedRocketry.api.Configuration.standardGeodeOres.add(str); } //Register laserDrill ores if(!zmaster587.advancedRocketry.api.Configuration.laserDrillOresBlackList) { for(String str : orbitalLaserOres) zmaster587.advancedRocketry.api.Configuration.standardLaserDrillOres.add(str); } //Do blacklist stuff for ore registration for(String oreName : OreDictionary.getOreNames()) { if(zmaster587.advancedRocketry.api.Configuration.asteriodOresBlackList && oreName.startsWith("ore")) { boolean found = false; for(String str : asteriodOres) { if(oreName.equals(str)) { found = true; break; } } if(!found) zmaster587.advancedRocketry.api.Configuration.standardAsteroidOres.add(oreName); } if(zmaster587.advancedRocketry.api.Configuration.geodeOresBlackList && oreName.startsWith("ore")) { boolean found = false; for(String str : geodeOres) { if(oreName.equals(str)) { found = true; break; } } if(!found) zmaster587.advancedRocketry.api.Configuration.standardGeodeOres.add(oreName); } if(zmaster587.advancedRocketry.api.Configuration.laserDrillOresBlackList && oreName.startsWith("ore")) { boolean found = false; for(String str : orbitalLaserOres) { if(oreName.equals(str)) { found = true; break; } } if(!found) zmaster587.advancedRocketry.api.Configuration.standardLaserDrillOres.add(oreName); } } //Load XML recipes LibVulpes.instance.loadXMLRecipe(TileCuttingMachine.class); LibVulpes.instance.loadXMLRecipe(TilePrecisionAssembler.class); LibVulpes.instance.loadXMLRecipe(TileChemicalReactor.class); LibVulpes.instance.loadXMLRecipe(TileCrystallizer.class); LibVulpes.instance.loadXMLRecipe(TileElectrolyser.class); LibVulpes.instance.loadXMLRecipe(TileElectricArcFurnace.class); LibVulpes.instance.loadXMLRecipe(TileLathe.class); LibVulpes.instance.loadXMLRecipe(TileRollingMachine.class); } @EventHandler public void serverStarted(FMLServerStartedEvent event) { for (int dimId : DimensionManager.getInstance().getLoadedDimensions()) { DimensionProperties properties = DimensionManager.getInstance().getDimensionProperties(dimId); if(!properties.isNativeDimension && properties.getId() == zmaster587.advancedRocketry.api.Configuration.MoonId && !Loader.isModLoaded("GalacticraftCore")) { properties.isNativeDimension = true; } } } @EventHandler public void serverStarting(FMLServerStartingEvent event) { event.registerServerCommand(new WorldCommand()); int dimOffset = DimensionManager.dimOffset; //Open ore files File file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/oreConfig.xml"); logger.info("Checking for ore config at " + file.getAbsolutePath()); if(!file.exists()) { logger.info(file.getAbsolutePath() + " not found, generating"); try { file.createNewFile(); BufferedWriter stream; stream = new BufferedWriter(new FileWriter(file)); stream.write("<OreConfig>\n</OreConfig>"); stream.close(); } catch (IOException e) { e.printStackTrace(); } } else { XMLOreLoader oreLoader = new XMLOreLoader(); try { oreLoader.loadFile(file); List<SingleEntry<HashedBlockPosition, OreGenProperties>> mapping = oreLoader.loadPropertyFile(); for(Entry<HashedBlockPosition, OreGenProperties> entry : mapping) { int pressure = entry.getKey().x; int temp = entry.getKey().y; if(pressure == -1) { if(temp != -1) { OreGenProperties.setOresForTemperature(Temps.values()[temp], entry.getValue()); } } else if(temp == -1) { if(pressure != -1) { OreGenProperties.setOresForPressure(AtmosphereTypes.values()[pressure], entry.getValue()); } } else { OreGenProperties.setOresForPressureAndTemp(AtmosphereTypes.values()[pressure], Temps.values()[temp], entry.getValue()); } } } catch (IOException e) { e.printStackTrace(); } } //End open and load ore files //Load planet files //Note: loading this modifies dimOffset DimensionPropertyCoupling dimCouplingList = null; XMLPlanetLoader loader = null; file = new File("./config/" + zmaster587.advancedRocketry.api.Configuration.configFolder + "/planetDefs.xml"); logger.info("Checking for config at " + file.getAbsolutePath()); if(file.exists()) { logger.info("Advanced Planet Config file Found!"); loader = new XMLPlanetLoader(); try { loader.loadFile(file); dimCouplingList = loader.readAllPlanets(); DimensionManager.dimOffset += dimCouplingList.dims.size(); } catch(IOException e) { } } //End load planet files //Register hard coded dimensions if(!zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().loadDimensions(zmaster587.advancedRocketry.dimension.DimensionManager.filePath) || resetFromXml) { int numRandomGeneratedPlanets = 9; int numRandomGeneratedGasGiants = 1; if(resetFromXml) { zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions(); zmaster587.advancedRocketry.api.Configuration.MoonId = -1; //Delete old dimensions File dir = new File(net.minecraftforge.common.DimensionManager.getCurrentSaveRootDirectory() + "/" + DimensionManager.workingPath); for(File file2 : dir.listFiles()) { if(file2.getName().startsWith("DIM") && !file2.getName().equals("DIM" + zmaster587.advancedRocketry.api.Configuration.spaceDimId)) { try { FileUtils.deleteDirectory(file2); } catch (IOException e) { e.printStackTrace(); } } } } boolean loadedFromXML = false; if(dimCouplingList != null) { logger.info("Loading initial planet config!"); for(StellarBody star : dimCouplingList.stars) { DimensionManager.getInstance().addStar(star); } for(DimensionProperties properties : dimCouplingList.dims) { DimensionManager.getInstance().registerDimNoUpdate(properties, properties.isNativeDimension); properties.setStar(properties.getStar()); } for(StellarBody star : dimCouplingList.stars) { numRandomGeneratedPlanets = loader.getMaxNumPlanets(star); numRandomGeneratedGasGiants = loader.getMaxNumGasGiants(star); generateRandomPlanets(star, numRandomGeneratedPlanets, numRandomGeneratedGasGiants); } loadedFromXML = true; } if(zmaster587.advancedRocketry.api.Configuration.MoonId == -1) zmaster587.advancedRocketry.api.Configuration.MoonId = DimensionManager.getInstance().getNextFreeDim(dimOffset); if(zmaster587.advancedRocketry.api.Configuration.MoonId != -1) { DimensionProperties dimensionProperties = new DimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId); dimensionProperties.setAtmosphereDensityDirect(0); dimensionProperties.averageTemperature = 20; dimensionProperties.rotationalPeriod = 128000; dimensionProperties.gravitationalMultiplier = .166f; //Actual moon value dimensionProperties.setName("Luna"); dimensionProperties.orbitalDist = 150; dimensionProperties.addBiome(AdvancedRocketryBiomes.moonBiome); dimensionProperties.setParentPlanet(DimensionManager.overworldProperties); dimensionProperties.setStar(DimensionManager.getSol()); dimensionProperties.isNativeDimension = !Loader.isModLoaded("GalacticraftCore"); DimensionManager.getInstance().registerDimNoUpdate(dimensionProperties, !Loader.isModLoaded("GalacticraftCore")); } if(!loadedFromXML) { generateRandomPlanets(DimensionManager.getSol(), numRandomGeneratedPlanets, numRandomGeneratedGasGiants); StellarBody star = new StellarBody(); star.setTemperature(10); star.setPosX(300); star.setPosZ(-200); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Wolf 12"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 5, 0); star = new StellarBody(); star.setTemperature(170); star.setPosX(-200); star.setPosZ(80); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Epsilon ire"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 7, 0); star = new StellarBody(); star.setTemperature(200); star.setPosX(-150); star.setPosZ(250); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Proxima Centaurs"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 3, 0); star = new StellarBody(); star.setTemperature(70); star.setPosX(-150); star.setPosZ(-250); star.setId(DimensionManager.getInstance().getNextFreeStarId()); star.setName("Magnis Vulpes"); DimensionManager.getInstance().addStar(star); generateRandomPlanets(star, 2, 0); } } else { VersionCompat.upgradeDimensionManagerPostLoad(DimensionManager.prevBuild); if(Loader.isModLoaded("GalacticraftCore") ) { DimensionManager.getInstance().getDimensionProperties(zmaster587.advancedRocketry.api.Configuration.MoonId).isNativeDimension = false; } } //Clean up floating stations and satellites if(resetFromXml) { //Move all space stations to the overworld for(ISpaceObject obj : SpaceObjectManager.getSpaceManager().getSpaceObjects()) { if(obj.getOrbitingPlanetId() != 0 ) { SpaceObjectManager.getSpaceManager().moveStationToBody(obj, 0, false); } } //Satellites are cleaned up on their own as dimension properties are reset } //Attempt to load ore config from adv planet XML if(dimCouplingList != null) { for(DimensionProperties properties : dimCouplingList.dims) { //Register dimensions loaded by other mods if not already loaded if(!properties.isNativeDimension && properties.getStar() != null && !DimensionManager.getInstance().isDimensionCreated(properties.getId())) { for(StellarBody star : dimCouplingList.stars) { for(StellarBody loadedStar : DimensionManager.getInstance().getStars()) { if(star.getId() == properties.getStarId() && star.getName().equals(loadedStar.getName())) { DimensionManager.getInstance().registerDimNoUpdate(properties, false); properties.setStar(loadedStar); } } } } if(properties.oreProperties != null) { DimensionProperties loadedProps = DimensionManager.getInstance().getDimensionProperties(properties.getId()); if(loadedProps != null) loadedProps.oreProperties = properties.oreProperties; } } } // make sure to set dim offset back to original to make things consistant DimensionManager.dimOffset = dimOffset; } private void generateRandomPlanets(StellarBody star, int numRandomGeneratedPlanets, int numRandomGeneratedGasGiants) { Random random = new Random(System.currentTimeMillis()); for(int i = 0; i < numRandomGeneratedGasGiants; i++) { int baseAtm = 180; int baseDistance = 100; DimensionProperties properties = DimensionManager.getInstance().generateRandomGasGiant(star.getId(), "",baseDistance + 50,baseAtm,125,100,100,75); if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(8); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(star.getId(), properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); if(moonProperties == null) continue; moonProperties.setParentPlanet(properties); star.removePlanet(moonProperties); } } } for(int i = 0; i < numRandomGeneratedPlanets; i++) { int baseAtm = 75; int baseDistance = 100; if(i % 4 == 0) { baseAtm = 0; } else if(i != 6 && (i+2) % 4 == 0) baseAtm = 120; if(i % 3 == 0) { baseDistance = 170; } else if((i + 1) % 3 == 0) { baseDistance = 30; } DimensionProperties properties = DimensionManager.getInstance().generateRandom(star.getId(), baseDistance,baseAtm,125,100,100,75); if(properties == null) continue; if(properties.gravitationalMultiplier >= 1f) { int numMoons = random.nextInt(4); for(int ii = 0; ii < numMoons; ii++) { DimensionProperties moonProperties = DimensionManager.getInstance().generateRandom(star.getId(), properties.getName() + ": " + ii, 25,100, (int)(properties.gravitationalMultiplier/.02f), 25, 100, 50); if(moonProperties == null) continue; moonProperties.setParentPlanet(properties); star.removePlanet(moonProperties); } } } } @EventHandler public void serverStopped(FMLServerStoppedEvent event) { zmaster587.advancedRocketry.dimension.DimensionManager.getInstance().unregisterAllDimensions(); zmaster587.advancedRocketry.cable.NetworkRegistry.clearNetworks(); SpaceObjectManager.getSpaceManager().onServerStopped(); zmaster587.advancedRocketry.api.Configuration.MoonId = -1; DimensionManager.getInstance().overworldProperties.resetProperties(); proxy.saveUILayout(config); } @SubscribeEvent public void registerOre(OreRegisterEvent event) { //Register ore products if(!zmaster587.advancedRocketry.api.Configuration.allowMakingItemsForOtherMods) return; for(AllowedProducts product : AllowedProducts.getAllAllowedProducts() ) { if(event.getName().startsWith(product.name().toLowerCase(Locale.ENGLISH))) { HashSet<String> list = modProducts.get(product); if(list == null) { list = new HashSet<String>(); modProducts.put(product, list); } list.add(event.getName().substring(product.name().length())); } } //GT uses stick instead of Rod if(event.getName().startsWith("stick")) { HashSet<String> list = modProducts.get(AllowedProducts.getProductByName("STICK")); if(list == null) { list = new HashSet<String>(); modProducts.put(AllowedProducts.getProductByName("STICK"), list); } list.add(event.getName().substring("stick".length())); } } }
package org.objectweb.proactive.examples.c3d.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.net.InetAddress; import java.net.UnknownHostException; import javax.swing.Box; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextArea; import javax.swing.border.TitledBorder; import org.objectweb.proactive.core.util.UrlBuilder; /** * The GUI class, which when extended gives a nice graphical frontend. * The actionPerformed method needs to be overloaded, to handle the protected field events. */ public abstract class DispatcherGUI implements ActionListener { protected JFrame mainFrame; protected JMenuItem exitMenuItem; protected JMenuItem benchmarkMenuItem; protected JMenuItem clearLogMenuItem; protected JTextArea logArea; protected DefaultListModel userListModel; private DefaultListModel availableEngineListModel; private DefaultListModel usedEngineListModel; protected JList availableEngineList; protected JList usedEngineList; protected JButton addEngineButton; protected JButton removeEngineButton; /** You might wish to add a window listener on the closing event... */ public DispatcherGUI(String title) { this.mainFrame = new JFrame(title); this.mainFrame.setContentPane(createMainPanel()); this.mainFrame.setJMenuBar(createMenuBar()); this.mainFrame.pack(); this.mainFrame.setVisible(true); } /** * Creates the menu which is used in the mainFrame */ private JMenuBar createMenuBar() { //First, the menu items clearLogMenuItem = new JMenuItem("Clear Log", KeyEvent.VK_C); exitMenuItem = new JMenuItem("Quit", KeyEvent.VK_Q); benchmarkMenuItem = new JMenuItem("Benchmark", KeyEvent.VK_B); // make them responsive benchmarkMenuItem.addActionListener(this); clearLogMenuItem.addActionListener(this); exitMenuItem.addActionListener(this); // The menu in the menu Bar. JMenu menu = new JMenu("Menu"); menu.setMnemonic(KeyEvent.VK_M); menu.add(clearLogMenuItem); menu.add(benchmarkMenuItem); menu.add(new JSeparator()); menu.add(exitMenuItem); // Create the wrapping menuBar object JMenuBar menuBar = new JMenuBar(); menuBar.add(menu); return menuBar; } /** * Contains all the components, except the menuBar. */ private JComponent createMainPanel() { // The BorderLayout was used to have the log use as much space as possible. JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); mainPanel.add(createInfoText(), BorderLayout.NORTH); mainPanel.add(createLogPanel("Application Log", new Dimension(200, 200)), BorderLayout.CENTER); JPanel extraPanel = new JPanel(); extraPanel.setLayout(new GridLayout(2, 1)); extraPanel.add(createUserListPanel()); extraPanel.add(createEnginePanel()); mainPanel.add(extraPanel, BorderLayout.SOUTH); return mainPanel; } /** * The top part, stating name of program & machine name */ private JComponent createInfoText() { JPanel infoPanel = new JPanel(); // TODO : the box should have been enough, but the label overwrites the menu!!! Box box = Box.createVerticalBox(); String localhostName = ""; try { localhostName = UrlBuilder.getHostNameorIP(InetAddress.getLocalHost()); } catch (UnknownHostException e) { localhostName = "unknown host name!"; } Label machine = new Label("on " + localhostName + " (" + System.getProperty("os.name") + ")", Label.CENTER); Label header = new Label("C3D Dispatcher", Label.CENTER); header.setFont(new Font("SansSerif", Font.ITALIC + Font.BOLD, 18)); box.add(header); box.add(machine); infoPanel.add(box); infoPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, header.getSize().height + machine.getSize().height)); return infoPanel; } private JComponent createUserListPanel() { this.userListModel = new DefaultListModel(); JScrollPane panel = createListPanel(new JList(this.userListModel)); panel.setBorder(new TitledBorder("List of users")); return panel; } /** * The list of users connected. */ private JScrollPane createListPanel(JList jlist) { JScrollPane scroll = new JScrollPane(jlist); scroll.setMaximumSize(new Dimension(Integer.MAX_VALUE, 100)); return scroll; } /** * A GridBag containing selectable engines, and buttons to add/remove them. */ private JComponent createEnginePanel() { // two parallel boxes, which contain used & available engines Box left = Box.createVerticalBox(); Box right = Box.createVerticalBox(); left.add(new JLabel("Available engines")); right.add(new JLabel("Engines used")); this.availableEngineListModel = new DefaultListModel(); this.availableEngineList = new JList(this.availableEngineListModel); JScrollPane availPanel = createListPanel(this.availableEngineList); left.add(availPanel); this.usedEngineListModel = new DefaultListModel(); this.usedEngineList = new JList(this.usedEngineListModel); JComponent usedPanel = createListPanel(this.usedEngineList); right.add(usedPanel); this.addEngineButton = new JButton("Add engine"); this.addEngineButton.addActionListener(this); left.add(this.addEngineButton); this.removeEngineButton = new JButton("Remove engine"); this.removeEngineButton.addActionListener(this); right.add(this.removeEngineButton); JPanel engineChoicePanel = new JPanel(); engineChoicePanel.setLayout(new GridLayout(1, 2)); engineChoicePanel.add(left); engineChoicePanel.add(right); return engineChoicePanel; } private JComponent createLogPanel(String title, Dimension prefSize) { this.logArea = new JTextArea(); this.logArea.setEditable(false); JScrollPane scroll = new JScrollPane(this.logArea); scroll.setBorder(new TitledBorder(title)); scroll.setPreferredSize(prefSize); return scroll; } /** * Destroy the graphical window */ public void trash() { this.mainFrame.setVisible(false); this.mainFrame.dispose(); } /** * Should implement the response to the events generated by the * protected fields of the GUI class. */ public abstract void actionPerformed(ActionEvent e); /** * Add a user to the list of users. */ public void addUser(String userName) { this.userListModel.addElement(userName); } /** * Remove a user from the list of users. */ public void removeUser(String userName) { this.userListModel.removeElement(userName); } /** * set an engine as available, removing it if needed from the used list */ public void addAvailableEngine(String engineName) { this.availableEngineListModel.addElement(engineName); this.usedEngineListModel.removeElement(engineName); } /** * set an engine as used, removing it if needed from the available list */ public void addUsedEngine(String engineName) { this.usedEngineListModel.addElement(engineName); this.availableEngineListModel.removeElement(engineName); } /** * Used for benchmarking: put n engines as "used" * @return the names of all the engines used once set */ public String[] setEngines(int nbEnginesToUse) { // remove all engines. while (this.usedEngineListModel.size() > nbEnginesToUse) { String noMoreUsed = (String) this.usedEngineListModel.get(0); addAvailableEngine(noMoreUsed); } while ((this.usedEngineListModel.size() < nbEnginesToUse) && !this.availableEngineListModel.isEmpty()) { String nowUsed = (String) this.availableEngineListModel.get(0); addUsedEngine(nowUsed); } String[] engineNames = new String[nbEnginesToUse]; for (int i = 0; i < this.usedEngineListModel.size(); i++) { engineNames[i] = (String) this.usedEngineListModel.get(i); } return engineNames; } /** Append the given log to the GUI log area */ public void log(String log) { logArea.append(log); //logArea.setCaretPosition(logArea.getText().length()); // move scrollbar down if needed } public void clearLog() { logArea.setText(""); } }
package org.pentaho.di.trans.steps.fieldsplitter; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleValueException; import org.pentaho.di.core.row.RowDataUtil; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; /** * Split a single String fields into multiple parts based on certain conditions. * * @author Matt * @since 31-Okt-2003 */ public class FieldSplitter extends BaseStep implements StepInterface { private FieldSplitterMeta meta; private FieldSplitterData data; public FieldSplitter(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } private Object[] splitField(Object[] r) throws KettleValueException { if (first) { // get the RowMeta data.previousMeta = getInputRowMeta().clone(); // search field data.fieldnr=data.previousMeta.indexOfValue(meta.getSplitField()); if (data.fieldnr<0) { throw new KettleValueException(Messages.getString("FieldSplitter.Log.CouldNotFindFieldToSplit",meta.getSplitField())); //$NON-NLS-1$ //$NON-NLS-2$ } // only String type allowed if (!data.previousMeta.getValueMeta(data.fieldnr).isString()) { throw new KettleValueException((Messages.getString("FieldSplitter.Log.SplitFieldNotValid",meta.getSplitField()))); //$NON-NLS-1$ //$NON-NLS-2$ } // prepare the outputMeta data.outputMeta= getInputRowMeta().clone(); meta.getFields(data.outputMeta, getStepname(), null, null, this); } String v=data.previousMeta.getString(r, data.fieldnr); // reserve room Object[] outputRow = RowDataUtil.allocateRowData(data.outputMeta.size()); int nrExtraFields = meta.getFieldID().length - 1; for (int i=0;i<data.fieldnr;i++) outputRow[i] = r[i]; for (int i=data.fieldnr+1;i<data.outputMeta.size();i++) outputRow[i+nrExtraFields] = r[i]; // OK, now we have room in the middle to place the fields... // Named values info.id[0] not filled in! boolean use_ids = meta.getFieldID().length>0 && meta.getFieldID()[0]!=null && meta.getFieldID()[0].length()>0; Object value=null; if (use_ids) { if (log.isDebug()) logDebug(Messages.getString("FieldSplitter.Log.UsingIds")); //$NON-NLS-1$ // pol all split fields // Loop over the specified field list // If we spot the corresponding id[] entry in pol, add the value String pol[] = new String[meta.getField().length]; int prev=0; int i=0; while(v!=null && prev<v.length() && i<pol.length) { pol[i]=polNext(v, meta.getDelimiter(), prev); if (log.isDebug()) logDebug(Messages.getString("FieldSplitter.Log.SplitFieldsInfo",pol[i],String.valueOf(prev))); //$NON-NLS-1$ //$NON-NLS-2$ prev+=pol[i].length()+meta.getDelimiter().length(); i++; } // We have to add info.field.length variables! for (i=0;i<meta.getField().length;i++) { // We have a field, search the corresponding pol[] entry. String split=null; for (int p=0; p<pol.length && split==null; p++) { // With which line does pol[p] correspond? if (pol[p]!=null && pol[p].indexOf(meta.getFieldID()[i])>=0) split=pol[p]; } // Optionally remove the indicator if (split!=null && meta.removeID()[i]) { StringBuffer sb = new StringBuffer(split); int idx = sb.indexOf(meta.getFieldID()[i]); sb.delete(idx, idx+meta.getFieldID()[i].length()); split=sb.toString(); } if (split==null) split=""; //$NON-NLS-1$ if (log.isDebug()) logDebug(Messages.getString("FieldSplitter.Log.SplitInfo")+split); //$NON-NLS-1$ try { value = data.outputMeta.getValueMeta(data.fieldnr+i).convertDataFromString ( split, data.previousMeta.getValueMeta(data.fieldnr), meta.getFieldDefault()[i], "", // --> The default String value in case a field is empty. //$NON-NLS-1$ ValueMetaInterface.TRIM_TYPE_BOTH ); } catch(Exception e) { throw new KettleValueException(Messages.getString("FieldSplitter.Log.ErrorConvertingSplitValue",split,meta.getSplitField()+"]!"), e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } outputRow[data.fieldnr+i]=value; } } else { if (log.isDebug()) logDebug(Messages.getString("FieldSplitter.Log.UsingPositionOfValue")); //$NON-NLS-1$ int prev=0; for (int i=0;i<meta.getField().length;i++) { String pol = polNext(v, meta.getDelimiter(), prev); if (log.isDebug()) logDebug(Messages.getString("FieldSplitter.Log.SplitFieldsInfo",pol,String.valueOf(prev))); //$NON-NLS-1$ //$NON-NLS-2$ prev+=(pol==null?0:pol.length()) + meta.getDelimiter().length(); try { value = data.outputMeta.getValueMeta(data.fieldnr+i).convertDataFromString ( pol, data.previousMeta.getValueMeta(data.fieldnr), meta.getFieldDefault()[i], "", // --> The default String value in case a field is empty. //$NON-NLS-1$ ValueMetaInterface.TRIM_TYPE_BOTH ); } catch(Exception e) { throw new KettleValueException(Messages.getString("FieldSplitter.Log.ErrorConvertingSplitValue",pol,meta.getSplitField()+"]!"), e); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } outputRow[data.fieldnr+i]=value; } } return outputRow; } private static final String polNext(String str, String del, int start) { String retval; if (str==null || start>=str.length()) return ""; //$NON-NLS-1$ int next = str.indexOf(del, start); if (next == start) // ;; or ,, : two consecutive delimiters { retval=""; //$NON-NLS-1$ } else if (next > start) // part of string { retval=str.substring(start, next); } else // Last field in string { retval=str.substring(start); } return retval; } public synchronized boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(FieldSplitterMeta)smi; data=(FieldSplitterData)sdi; Object[] r=getRow(); // get row from rowset, wait for our turn, indicate busy! if (r==null) // no more input to be expected... { setOutputDone(); return false; } Object[] outputRowData = splitField(r); putRow(data.outputMeta, outputRowData); if (checkFeedback(linesRead)) logBasic(Messages.getString("FieldSplitter.Log.LineNumber")+linesRead); //$NON-NLS-1$ return true; } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(FieldSplitterMeta)smi; data=(FieldSplitterData)sdi; if (super.init(smi, sdi)) { // Add init code here. return true; } return false; } // Run is were the action happens! public void run() { try { logBasic(Messages.getString("System.Log.StartingToRun")); //$NON-NLS-1$ while (processRow(meta, data) && !isStopped()); } catch(Throwable t) { logError(Messages.getString("System.Log.UnexpectedError")+" : "); //$NON-NLS-1$ //$NON-NLS-2$ logError(Const.getStackTracker(t)); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
package org.pentaho.di.trans.steps.numberrange; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.ObjectId; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDataInterface; import org.pentaho.di.trans.step.StepInterface; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.w3c.dom.Node; /** * Configuration for the NumberRangePlugin * * @author ronny.roeller@fredhopper.com * */ public class NumberRangeMeta extends BaseStepMeta implements StepMetaInterface { private String inputField; private String outputField; private String fallBackValue; private List<NumberRangeRule> rules; public NumberRangeMeta() { super(); } public void emptyRules() { rules = new LinkedList<NumberRangeRule>(); } public NumberRangeMeta(Node stepnode,List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { loadXML(stepnode, databases, counters); } public NumberRangeMeta(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { readRep(rep, id_step, databases, counters); } public String getXML() { StringBuffer retval = new StringBuffer(); retval.append(" ").append(XMLHandler.addTagValue("inputField", inputField)); retval.append(" ").append(XMLHandler.addTagValue("outputField", outputField)); retval.append(" ").append(XMLHandler.addTagValue("fallBackValue", getFallBackValue())); retval.append(" <rules>").append(Const.CR); //$NON-NLS-1$ for (NumberRangeRule rule : rules) { retval.append(" <rule>").append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("lower_bound", rule.getLowerBound())); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("upper_bound", rule.getUpperBound())); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("value", rule.getValue())); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </rule>").append(Const.CR); //$NON-NLS-1$ } retval.append(" </rules>").append(Const.CR); //$NON-NLS-1$ return retval.toString(); } public void getFields(RowMetaInterface row, String name, RowMetaInterface[] info, StepMeta nextStep, VariableSpace space) throws KettleStepException { ValueMetaInterface mcValue = new ValueMeta(outputField, ValueMetaInterface.TYPE_STRING); mcValue.setOrigin(name); mcValue.setLength(255); row.addValueMeta(mcValue); } public Object clone() { Object retval = super.clone(); return retval; } public void loadXML(Node stepnode, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleXMLException { try { inputField = XMLHandler.getTagValue(stepnode, "inputField"); outputField = XMLHandler.getTagValue(stepnode, "outputField"); emptyRules(); String fallBackValue = XMLHandler.getTagValue(stepnode, "fallBackValue"); setFallBackValue(fallBackValue); Node fields = XMLHandler.getSubNode(stepnode, "rules"); //$NON-NLS-1$ int count = XMLHandler.countNodes(fields, "rule"); //$NON-NLS-1$ for (int i = 0; i < count; i++) { Node fnode = XMLHandler.getSubNodeByNr(fields, "rule", i); //$NON-NLS-1$ String lowerBoundStr = XMLHandler.getTagValue(fnode, "lower_bound"); //$NON-NLS-1$ String upperBoundStr = XMLHandler.getTagValue(fnode, "upper_bound"); //$NON-NLS-1$ String value = XMLHandler.getTagValue(fnode, "value"); //$NON-NLS-1$ double lowerBound = Double.parseDouble(lowerBoundStr); double upperBound = Double.parseDouble(upperBoundStr); addRule(lowerBound, upperBound, value); } } catch (Exception e) { throw new KettleXMLException("Unable to read step info from XML node", e); } } public void setDefault() { emptyRules(); setFallBackValue("unknown"); addRule(-Double.MAX_VALUE, 5, "Less than 5"); addRule(5, 10, "5-10"); addRule(10, Double.MAX_VALUE, "More than 10"); inputField = ""; outputField = "range"; } public void readRep(Repository rep, ObjectId id_step, List<DatabaseMeta> databases, Map<String, Counter> counters) throws KettleException { try { inputField = rep.getStepAttributeString(id_step, "inputField"); outputField = rep.getStepAttributeString(id_step, "outputField"); emptyRules(); String fallBackValue = rep.getStepAttributeString(id_step, "fallBackValue"); setFallBackValue(fallBackValue); int nrfields = rep.countNrStepAttributes(id_step, "lower_bound"); //$NON-NLS-1$ for (int i = 0; i < nrfields; i++) { String lowerBoundStr = rep.getStepAttributeString(id_step, i, "lower_bound"); //$NON-NLS-1$ String upperBoundStr = rep.getStepAttributeString(id_step, i, "upper_bound"); //$NON-NLS-1$ String value = rep.getStepAttributeString(id_step, i, "value"); //$NON-NLS-1$ double lowerBound = Double.parseDouble(lowerBoundStr); double upperBound = Double.parseDouble(upperBoundStr); addRule(lowerBound, upperBound, value); } } catch (Exception dbe) { throw new KettleException("error reading step with id_step="+ id_step + " from the repository", dbe); } } public void saveRep(Repository rep, ObjectId id_transformation, ObjectId id_step) throws KettleException { try { rep.saveStepAttribute(id_transformation, id_step, "inputField", inputField); rep.saveStepAttribute(id_transformation, id_step, "outputField",outputField); rep.saveStepAttribute(id_transformation, id_step, "fallBackValue", getFallBackValue()); int i = 0; for (NumberRangeRule rule : rules) { rep.saveStepAttribute(id_transformation, id_step, i,"lower_bound", String.valueOf(rule.getLowerBound())); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i,"upper_bound", String.valueOf(rule.getUpperBound())); //$NON-NLS-1$ rep.saveStepAttribute(id_transformation, id_step, i, "value", String.valueOf(rule.getValue())); //$NON-NLS-1$ i++; } } catch (KettleDatabaseException dbe) { throw new KettleException( "Unable to save step information to the repository, id_step="+ id_step, dbe); } } public void check(List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepinfo, RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info) { CheckResult cr; if (prev == null || prev.size() == 0) { cr = new CheckResult(CheckResult.TYPE_RESULT_WARNING, "Not receiving any fields from previous steps!", stepinfo); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is connected to previous one, receiving " + prev.size() + " fields", stepinfo); remarks.add(cr); } // See if we have input streams leading to this step! if (input.length > 0) { cr = new CheckResult(CheckResult.TYPE_RESULT_OK, "Step is receiving info from other steps.", stepinfo); remarks.add(cr); } else { cr = new CheckResult(CheckResult.TYPE_RESULT_ERROR, "No input received from other steps!", stepinfo); remarks.add(cr); } } public StepInterface getStep(StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr, TransMeta transMeta, Trans disp) { return new NumberRange(stepMeta, stepDataInterface, cnr, transMeta, disp); } public StepDataInterface getStepData() { return new NumberRangeData(); } public String getInputField() { return inputField; } public String getOutputField() { return outputField; } public void setOutputField(String outputField) { this.outputField = outputField; } public List<NumberRangeRule> getRules() { return rules; } public String getFallBackValue() { return fallBackValue; } public void setInputField(String inputField) { this.inputField = inputField; } public void setFallBackValue(String fallBackValue) { this.fallBackValue = fallBackValue; } public void addRule(double lowerBound, double upperBound, String value) { NumberRangeRule rule = new NumberRangeRule(lowerBound, upperBound, value); rules.add(rule); } public boolean supportsErrorHandling() { return true; } }
package org.teachingkidsprogramming.section03ifs; import org.junit.Assert; import org.junit.Test; import org.teachingextensions.logo.utils.EventUtils.MessageBox; @SuppressWarnings("unused") public class DeepDive03Ifs { // Step 1: SELECT the method name (doesABear on line 19), then click the Run Button // Keyboard shortcut to run -> PC: Ctrl+F11 or Mac: Command+fn+F11 // Step 2: READ the name of the method that failed // Step 4: SAY at least one thing you just learned // Step 5: GO to the next method @Test public void doesABear() throws Exception { String bearPoopPlace = ""; if (true) { bearPoopPlace = "woods"; } Assert.assertEquals("woods", bearPoopPlace); } @Test public void neverEverEver() throws Exception { String dessert = "chocolate"; if (false) { dessert = "ketchup"; } Assert.assertEquals("chocolate", dessert); } @Test public void notEverEverEver() throws Exception { String dessert = "chocolate"; if (!true) { dessert = "ketchup"; } Assert.assertEquals("chocolate", dessert); } @Test public void isThePopeCatholic() throws Exception { String pope = ""; if (true) { pope = "Catholic"; } Assert.assertEquals("Catholic", pope); } @Test public void trueOrFalse() throws Exception { String animal = "cat"; boolean elephant = true; if (elephant) { animal = "flat " + animal; } Assert.assertEquals("flat cat", animal); } @Test public void letSleepingBabiesLie() throws Exception { String babySounds = ""; boolean sleeping = false; if (sleeping) { babySounds = "zzzzzzzzzzzz"; } else { babySounds = "waaaaaahhh!"; } Assert.assertEquals("waaaaaahhh!", babySounds); } @Test public void howCoachThinks() throws Exception { String coachSays = "try harder"; int percentEffort = 110; if (percentEffort == 110) { coachSays = "good job"; } Assert.assertEquals("good job", coachSays); } @Test public void lessThan() throws Exception { String modeOfTransportation = ""; int age = 15; if (age < 16) { modeOfTransportation = "keep walking"; } else { modeOfTransportation = "drive away"; } Assert.assertEquals("keep walking", modeOfTransportation); } @Test public void greaterThan() throws Exception { String kidSays = ""; int numberOfIceCreams = 6; if (numberOfIceCreams > 4) { kidSays = "I think I'm gonna barf"; } else { kidSays = "More ice cream!"; } Assert.assertEquals("I think I'm gonna barf", kidSays); } @Test public void notEqual() throws Exception { String playerSays = ""; int cards = 52; if (cards != 52) { playerSays = "Not playing with a full deck!"; } else { playerSays = "Game on!"; } Assert.assertEquals("Game on!", playerSays); } @Test public void equalsForStrings() throws Exception { String knockKnock = ""; String whosThere = "bananas"; if (whosThere.equals("bananas")) { knockKnock = "Who's there?"; } else if (whosThere.equals("orange")) { knockKnock = "Orange you glad I didn't say bananas?"; } Assert.assertEquals("Who's there?", knockKnock); } @Test public void thisAndThat() throws Exception { String time = ""; int score = 4; int years = 7; if (score == 4 && years == 7) { time = "Presidential"; } Assert.assertEquals("Presidential", time); } @Test public void theBeginningOrEnd() throws Exception { String shoppingList = ""; int age = 90; if (age <= 2 || 90 <= age) { shoppingList = "diapers"; } Assert.assertEquals("diapers", shoppingList); } @Test public void ifInHighSchool() throws Exception { String status = ""; int age = 18; if (age <= 15) { status = "smarty"; } else if (age > 19) { status = "dummy"; } else { status = "normal"; } Assert.assertEquals("normal", status); } @Test public void nestedIfOrPigsInABlanket() throws Exception { String status = ""; String animal = "PIG"; boolean isWinningKarate = false; if (animal.equalsIgnoreCase("pig")) { if (isWinningKarate) { status = "pork chop"; } else { status = "hambulance"; } } Assert.assertEquals("hambulance", status); } @Test public void semicolonsMessUpIfStatements() throws Exception { String dessert = "chocolate"; if (false) { dessert = "ketchup"; } Assert.assertEquals("chocolate", dessert); } // test for Choose Your Own Adventure // our very first test :) @Test public void cyoaWakeUpTest() throws Exception { String result = MessageBox.askForTextInput("Do you want to 'wake up' or 'explore' the dream?"); // test that user entered "hello" Assert.assertEquals(result, "wake up"); } @Test public void TestNumberTwo() throws Exception { String result = MessageBox.askForTextInput("Do you want to 'wake up' or 'explore' the dream?"); Assert.assertEquals(result, "explore"); } @Test public void cyoaNoAnswerInputTest() throws Exception { String result = MessageBox.askForTextInput("Do you want to 'wake up' or 'explore' the dream?"); Assert.assertEquals("", result); } @Test public void ifStatementsAreCool() throws Exception { String teacherSays = "may"; if (false) { teacherSays = "can"; } Assert.assertEquals("may", teacherSays); } public void howManyLaps() throws Exception { int days = ____; int lapsPerDay = ____; } /** * Ignore the following, It's needed to run the deep dive * * * * * * * * * * */ public boolean _____ = false; //public boolean _ = false; public boolean ______ = true; public String ___ = "You need to fill in the blank ___"; public Integer ____ = null; public String ___() { return ___; } }
package org.usfirst.frc.team997.robot.commands; import org.usfirst.frc.team997.robot.Robot; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; public class DriveToSetpoint extends Command { private final double setpoint, speed; public DriveToSetpoint(double speed, double distance) { requires(Robot.driveTrain); this.setpoint = distance; this.speed = speed; } // set up a default of half speed. This might still // be too fast. public DriveToSetpoint(double distance) { this(0.5, distance); } // Called just before this Command runs the first time protected void initialize() { Robot.driveTrain.resetEncoders(); Robot.driveTrain.resetGyro(); } // Called repeatedly when this Command is scheduled to run protected void execute() { double adjust = Robot.driveTrain.getGyro() / 10; final double threshold = .1; // ensure doesn't drastically swerve from readings. if (adjust > threshold) adjust = threshold; else if (adjust < -threshold) adjust = -threshold; SmartDashboard.putNumber("Gyro Drive Straight Adjustment: ", adjust); Robot.driveTrain.driveVoltage(this.speed - adjust, this.speed + adjust); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return Robot.driveTrain.getAverageEncoders() > setpoint; } // Called once after isFinished returns true protected void end() { Robot.driveTrain.driveVoltage(0, 0); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { Robot.driveTrain.driveVoltage(0, 0); } }
package pt.up.fe.aiad.scheduler.agentbehaviours; import jade.core.AID; import jade.core.behaviours.SimpleBehaviour; import jade.lang.acl.ACLMessage; import jade.lang.acl.MessageTemplate; import pt.up.fe.aiad.scheduler.ScheduleEvent; import pt.up.fe.aiad.scheduler.SchedulerAgent; import pt.up.fe.aiad.scheduler.Serializer; import pt.up.fe.aiad.utils.TimeInterval; import java.util.*; import java.util.function.Predicate; public class ADOPTBehaviour extends SimpleBehaviour { private boolean allFinished = false; private SchedulerAgent _agent; public HashMap<String, VirtualAgent> _virtualAgents = new HashMap<>(); public static class Cost { public String sender; public HashMap<String, TimeInterval> context; public int lb; public int ub; } public static class Value { public String sender; public TimeInterval chosenValue; } public static class Threshold { public int t; public HashMap<String, TimeInterval> context; } public static class VirtualAgent { ScheduleEvent _event; SchedulerAgent _masterAgent; private final ADOPTBehaviour _masterInstance; private TreeSet<String> _children = new TreeSet<>(); private TreeSet<String> _pseudoChildren = new TreeSet<>(); private TreeSet<String> _pseudoParents = new TreeSet<>(); private String _parentX; private String _leader; private boolean _receivedTerminateFromParent = false; private boolean _isFinished = false; HashMap<String, VirtualAgent> _agents; int threshold; TimeInterval di; HashMap<String, TimeInterval> CurrentContext; // agent -> time HashMap<TimeInterval, HashMap<String, Integer>> lb; HashMap<TimeInterval, HashMap<String, Integer>> ub; HashMap<TimeInterval, HashMap<String, Integer>> t; HashMap<TimeInterval, HashMap<String, HashMap<String, TimeInterval>>> context; // D -> child -> context (agent -> timeInterval) public VirtualAgent(ScheduleEvent scheduleEvent, SchedulerAgent schedulerAgent, ADOPTBehaviour masterInstance, DFSBehaviour.VirtualAgent va, String leader) { _event = scheduleEvent; _masterAgent = schedulerAgent; _masterInstance = masterInstance; _agents = _masterInstance._virtualAgents; _leader = leader; _parentX = va._parentX; _children = va._children; _pseudoChildren = va._pseudoChildren; _pseudoParents = va._pseudoParents; threshold = 0; CurrentContext = new HashMap<>(); lb = new HashMap<>(); ub = new HashMap<>(); t = new HashMap<>(); context = new HashMap<>(); for (TimeInterval d : _event._possibleSolutions) { HashMap<String, Integer> childLbs = new HashMap<>(); HashMap<String, Integer> childT = new HashMap<>(); HashMap<String, Integer> childUbs = new HashMap<>(); HashMap<String, HashMap<String, TimeInterval>> childContexts = new HashMap<>(); for (String xl : _children) { childLbs.put(xl, 0); childT.put(xl, 0); childUbs.put(xl, 10000); childContexts.put(xl, new HashMap<>()); } lb.put(d, childLbs); t.put(d, childT); ub.put(d, childUbs); context.put(d, childContexts); } di = _event._possibleSolutions.get(0); int currentDelta = delta(di); for (TimeInterval d : _event._possibleSolutions) { int tempDelta = delta(d); if (tempDelta < currentDelta) { di = d; currentDelta = tempDelta; } if (currentDelta == 0) { break; } } backTrack(); /*System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): leader: " + _leader); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): parent: " + _parentX); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): children: " + Arrays.toString(_children.toArray())); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): pchildren: " + Arrays.toString(_pseudoChildren.toArray())); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): pparent: " + Arrays.toString(_pseudoParents.toArray())); */ } int delta(TimeInterval v) { int d = _event.getCost(v); for (Map.Entry<String, TimeInterval> xj : CurrentContext.entrySet()) { if (xj.getKey().split("-", 2)[1].equals(_event.getName()) && !xj.getValue().equals(v)) d += 1000; } for (Map.Entry<String, VirtualAgent> others : _agents.entrySet()) { if (others.getKey().compareTo(_event.getName()) < 0 && others.getValue().di != null && others.getValue().di.overlaps(v)) d += 1000; } return d; } int LB(TimeInterval v) { int c = delta(v); for (String xl : _children) { c += lb.get(v).get(xl); } return c; } int UB(TimeInterval v) { int c = delta(v); for (String xl : _children) { c += ub.get(v).get(xl); } return c; } int LB() { int totalLB = Integer.MAX_VALUE; for (TimeInterval d : _event._possibleSolutions) { int tempLB = LB(d); if (tempLB < totalLB) totalLB = tempLB; if (totalLB == 0) break; } return totalLB; } int UB() { int totalUB = Integer.MAX_VALUE; for (TimeInterval d : _event._possibleSolutions) { int tempUB = UB(d); if (tempUB < totalUB) totalUB = tempUB; if (totalUB == 0) break; } return totalUB; } void backTrack() { /*System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): leader: " + _leader); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): parent: " + _parentX); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): children: " + Arrays.toString(_children.toArray())); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): pchildren: " + Arrays.toString(_pseudoChildren.toArray())); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): pparent: " + Arrays.toString(_pseudoParents.toArray())); System.err.println("ADOPT(" + _masterAgent.getLocalName() + "-" + _event.getName() + "): my Di is : " + di.toString() + " with cost " + delta(di)); */ int tempUB = UB(); if (threshold == tempUB) { chooseDiForMinUB(); } else if (LB(di) > threshold) { chooseDiForMinLB(); } //ENDIF //SEND (VALUE, (xi, di /* globals*/)) to each lower priority neighbor sendValue(); maintainAllocationInvariant(); if (threshold == tempUB) { if (_receivedTerminateFromParent || _leader.equals(_masterAgent.getName()+ "-" + _event.getName())) { sendTerminate(); _isFinished = true; _event._currentInterval = di; _event._currentCost = LB(di); _masterInstance.checkFinished(); return; } } sendCost(); } private void chooseDiForMinUB() { int currentUB = UB(di); for (TimeInterval d : _event._possibleSolutions) { int tempUB = UB(d); if (tempUB < currentUB) { currentUB = tempUB; di = d; } if (currentUB == 0) break; } } private void chooseDiForMinLB() { int currentLB = LB(di); for (TimeInterval d : _event._possibleSolutions) { int tempLB = LB(d); if (tempLB < currentLB) { currentLB = tempLB; di = d; } if (currentLB == 0) break; } } private void maintainThresholdInvariant() { int lb = LB(); int ub = UB(); if (threshold < lb) { threshold = lb; } if (threshold > ub) { threshold = ub; } } private void maintainAllocationInvariant() { int deltaDi = delta(di); while (threshold > deltaDi + getSumOfChildrenThresholdsForDi()) { String xl = getFirstChildIf((x) -> ub.get(di).get(x) > t.get(di).get(x)); t.get(di).put(xl, t.get(di).get(xl) + 1); } while (threshold < deltaDi + getSumOfChildrenThresholdsForDi()) { String xl = getFirstChildIf((x) -> t.get(di).get(x) > lb.get(di).get(x)); t.get(di).put(xl, t.get(di).get(xl) - 1); } sendThreshold(); } private void maintainChildThresholdInvariant() { for (TimeInterval d : _event._possibleSolutions) { for (String xl : _children) { if (lb.get(d).get(xl) > t.get(d).get(xl)) { t.get(d).put(xl, lb.get(d).get(xl)); } if (t.get(d).get(xl) > ub.get(d).get(xl)) { t.get(d).put(xl, ub.get(d).get(xl)); } } } } private String getFirstChildIf(Predicate<String> pred) { for (String x: _children) { if (pred.test(x)) return x; } return null; } private int getSumOfChildrenThresholdsForDi() { int c = 0; for (String xl : _children) { c += t.get(di).get(xl); } return c; } private void sendValue() { // SEND (VALUE, (xi, di)) to each lower priority neighbor Value value = new Value(); value.sender = _masterAgent.getName()+"-"+_event.getName(); value.chosenValue = di; String json = Serializer.ValueToJSON(value); HashMap<String, TreeSet<String>> eventTypesToAgents = new HashMap<>(); for (String xl : _children) { String[] strs = xl.split("-",2); if (eventTypesToAgents.keySet().contains(strs[1])) { eventTypesToAgents.get(strs[1]).add(strs[0]); } else { TreeSet<String> ags = new TreeSet<>(); ags.add(strs[0]); eventTypesToAgents.put(strs[1], ags); } } for (String xl : _pseudoChildren) { String[] strs = xl.split("-",2); if (eventTypesToAgents.keySet().contains(strs[1])) { eventTypesToAgents.get(strs[1]).add(strs[0]); } else { TreeSet<String> ags = new TreeSet<>(); ags.add(strs[0]); eventTypesToAgents.put(strs[1], ags); } } for (Map.Entry<String, TreeSet<String>> ea : eventTypesToAgents.entrySet()) { ACLMessage msg = new ACLMessage(ACLMessage.PROPOSE); for (String ag : ea.getValue()) { msg.addReceiver(new AID(ag, true)); } msg.setContent("VALUE-" + ea.getKey() + "-" + json); msg.setConversationId("ADOPT"); _masterAgent.send(msg); } } private void sendTerminate() { HashMap<String, TimeInterval> context = new HashMap<>(CurrentContext); context.put(_masterAgent.getName()+"-"+_event.getName(), di); String json = Serializer.ContextToJSON(context); HashMap<String, TreeSet<String>> eventTypesToAgents = new HashMap<>(); for (String xl : _children) { String[] strs = xl.split("-",2); if (eventTypesToAgents.keySet().contains(strs[1])) { eventTypesToAgents.get(strs[1]).add(strs[0]); } else { TreeSet<String> ags = new TreeSet<>(); ags.add(strs[0]); eventTypesToAgents.put(strs[1], ags); } } for (Map.Entry<String, TreeSet<String>> ea : eventTypesToAgents.entrySet()) { ACLMessage msg = new ACLMessage(ACLMessage.CANCEL); for (String ag : ea.getValue()) { msg.addReceiver(new AID(ag, true)); } msg.setContent("TERMINATE-" + ea.getKey() + "-" + json); msg.setConversationId("ADOPT"); _masterAgent.send(msg); } } private void sendCost() { // SEND (COST, xi, CurrentContext, LB,UB) to parent if (_parentX == null) //root return; Cost cost = new Cost(); cost.sender = _masterAgent.getName()+"-"+_event.getName(); cost.context = CurrentContext; cost.lb = LB(); cost.ub = UB(); String json = Serializer.CostToJSON(cost); ACLMessage msg = new ACLMessage(ACLMessage.CONFIRM); String[] strs = _parentX.split("-", 2); msg.addReceiver(new AID(strs[0], true)); msg.setContent("COST-" + strs[1] + "-" + json); msg.setConversationId("ADOPT"); _masterAgent.send(msg); } private void sendThreshold() { //SEND (THRESHOLD, t(di, xl), CurrentContext ) to each child xl for (String xl : _children) { Threshold thresh = new Threshold(); thresh.context = CurrentContext; thresh.t = t.get(di).get(xl); String json = Serializer.ThresholdToJSON(thresh); ACLMessage msg = new ACLMessage(ACLMessage.PROPAGATE); String[] strs = xl.split("-", 2); msg.addReceiver(new AID(strs[0], true)); msg.setContent("THRESHOLD-" + strs[1] + "-" + json); msg.setConversationId("ADOPT"); _masterAgent.send(msg); } } public void receiveCost(Cost cost) { String thisName = _masterAgent.getName()+"-"+_event.getName(); TimeInterval d = cost.context.get(thisName); cost.context.remove(thisName); if (!_receivedTerminateFromParent) { for (Map.Entry<String, TimeInterval> c : cost.context.entrySet()) { if (!_parentX.equals(c.getKey()) && !_children.contains(c.getKey()) && !_pseudoChildren.contains(c.getKey()) && !_pseudoParents.contains(c.getKey())) { CurrentContext.put(c.getKey(),c.getValue()); } } for (TimeInterval dPrime : _event._possibleSolutions) { for (String xl : _children) { if (!compatibleContexts(context.get(dPrime).get(xl), CurrentContext)) { lb.get(dPrime).put(xl, 0); t.get(dPrime).put(xl, 0); ub.get(dPrime).put(xl, 10000); context.get(dPrime).get(xl).clear(); } } } } if (d != null && compatibleContexts(cost.context, CurrentContext)) { lb.get(d).put(cost.sender, cost.lb); ub.get(d).put(cost.sender, cost.ub); context.get(d).put(cost.sender, cost.context); maintainChildThresholdInvariant(); maintainThresholdInvariant(); } backTrack(); } public void receiveValue(Value value) { if (!_receivedTerminateFromParent) { CurrentContext.put(value.sender, value.chosenValue); for (TimeInterval d : _event._possibleSolutions) { for (String xl : _children) { if (!compatibleContexts(context.get(d).get(xl), CurrentContext)) { lb.get(d).put(xl,0); t.get(d).put(xl,0); ub.get(d).put(xl,10000); context.get(d).put(xl,new HashMap<>()); } } } maintainThresholdInvariant(); backTrack(); } } public void receiveThreshold(Threshold thresh) { if (compatibleContexts(thresh.context, CurrentContext)) { threshold = thresh.t; maintainThresholdInvariant(); backTrack(); } } public void receiveTerminate(HashMap<String, TimeInterval> context) { CurrentContext = context; _receivedTerminateFromParent = true; _isFinished = true; _event._currentInterval = di; _event._currentCost = LB(di); _masterInstance.checkFinished(); backTrack(); } private boolean compatibleContexts(HashMap<String, TimeInterval> c1, HashMap<String, TimeInterval> c2) { Set<String> commonKeys = new TreeSet<>(c1.keySet()); commonKeys.retainAll(c2.keySet()); for (String xl : commonKeys) { if (!c1.get(xl).equals(c2.get(xl))) return false; } return true; } } private String _leader; private HashMap<String, DFSBehaviour.VirtualAgent> _agentsDFS; public ADOPTBehaviour(String leader, HashMap<String, DFSBehaviour.VirtualAgent> agents) { _leader = leader; _agentsDFS = agents; } @Override public void onStart() { _agent = (SchedulerAgent) myAgent; if (_agent._events.isEmpty()) { allFinished = true; _agent.finishedAlgorithm(); return; } TreeSet<String> orderedEventNames = new TreeSet<>(_agentsDFS.keySet()); //because delta depends on overlapping events this order is necessary the first time for (String ev : orderedEventNames) { DFSBehaviour.VirtualAgent ag = _agentsDFS.get(ev); _virtualAgents.put(ev.split("-",2)[1], new VirtualAgent(ag._event, _agent, this, ag, _leader)); } } @Override public void action() { if (allFinished) return; MessageTemplate mt = MessageTemplate.MatchConversationId("ADOPT"); ACLMessage msg = myAgent.receive(mt); if (msg != null) { int separatorIndex = msg.getContent().indexOf('-'); if (separatorIndex != -1) { String str = msg.getContent(); String[] strs = str.split("-", 3); switch (strs[0]) { case "COST": _virtualAgents.get(strs[1]).receiveCost(Serializer.CostFromJSON(strs[2])); break; case "VALUE": _virtualAgents.get(strs[1]).receiveValue(Serializer.ValueFromJSON(strs[2])); break; case "THRESHOLD": _virtualAgents.get(strs[1]).receiveThreshold(Serializer.ThresholdFromJSON(strs[2])); break; case "TERMINATE": _virtualAgents.get(strs[1]).receiveTerminate(Serializer.ContextFromJSON(strs[2])); break; default: System.err.println("Received an invalid message type."); break; } } else { System.err.println("Received an invalid message"); } } else { block(); } } @Override public boolean done() { if (allFinished) _agent.finishedAlgorithm(); return allFinished; } public void checkFinished() { allFinished = true; for (VirtualAgent va : _virtualAgents.values()) { allFinished = allFinished && va._isFinished; if (!allFinished) return; } } }
package com.currencycloud.client.http; import com.currencycloud.client.CurrencyCloudClient; import com.currencycloud.client.exception.ApiException; import com.currencycloud.client.model.Account; import com.currencycloud.client.model.Accounts; import com.currencycloud.client.model.Beneficiary; import com.currencycloud.client.model.ErrorMessage; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; /** * This test executes actual http calls to the demo server and shouldn't be run when unit tests are run. Run when * needed only. */ @Ignore public class DemoServerTest { private static final Logger log = LoggerFactory.getLogger(DemoServerTest.class); private CurrencyCloudClient currencyCloud = new CurrencyCloudClient( CurrencyCloudClient.Environment.demo, "rjnienaber@gmail.com", "ef0fd50fca1fb14c1fab3a8436b9ecb65f02f129fd87eafa45ded8ae257528f0" ); /** * Test that payment types collection is handled correctly. * */ @Test public void testPaymentTypes() throws Exception { try { Beneficiary beneficiary = Beneficiary.createForValidate("GB", "GBP", "GB"); beneficiary.setBankAddress(Arrays.asList("Trafalgar Square", "London", "UK")); beneficiary.setBankName("Acme Bank"); beneficiary.setPaymentTypes(Arrays.asList("priority", "regular")); currencyCloud.validateBeneficiary(beneficiary); assertThat("Should fail.", false); } catch (ApiException e) { log.info(e.toString()); Map<String, List<ErrorMessage>> msgs = e.getErrorMessages(); List<ErrorMessage> paymentTypesErrors = msgs.get("payment_types"); if (paymentTypesErrors != null) { for (ErrorMessage paymentTypesError : paymentTypesErrors) { if (Arrays.asList("payment_types_type_is_wrong", "payment_types_not_included_in_list") .contains(paymentTypesError.getCode())) { throw new AssertionError(paymentTypesError.getMessage()); } } } } } /** Test that payment types collection is handled correctly. */ @Test public void testAddress() throws Exception { List<String> paymentTypes = Arrays.asList("priority", "regular"); Beneficiary beneficiary = Beneficiary.createForCreate("John W Doe", "DE", "EUR", "John Doe"); beneficiary.setBeneficiaryAddress(Collections.singletonList("Hamburg, GE")); beneficiary.setBeneficiaryCountry("DE"); beneficiary.setBicSwift("COBADEFF"); beneficiary.setIban("DE89370400440532013000"); beneficiary.setBeneficiaryEntityType("individual"); beneficiary.setBeneficiaryCompanyName("ACME Ltd."); beneficiary.setBeneficiaryFirstName("John"); beneficiary.setBeneficiaryLastName("Doe"); beneficiary.setBeneficiaryCity("Hamburg"); beneficiary.setBankAddress(Arrays.asList("Trafalgar Square", "London", "UK")); beneficiary.setBankName("Acme Bank"); beneficiary.setPaymentTypes(paymentTypes); beneficiary = currencyCloud.createBeneficiary(beneficiary); assertThat(beneficiary.getPaymentTypes(), is(equalTo(paymentTypes))); } @Test public void testAccounts() throws Exception { Accounts accounts = currencyCloud.findAccounts(null, null); log.debug("Accounts = {}", accounts); Account account = currencyCloud.currentAccount(); log.debug("Current account = {}", account); String myAccId = account.getId(); account = currencyCloud.retrieveAccount(myAccId); assertThat(account.getId(), equalTo(myAccId)); boolean found = false; for (Account a : accounts.getAccounts()) { if (Objects.equals(a.getId(), myAccId)) { found = true; } } assertThat("Current account not found among the ones listed.", found); // account.setCountry("SI"); // log.debug("account = {}", account); } }
package com.fundynamic.d2tm.game.entities; import com.fundynamic.d2tm.Game; import com.fundynamic.d2tm.game.AbstractD2TMTest; import com.fundynamic.d2tm.math.Coordinate; import com.fundynamic.d2tm.math.MapCoordinate; import com.fundynamic.d2tm.math.Vector2D; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; import java.util.List; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; public class EntityTest extends AbstractD2TMTest { private TestableEntity entity1; private TestableEntity entity2; private Coordinate topLeftCoordinate; private EntityData entityData; @Before public void setUp() throws SlickException { super.setUp(); topLeftCoordinate = Coordinate.create(Game.TILE_SIZE * 4, Game.TILE_SIZE * 4); // 4X32 = 128 entityData = new EntityData(); entityData.setWidth(64); entityData.setHeight(64); entity1 = new TestableEntity(topLeftCoordinate, mock(SpriteSheet.class), entityData, player, entityRepository). setName("Entity1"); entity2 = new TestableEntity(topLeftCoordinate, mock(SpriteSheet.class), entityData, player, entityRepository). setName("Entity2"); } @Test public void randomPositionWithinDoesNotExceedBoundaries() { // choose an arbitrary amount of calls (100) and just try it. // Yeah, this could be more efficient with using a seed and whatnot... for (int i = 0; i < 100; i++) { Vector2D randomPositionWithin = entity1.getRandomPositionWithin(); assertThat(randomPositionWithin.getX(), is(not(lessThan(topLeftCoordinate.getX() - 16)))); assertThat(randomPositionWithin.getY(), is(not(lessThan(topLeftCoordinate.getY() - 16)))); assertThat(randomPositionWithin.getX(), is(not(greaterThan(topLeftCoordinate.getX() + entityData.getWidth())))); assertThat(randomPositionWithin.getY(), is(not(greaterThan(topLeftCoordinate.getY() + entityData.getHeight())))); } } @Test public void getAllSurroundingCoordinatesOfAnEntity() { // entity1 is 64x64 pixels (ie, 2x2). Marked as X // The tiles we would expect are marked as E // EEEE 4 // EXXE 2 // EXXE 2 // EEEE 4 // 4 + 2 + 2 + 4 => 12 surrounding cells List<MapCoordinate> allSurroundingCellsAsCoordinates = entity1.getAllSurroundingCellsAsCoordinates(); Assert.assertEquals(12, allSurroundingCellsAsCoordinates.size()); // we expect the first tile to be at 1 tile above and 1 tile left to the entity1: MapCoordinate upLeftOfTopLeft = allSurroundingCellsAsCoordinates.get(0); Assert.assertEquals(3, upLeftOfTopLeft.getXAsInt()); Assert.assertEquals(3, upLeftOfTopLeft.getYAsInt()); } // Event handling, subscribers, etc // This is how it is set up: // Event2, subscribes to an ENTITY_DESTROYED event for entity1. So when Entity1 gets destroyed, Entity2 will // be notified. // By Event2's subscription on Event1, when Event2 gets destroyed, Event1 will know to stop holding the reference // to Event2 (allowing GC to clear it up). // Thus both Entities are tied by an OnEvent: Entity2 -> Entity1, and Entity1 -> Entity2 // When Entity1 gets destroyed first, it will no longer notify other Entities, thus all subscriptions should // be cleared. @Test public void onEventOnOwnEntityWillHaveOnlyOneDestroySubscription() { entity1.onEvent(EventType.DUMMY, entity1, s -> s.eventMethod()); Assert.assertEquals(0, entity1.getAmountEventMethodCalled()); // nothing triggered the DUMMY event yet // expect one subscription (because event triggers on own object) Assert.assertEquals(1, entity1.eventSubscriptionsFor(EventType.ENTITY_DESTROYED).size()); } @Test public void Entity1EmitsDummyEventCallsExpectedMethodAndRaisesValue() { entity1.onEvent(EventType.DUMMY, entity2, s -> s.eventMethod()); // at first we expect no methods have been called yet (no events happened) Assert.assertEquals(0, entity1.getAmountEventMethodCalled()); Assert.assertEquals(0, entity2.getAmountEventMethodCalled()); entity1.emitEvent(EventType.DUMMY); // some dummy event happened! Assert.assertEquals(0, entity1.getAmountEventMethodCalled()); // entity1 was not interested Assert.assertEquals(1, entity2.getAmountEventMethodCalled()); // entity2 was interested and should have raised value } @Test public void givenEntityDestroyedWillRemoveSubscriberFromDestroyedEntity() { // when event1 gets destroyed, call 'eventMethod' on event2 entity1.onEvent(EventType.DUMMY, entity2, s -> s.eventMethod()); // For entity1: expect the subscription of entity2 upon ENTITY_DESTROYED Assert.assertEquals(1, entity1.eventSubscriptionsFor(EventType.DUMMY).size()); // 1 subscription Entity.EventSubscription<? extends Entity> eventSubscription = entity1.eventSubscriptionsFor(EventType.DUMMY).get(0); Assert.assertSame(eventSubscription.getSubscriber(), entity2); // and its subscriber is entity2 // For entity2: expect the subscription of entity1 upon ENTITY_DESTROYED, so that it knows no longer // to call entity2's method in case entity2 gets destroyed Assert.assertEquals(1, entity2.eventSubscriptionsFor(EventType.ENTITY_DESTROYED).size()); eventSubscription = entity2.eventSubscriptionsFor(EventType.ENTITY_DESTROYED).get(0); Assert.assertSame(eventSubscription.getSubscriber(), entity1); // the entity1 to be notified if entity2 gets destroyed // ACT: Entity1 gets destroyed! entity1.destroy(); // expect no subscriptions for Entity1, because they should be cleared Assert.assertEquals(0, entity1.eventSubscriptionsFor(EventType.ENTITY_DESTROYED).size()); // Entity2 should no longer notify entity1 upon its destroy, because entity1 is no longer among us... Assert.assertEquals(0, entity2.eventSubscriptionsFor(EventType.ENTITY_DESTROYED).size()); entity1 = null; System.gc(); // clear out all references to entity1, and clear memory. // should be able to destroy entity2 without problems now entity2.destroy(); } @Test public void Entity1EmitsDummyEventCallsExpectedMethodAndRaisesValueAtMultipleSubscribers() { TestableEntity entity3 = new TestableEntity(topLeftCoordinate, mock(SpriteSheet.class), entityData, player, entityRepository). setName("Entity3"); entity1.onEvent(EventType.DUMMY, entity2, s -> s.eventMethod()); entity1.onEvent(EventType.DUMMY, entity3, s -> s.eventMethod()); // at first we expect no methods have been called yet (no events happened) Assert.assertEquals(0, entity1.getAmountEventMethodCalled()); Assert.assertEquals(0, entity2.getAmountEventMethodCalled()); Assert.assertEquals(0, entity3.getAmountEventMethodCalled()); entity1.emitEvent(EventType.DUMMY); // some dummy event happened! Assert.assertEquals(0, entity1.getAmountEventMethodCalled()); // entity1 was not interested Assert.assertEquals(1, entity2.getAmountEventMethodCalled()); // entity2 was interested and should have raised value Assert.assertEquals(1, entity3.getAmountEventMethodCalled()); // entity2 was interested and should have raised value } @Test public void SubscribingMoreThanOnceOnSameEntityWilCallMethodMultipleTimes() { // woops subscribing too much entity1.onEvent(EventType.DUMMY, entity2, s -> s.eventMethod()); entity1.onEvent(EventType.DUMMY, entity2, s -> s.eventMethod()); entity1.onEvent(EventType.DUMMY, entity2, s -> s.eventMethod()); entity1.onEvent(EventType.DUMMY, entity2, s -> s.eventMethod()); entity1.emitEvent(EventType.DUMMY); // some dummy event happened! // expected to be raised to 4 Assert.assertEquals(4, entity2.getAmountEventMethodCalled()); } // destroy without any events set, check NPE , etc }
package com.google.sps.servlets; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.After; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.sps.tool.Tool.compareJson; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.*; import java.io.PrintWriter; import java.io.StringWriter; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import static com.google.appengine.api.datastore.FetchOptions.Builder.withLimit; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.Entity; import com.google.gson.Gson; import com.google.common.collect.ImmutableMap; import com.google.sps.data.Folder; import com.google.sps.data.Card; import com.google.sps.tool.EntityTestingTool; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; @RunWith(JUnit4.class) public final class UserCardsServletTest { private final LocalServiceTestHelper helper = new LocalServiceTestHelper( new LocalDatastoreServiceTestConfig() .setDefaultHighRepJobPolicyUnappliedJobPercentage(0), new LocalUserServiceTestConfig()) .setEnvIsAdmin(true).setEnvIsLoggedIn(true) .setEnvEmail("test@gmail.com").setEnvAuthDomain("gmail.com"); private HttpServletRequest mockRequest; private HttpServletResponse mockResponse; private StringWriter responseWriter; private UserCardsServlet servlet; private DatastoreService datastore; @Before public void setUp() throws Exception { helper.setUp(); servlet = new UserCardsServlet(); mockRequest = mock(HttpServletRequest.class); mockResponse = mock(HttpServletResponse.class); // Set up a fake HTTP response responseWriter = new StringWriter(); when(mockResponse.getWriter()).thenReturn(new PrintWriter(responseWriter)); // Initialize datastore datastore = DatastoreServiceFactory.getDatastoreService(); } @After public void tearDown() throws Exception { helper.setEnvIsLoggedIn(true); helper.tearDown(); } @Test public void QueryUserCards() throws Exception { // Returns array of Cards and signals front-end to show Create Card Option // Generate testing card objects to store in datastore Card cardA = new Card("null", "viet", "en", "vi", "test", "test"); Card cardB = new Card("null", "viet", "en", "vi", "test", "test"); // Generate a dummy Folder Entity Entity folder = new Entity("Folder", "testID"); String folderKey = KeyFactory.keyToString(folder.getKey()); when(mockRequest.getParameter("folderKey")).thenReturn(folderKey); List<Card> cards = new ArrayList<>(); Card cardAInDatastore = EntityTestingTool.populateDatastoreWithACard(cardA, datastore, folderKey); Card cardBInDatastore = EntityTestingTool.populateDatastoreWithACard(cardB, datastore, folderKey); cards.add(cardAInDatastore); cards.add(cardBInDatastore); servlet.doGet(mockRequest, mockResponse); String response = responseWriter.toString(); String expectedResponse = new Gson().toJson(EntityTestingTool.getExpectedJsonCardInfo( /*card*/cards, /*showCreateFormStatus*/true)); assertTrue(compareJson(response, expectedResponse)); } @Test public void UserHasNoCurrentCard() throws Exception { // Returns an empty array list and signals front-end to show Create Card Option List<Card> noCardsInDatastore = new ArrayList<>(); // Generate a dummy Folder Entity Entity folder = new Entity("Folder", "testID"); String folderKey = KeyFactory.keyToString(folder.getKey()); when(mockRequest.getParameter("folderKey")).thenReturn(folderKey); servlet.doGet(mockRequest, mockResponse); String response = responseWriter.toString(); String expectedResponse = new Gson().toJson(EntityTestingTool.getExpectedJsonCardInfo( /*card*/noCardsInDatastore, /*showCreateFormStatus*/true)); assertTrue(compareJson(response, expectedResponse)); } @Test public void UserNotLoggedIn() throws Exception { // Returns an empty array list and signals front-end to not show Create Folder Option helper.setEnvIsLoggedIn(false); List<Card> noCardsQueried = new ArrayList<>(); servlet.doGet(mockRequest, mockResponse); String response = responseWriter.toString(); String expectedResponse = new Gson().toJson(EntityTestingTool.getExpectedJsonCardInfo( /*card*/noCardsQueried, /*showCreateFormStatus*/false)); assertTrue(compareJson(response, expectedResponse)); } @Test public void UserCreatesAHelloSpanishCard() throws Exception { // Generate a dummy Folder Entity Entity folder = new Entity("Folder", "testID"); String folderKey = KeyFactory.keyToString(folder.getKey()); when(mockRequest.getParameter("testStatus")).thenReturn("True"); when(mockRequest.getParameter("folderKey")).thenReturn(folderKey); when(mockRequest.getParameter("labels")).thenReturn("spanish"); when(mockRequest.getParameter("fromLang")).thenReturn("en"); when(mockRequest.getParameter("toLang")).thenReturn("es"); when(mockRequest.getParameter("rawText")).thenReturn("hello"); when(mockRequest.getParameter("translatedText")).thenReturn("hola"); servlet.doPost(mockRequest, mockResponse); PreparedQuery responseEntity = datastore.prepare(new Query("Card").setAncestor(folder.getKey())); assertTrue(EntityTestingTool.checkForNoNullValues(responseEntity.asSingleEntity())); assertEquals(1, responseEntity.countEntities(withLimit(10))); } @Test public void UserCreatesACardAndHasOtherCardsBefore() throws Exception { // Making sure that User's current number of cards increase after creating a card // Generate testing card objects to store in datastore Card cardA = new Card("null", "viet", "en", "vi", "test", "test"); Card cardB = new Card("null", "viet", "en", "vi", "test", "test"); // Generate a dummy Folder Entity Entity folder = new Entity("Folder", "testID"); String folderKey = KeyFactory.keyToString(folder.getKey()); when(mockRequest.getParameter("testStatus")).thenReturn("True"); when(mockRequest.getParameter("folderKey")).thenReturn(folderKey); when(mockRequest.getParameter("labels")).thenReturn("spanish"); when(mockRequest.getParameter("fromLang")).thenReturn("en"); when(mockRequest.getParameter("toLang")).thenReturn("es"); when(mockRequest.getParameter("rawText")).thenReturn("hello"); when(mockRequest.getParameter("translatedText")).thenReturn("hola"); EntityTestingTool.populateDatastoreWithACard(cardA, datastore, folderKey); EntityTestingTool.populateDatastoreWithACard(cardB, datastore, folderKey); servlet.doPost(mockRequest, mockResponse); PreparedQuery responseEntity = datastore.prepare(new Query("Card").setAncestor(folder.getKey())); assertEquals(3, responseEntity.countEntities(withLimit(10))); } }
package com.neverwinterdp.scribengin; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Properties; import java.util.UUID; import kafka.javaapi.producer.Producer; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import org.apache.log4j.Logger; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.Lists; import com.neverwinterdp.scribengin.fixture.KafkaFixture; import com.neverwinterdp.scribengin.fixture.ZookeeperFixture; import com.neverwinterdp.scribengin.hostport.HostPort; import com.neverwinterdp.scribengin.scribeconsumer.ScribeConsumer; import com.neverwinterdp.scribengin.scribeconsumer.ScribeConsumerConfig; public class ScribeKafkaTest { private static final Logger logger = Logger.getLogger(ScribeKafkaTest.class); private static ZookeeperFixture zookeeper; private static KafkaFixture kf1; private static KafkaFixture kf2; @BeforeClass public static void setup() throws IOException, InterruptedException { System.out.println("calling setup..."); //xxx Process p = Runtime.getRuntime().exec("script/bootstrap_kafka.sh servers"); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { System.out.println(line);//xxx } zookeeper = new ZookeeperFixture("0.8.1", "127.0.0.1", 2323); zookeeper.start(); System.out.println("about to start kafka");//xxx kf1 = new KafkaFixture("0.8.1.1", "127.0.0.1", 19876, zookeeper.getHost(), zookeeper.getPort()); kf2 = new KafkaFixture("0.8.1.1", "127.0.0.1", 19877, zookeeper.getHost(), zookeeper.getPort()); kf1.start(); kf2.start(); } @AfterClass public static void teardown() throws IOException { System.out.println("calling teardown.."); //xxx kf1.stop(); kf2.stop(); zookeeper.stop(); } @Test public void testGetEarliestOffsetFromKafka() { logger.info("testKafka. "); int expectedInitialOffset=0; String topic = "testData"; injectTestData(topic); ScribeConsumerConfig config = new ScribeConsumerConfig(topic); config.cleanStart = true; config.partition = 0; config.topic = topic; config.brokerList = getKafkaCluster(); ScribeConsumer sc = new ScribeConsumer(config); sc.connectToTopic(); try { Method method = ScribeConsumer.class.getDeclaredMethod("getEarliestOffsetFromKafka", String.class, int.class, long.class); method.setAccessible(true); long offset = (Long) method.invoke(sc, topic, 0, kafka.api.OffsetRequest.EarliestTime()); Assert.assertTrue(offset == expectedInitialOffset); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { logger.error(e.getCause()); } } private List<HostPort> getKafkaCluster() { List<HostPort> hosts = Lists.newArrayList(); HostPort hostPort1 = new HostPort(kf1.getHost(), kf1.getPort()); hosts.add(hostPort1); HostPort hostPort2 = new HostPort(kf2.getHost(), kf2.getPort()); hosts.add(hostPort2); return hosts; } public void injectTestData(String topic) { logger.info("injectTestData. "); Properties props = new Properties(); props.put("metadata.broker.list", getKafkaURLs()); props.put("producer.type", "async"); logger.info("Kafka URLs " + getKafkaURLs()); props.put("serializer.class", "kafka.serializer.StringEncoder"); ProducerConfig config = new ProducerConfig(props); Producer<String, String> producer = new Producer<String, String>(config); for (int messages = 0; messages < 100; messages++) { String msg = UUID.randomUUID().toString(); KeyedMessage<String, String> data = new KeyedMessage<String, String>( topic, msg); try { producer.send(data); } catch (Exception ex) { ex.printStackTrace(); } } producer.close(); } private Object getKafkaURLs() { logger.info("getKafkaURLs. "); StringBuilder builder = new StringBuilder(); builder.append(kf1.getHost()); builder.append(":"); builder.append(kf1.getPort()); builder.append(","); builder.append(kf2.getHost()); builder.append(":"); builder.append(kf2.getPort()); builder.append(","); return builder.substring(0, builder.length() - 1); } }
package de.jbdb.sql2json.step1.input.modell; import static de.jbdb.sql2json.Sql2JSONTestObjects.TEST_COLUMN; import static de.jbdb.sql2json.Sql2JSONTestObjects.TEST_TWO_COLUMNS; import static de.jbdb.sql2json.Sql2JSONTestObjects.TEST_VALUE1; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class RowsTest { // TODO Additional tests // empty string = error // null = error @Test public void twoValuesInTwoRowsEach() throws Exception { Rows rows = new Rows(new Columns(TEST_TWO_COLUMNS), "(" + TEST_VALUE1 + "," + TEST_VALUE1 + ")," + "(" + TEST_VALUE1 + "," + TEST_VALUE1 + ")"); assertRows(rows, 2, 2); } @Test public void twoValuesInTwoRowsEachWithWhitespace() throws Exception { Rows rows = new Rows(new Columns(TEST_TWO_COLUMNS), " ( " + TEST_VALUE1 + " , " + TEST_VALUE1 + " ) , " + " ( " + TEST_VALUE1 + " , " + TEST_VALUE1 + " ) "); assertRows(rows, 2, 2); } @Test public void twoValuesWithTrailingBracketAndSemicolon() throws Exception { Rows rows = new Rows(new Columns(TEST_TWO_COLUMNS), " (testValue1, testValue1);"); assertRows(rows, 1, 2); } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void lessValuesThanColumns() throws Exception { expectedException.expect(AssertionError.class); expectedException.expectMessage( org.hamcrest.CoreMatchers.containsString("number of values does not match number of columns")); new Rows(new Columns("('TEST_COLUMN1', 'TEST_COLUMN2')"), "('TEST_VALUE1');"); } @Test public void moreValuesThanColumns() throws Exception { expectedException.expect(AssertionError.class); expectedException.expectMessage( org.hamcrest.CoreMatchers.containsString("number of values does not match number of columns")); new Rows(new Columns("('TEST_COLUMN1', 'TEST_COLUMN2')"), "('TEST_VALUE1', 'TEST_VALUE2', 'TEST_VALUE3');"); } @Test public void constructorWithNoValues() throws Exception { expectedException.expect(AssertionError.class); expectedException.expectMessage(org.hamcrest.CoreMatchers.containsString("values are missing")); new Rows(new Columns("TEST_COLUMN"), " "); } @Test public void addAll() throws Exception { Rows rows1 = new Rows(new Columns(TEST_COLUMN), TEST_VALUE1); Rows rows2 = new Rows(new Columns(TEST_COLUMN), TEST_VALUE1); rows1.addAll(rows2); assertRows(rows1, 2, 1); assertRows(rows2, 1, 1); } @Test public void toJSON_OneValue() throws Exception { Rows classUnderTest = new Rows(new Columns(TEST_COLUMN), "('TEST_VALUE1');"); String jsonString = classUnderTest.toJSON(); assertThat(jsonString).isEqualTo("[{\"" + TEST_COLUMN + "\":\"TEST_VALUE1\"}]"); } @Test public void toJSON_TwoValues() throws Exception { Rows classUnderTest = new Rows(new Columns(TEST_TWO_COLUMNS), "('TEST_VALUE1', 'TEST_VALUE2')"); String jsonString = classUnderTest.toJSON(); assertThat(jsonString) .isEqualTo("[{\"" + TEST_COLUMN + "\":\"TEST_VALUE1\",\"" + TEST_COLUMN + "\":\"TEST_VALUE2\"}]"); } @Test public void toJSON_TwoRowsWithTwoValuesEach() throws Exception { Rows classUnderTest = new Rows(new Columns(TEST_TWO_COLUMNS), "('TEST_VALUE1', 'TEST_VALUE2'), ('TEST_VALUE3', 'TEST_VALUE4')"); String jsonString = classUnderTest.toJSON(); assertThat(jsonString).isEqualTo("[" + "{\"" + TEST_COLUMN + "\":\"TEST_VALUE1\",\"" + TEST_COLUMN + "\":\"TEST_VALUE2\"}," + "{\"" + TEST_COLUMN + "\":\"TEST_VALUE3\",\"" + TEST_COLUMN + "\":\"TEST_VALUE4\"}" + "]"); } private void assertRows(Rows rows, int numberOfRows, int numberOfValues) { List<Row> rowAsList = rows.asList(); assertThat(rowAsList).isNotNull(); assertThat(rowAsList).isNotEmpty(); assertThat(rowAsList).hasSize(numberOfRows); assertThat(rowAsList.get(0)).isEqualTo(createRow(numberOfValues)); } private Row createRow(int numberOfValues) { StringBuffer valueString = new StringBuffer(); StringBuffer columnString = new StringBuffer(); valueString.append("("); for (int i = 0; i < numberOfValues; i++) { valueString.append(TEST_VALUE1); valueString.append(","); columnString.append(TEST_COLUMN); columnString.append(","); } valueString.delete(valueString.length() - 1, valueString.length()); columnString.delete(columnString.length() - 1, columnString.length()); Row row = new Row(new Columns(columnString.toString()), valueString.toString()); assertThat(row.getValues()).hasSize(numberOfValues); return row; } }
package io.kuzzle.test.core.Kuzzle; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.net.URISyntaxException; import io.kuzzle.sdk.core.Options; import io.kuzzle.sdk.enums.Mode; import io.kuzzle.sdk.listeners.ResponseListener; import io.kuzzle.sdk.listeners.OnQueryDoneListener; import io.kuzzle.test.testUtils.KuzzleExtend; import io.socket.client.Socket; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; public class getStatisticsTest { private KuzzleExtend kuzzle; private ResponseListener listener; @Before public void setUp() throws URISyntaxException { Options options = new Options(); options.setConnect(Mode.MANUAL); options.setDefaultIndex("testIndex"); kuzzle = new KuzzleExtend("localhost", options, null); kuzzle.setSocket(mock(Socket.class)); listener = new ResponseListener<Object>() { @Override public void onSuccess(Object object) { } @Override public void onError(JSONObject error) { } }; } @Test public void checkAllSignaturesVariants() { kuzzle = spy(kuzzle); listener = spy(listener); kuzzle.getStatistics(listener); kuzzle.getStatistics(System.currentTimeMillis(), listener); verify(kuzzle).getStatistics(any(Options.class), any(ResponseListener.class)); verify(kuzzle).getStatistics(any(long.class), any(Options.class), any(ResponseListener.class)); } @Test(expected = RuntimeException.class) public void testGetStatisticsException() throws JSONException { listener = spy(listener); kuzzle = spy(kuzzle); doThrow(JSONException.class).when(listener).onSuccess(any(JSONArray.class)); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(new JSONObject().put("result", new JSONObject().put("hits", mock(JSONArray.class)))); return null; } }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); kuzzle.getStatistics(System.currentTimeMillis(), listener); } @Test(expected = RuntimeException.class) public void testGetStatisticsQueryException() throws JSONException { kuzzle = spy(kuzzle); doThrow(JSONException.class).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); kuzzle.getStatistics(System.currentTimeMillis(), listener); } @Test(expected = IllegalArgumentException.class) public void testGetStatsIllegalListener() { kuzzle.getStatistics(System.currentTimeMillis(), null); } @Test public void testGetStatistics() throws JSONException { kuzzle = spy(kuzzle); final JSONObject response = new JSONObject("{ result: {\n" + " total: 25,\n" + " hits: [\n" + " {\n" + " completedRequests: {\n" + " websocket: 148,\n" + " rest: 24,\n" + " mq: 78\n" + " },\n" + " failedRequests: {\n" + " websocket: 3\n" + " },\n" + " ongoingRequests: {\n" + " mq: 8,\n" + " rest: 2\n" + " },\n" + " connections: {\n" + " websocket: 13\n" + " },\n" + " \"timestamp\": \"2016-01-13T13:46:19.917Z\"\n" + " }\n" + " ]\n" + " }" + "}"); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ((OnQueryDoneListener) invocation.getArguments()[3]).onSuccess(response); ((OnQueryDoneListener) invocation.getArguments()[3]).onError(mock(JSONObject.class)); return null; } }).when(kuzzle).query(any(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); kuzzle.getStatistics(System.currentTimeMillis(), mock(ResponseListener.class)); ArgumentCaptor argument = ArgumentCaptor.forClass(io.kuzzle.sdk.core.Kuzzle.QueryArgs.class); verify(kuzzle).query((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.capture(), any(JSONObject.class), any(Options.class), any(OnQueryDoneListener.class)); assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).controller, "server"); assertEquals(((io.kuzzle.sdk.core.Kuzzle.QueryArgs) argument.getValue()).action, "getStats"); } @Test(expected = IllegalArgumentException.class) public void testGetStatisticsWithoutListener() { kuzzle.getStatistics(null); } }
package krasa.build.backend.execution; import krasa.build.backend.dto.Result; import krasa.build.backend.dto.Result; import krasa.build.backend.execution.process.ProcessLog; import org.apache.commons.lang3.RandomStringUtils; import org.junit.Assert; import org.junit.Test; /** * @author Vojtech Krasaool */ public class ProcessLogTest { public static final int COUNT = 3000; int i = 0; protected ProcessLog processLog; @Test public void testGetNext() throws Exception { processLog = new ProcessLog(); String random = RandomStringUtils.randomAlphabetic(COUNT); processLog.append(random); Result next = processLog.getNext(0); Assert.assertEquals(COUNT, next.getLength()); Assert.assertEquals(random, next.getText()); processLog.append("," + ++i); processLog.append("," + ++i); processLog.append("," + ++i); processLog.append("," + ++i); processLog.append("," + ++i); next = processLog.getNext(0); Assert.assertEquals(COUNT + 5, next.getLength()); Assert.assertEquals(random + ",1,2,3,4,5", next.getText()); for (int j = 0; j < 2000; j++) { processLog.append("," + ++i); } next = processLog.getNext(0); Assert.assertEquals(COUNT + 2005, next.getLength()); Assert.assertTrue(next.getText().endsWith("2005")); for (int j = 0; j < 3000; j++) { processLog.append("," + ++i);| } next = processLog.getNext(0); Assert.assertEquals(COUNT + 5005, next.getLength()); Assert.assertEquals(next.getText().substring(COUNT + 1).substring(0, "...2505 lines skipped".length()), "...2505 lines skipped"); Assert.assertTrue(next.getText().endsWith("5005")); next = processLog.getNext(COUNT); Assert.assertEquals(COUNT + 5005, next.getLength()); Assert.assertEquals(next.getText().substring(1).substring(0, "...2505 lines skipped".length()), "...2505 lines skipped"); Assert.assertTrue(next.getText().endsWith("5005")); next = processLog.getNext(COUNT + 5000); Assert.assertEquals(COUNT + 5005, next.getLength()); Assert.assertEquals(next.getText(), ",5001,5002,5003,5004,5005"); } }
package net.finmath.montecarlo; import java.util.Map; import org.junit.Assert; import org.junit.Test; import net.finmath.stochastic.RandomVariableInterface; /** * Test cases for the class net.finmath.montecarlo.RandomVariableAAD. * * @author Christian Fries * @author Stefan Sedlmair * @see net.finmath.montecarlo.RandomVariable */ public class RandomVariableAADTest { @Test public void testRandomVariableDeterministc() { RandomVariableAAD.resetArrayListOfAllAADRandomVariables(); // Create a random variable with a constant RandomVariableInterface randomVariable = RandomVariableAAD.constructNewAADRandomVariable(2.0); // Perform some calculations randomVariable = randomVariable.mult(2.0); randomVariable = randomVariable.add(1.0); randomVariable = randomVariable.squared(); randomVariable = randomVariable.sub(4.0); randomVariable = randomVariable.div(7.0); // The random variable has average value 3.0 (it is constant 3.0) Assert.assertTrue(randomVariable.getAverage() == 3.0); // Since the random variable is deterministic, it has zero variance Assert.assertTrue(randomVariable.getVariance() == 0.0); } @Test public void testRandomVariableStochastic() { RandomVariableAAD.resetArrayListOfAllAADRandomVariables(); // Create a stochastic random variable RandomVariableInterface randomVariable2 = RandomVariableAAD.constructNewAADRandomVariable(0.0, new double[] {-4.0, -2.0, 0.0, 2.0, 4.0} ); // Perform some calculations randomVariable2 = randomVariable2.add(4.0); randomVariable2 = randomVariable2.div(2.0); // The random variable has average value 2.0 Assert.assertTrue(randomVariable2.getAverage() == 2.0); // The random variable has variance value 2.0 = (4 + 1 + 0 + 1 + 4) / 5 Assert.assertEquals(2.0, randomVariable2.getVariance(), 1E-12); // Multiply two random variables, this will expand the receiver to a stochastic one RandomVariableInterface randomVariable = RandomVariableAAD.constructNewAADRandomVariable(3.0); randomVariable = randomVariable.mult(randomVariable2); // The random variable has average value 6.0 Assert.assertTrue(randomVariable.getAverage() == 6.0); // The random variable has variance value 2 * 9 Assert.assertTrue(randomVariable.getVariance() == 2.0 * 9.0); } @Test public void testRandomVariableArithmeticSqrtPow() { RandomVariableAAD.resetArrayListOfAllAADRandomVariables(); // Create a stochastic random variable RandomVariableInterface randomVariable = RandomVariableAAD.constructNewAADRandomVariable(0.0, new double[] {3.0, 1.0, 0.0, 2.0, 4.0, 1.0/3.0} ); RandomVariableInterface check = randomVariable.sqrt().sub(randomVariable.pow(0.5)); // The random variable is identical 0.0 Assert.assertTrue(check.getAverage() == 0.0); Assert.assertTrue(check.getVariance() == 0.0); } @Test public void testRandomVariableArithmeticSquaredPow() { RandomVariableAAD.resetArrayListOfAllAADRandomVariables(); // Create a stochastic random variable RandomVariableInterface randomVariable = RandomVariableAAD.constructNewAADRandomVariable(0.0, new double[] {3.0, 1.0, 0.0, 2.0, 4.0, 1.0/3.0} ); RandomVariableInterface check = randomVariable.squared().sub(randomVariable.pow(2.0)); // The random variable is identical 0.0 Assert.assertTrue(check.getAverage() == 0.0); Assert.assertTrue(check.getVariance() == 0.0); } @Test public void testRandomVariableStandardDeviation() { RandomVariableAAD.resetArrayListOfAllAADRandomVariables(); // Create a stochastic random variable RandomVariableInterface randomVariable = RandomVariableAAD.constructNewAADRandomVariable(0.0, new double[] {3.0, 1.0, 0.0, 2.0, 4.0, 1.0/3.0} ); double check = randomVariable.getStandardDeviation() - Math.sqrt(randomVariable.getVariance()); Assert.assertTrue(check == 0.0); } @Test public void testRandomVariableSimpleGradient(){ RandomVariableAAD.resetArrayListOfAllAADRandomVariables(); RandomVariable randomVariable01 = new RandomVariable(0.0, new double[] {3.0, 1.0, 0.0, 2.0, 4.0}); RandomVariable randomVariable02 = new RandomVariable(0.0, new double[] {-4.0, -2.0, 0.0, 2.0, 4.0} ); RandomVariableAAD aadRandomVariable01 = RandomVariableAAD.constructNewAADRandomVariable(randomVariable01); RandomVariableAAD aadRandomVariable02 = RandomVariableAAD.constructNewAADRandomVariable(randomVariable02); /* x_3 = x_1 + x_2 */ RandomVariableInterface aadRandomVariable03 = aadRandomVariable01.add(aadRandomVariable02); /* x_4 = x_3 * x_1 */ RandomVariableInterface aadRandomVariable04 = aadRandomVariable03.mult(aadRandomVariable01); /* x_5 = x_4 + x_1 = ((x_1 + x_2) * x_1) + x_1 = x_1^2 + x_2x_1 + x_1*/ RandomVariableInterface aadRandomVariable05 = aadRandomVariable04.add(aadRandomVariable01); Map<Integer, RandomVariableInterface> aadGradient = ((RandomVariableAAD)aadRandomVariable05).getGradient(); /* dy/dx_1 = x_1 * 2 + x_2 + 1 * dy/dx_2 = x_1 */ RandomVariableInterface[] analyticGradient = new RandomVariableInterface[]{ randomVariable01.mult(2.0).add(randomVariable02).add(1.0), randomVariable01 }; for(int i=0; i<analyticGradient.length;i++){ // System.out.println(analyticGradient[i]); // System.out.println(aadGradient.get(i)); Assert.assertTrue(analyticGradient[i].equals(aadGradient.get(i))); } } @Test public void testRandomVariableGradientBigSum(){ RandomVariableAAD.resetArrayListOfAllAADRandomVariables(); /* OutOfMemoryError for >= 10^6*/ int lengthOfVectors = 4 * (int) Math.pow(10, 5); double[] x = new double[lengthOfVectors]; for(int i=0; i < lengthOfVectors; i++){ x[i] = Math.random(); } RandomVariable randomVariable01 = new RandomVariable(0.0, x); RandomVariableAAD aadRandomVariable01 = RandomVariableAAD.constructNewAADRandomVariable(randomVariable01); /* throws StackOverflowError/OutOfMemoryError for >= 10^4 iterations */ int numberOfIterations = (int) Math.pow(10, 3); RandomVariableAAD sum = RandomVariableAAD.constructNewAADRandomVariable(0.0); for(int i = 0; i < numberOfIterations; i++){ sum = (RandomVariableAAD) sum.add(aadRandomVariable01); } Map<Integer, RandomVariableInterface> aadGradient = sum.getGradient(); RandomVariableInterface[] analyticGradient = new RandomVariableInterface[]{new RandomVariable(numberOfIterations)}; for(int i=0; i<analyticGradient.length;i++){ Assert.assertTrue(analyticGradient[i].equals(aadGradient.get(i))); } } }
package org.twonote.rgwadmin4j.impl; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.AmazonS3Exception; import com.amazonaws.services.s3.model.HeadBucketRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import org.junit.Ignore; import org.junit.Test; import org.twonote.rgwadmin4j.model.*; import java.io.ByteArrayInputStream; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; import static org.junit.Assert.*; @SuppressWarnings("ConstantConditions") public class RgwAdminImplTest extends BaseTest { @Test public void listSubUser() throws Exception { testWithASubUser( s -> { List<String> subUserIds = RGW_ADMIN.listSubUser(s.getUserId()); assertEquals( subUserIds, s.getSubusers().stream().map(SubUser::getId).collect(Collectors.toList())); }); } @Test public void listUserInfo() throws Exception { testWithAUser( u -> { List<User> users = RGW_ADMIN.listUserInfo(); assertTrue(users.stream().anyMatch(v -> u.equals(v))); }); } @Test public void listUser() throws Exception { testWithAUser( u -> { List<String> userIds = RGW_ADMIN.listUser(); assertTrue(userIds.stream().anyMatch(k -> u.getUserId().equals(k))); }); } @Test public void listSubUserInfo() throws Exception { testWithASubUser( u -> { List<SubUser> subUsers = RGW_ADMIN.listSubUserInfo(u.getUserId()); assertEquals(subUsers, u.getSubusers()); }); } @Test public void getSubUserInfo() throws Exception { testWithASubUser( u -> { Optional<SubUser> subUserInfo = RGW_ADMIN.getSubUserInfo( u.getUserId(), u.getSubusers().get(0).getRelativeSubUserId()); assertEquals(u.getSubusers().get(0), subUserInfo.get()); }); } @Test public void createS3Credential() throws Exception { testWithAUser( v -> { List<S3Credential> response; // basic response = RGW_ADMIN.createS3Credential(v.getUserId()); assertEquals(2, response.size()); assertEquals(2, RGW_ADMIN.getUserInfo(v.getUserId()).get().getS3Credentials().size()); // specify the key String accessKey = v.getUserId() + "-adminAccessKey"; String secretKey = v.getUserId() + "-adminSecretKey"; response = RGW_ADMIN.createS3Credential(v.getUserId(), accessKey, secretKey); assertTrue( response .stream() .anyMatch( v1 -> accessKey.equals(v1.getAccessKey()) && secretKey.equals(v1.getSecretKey()))); // user not exist try { RGW_ADMIN.createS3Credential(UUID.randomUUID().toString()); fail("user not exist should throw exception"); } catch (RgwAdminException e) { assertTrue( "InvalidArgument".equals(e.getMessage()) // kraken || "NoSuchUser".equals(e.getMessage()) // luminous ); } }); } @Test public void removeS3Credential() throws Exception { testWithAUser( v -> { String accessKey = v.getS3Credentials().get(0).getAccessKey(); // basic RGW_ADMIN.removeS3Credential(v.getUserId(), accessKey); assertEquals(0, RGW_ADMIN.getUserInfo(v.getUserId()).get().getS3Credentials().size()); // key not exist try { RGW_ADMIN.removeS3Credential(v.getUserId(), UUID.randomUUID().toString()); fail(); } catch (RgwAdminException e) { assertEquals( 403, e.status()); // ceph version 11.2.0 (f223e27eeb35991352ebc1f67423d4ebc252adb7) } // user not exist try { RGW_ADMIN.removeS3Credential( UUID.randomUUID().toString(), UUID.randomUUID().toString()); fail("user not exist should throw exception"); } catch (RgwAdminException e) { assertTrue( "InvalidArgument".equals(e.getMessage()) || // kraken "NoSuchUser".equals(e.getMessage()) // luminous ); } }); } @Test public void createS3CredentialForSubUser() throws Exception { testWithASubUser( v -> { List<S3Credential> response; // basic String absSubUserId = v.getSubusers().get(0).getId(); // In forms of "foo:bar" String userId = absSubUserId.split(":")[0]; String subUserId = absSubUserId.split(":")[1]; response = RGW_ADMIN.createS3CredentialForSubUser(userId, subUserId); assertTrue(response.stream().anyMatch(vv -> absSubUserId.equals(vv.getUserId()))); // specify the key String accessKey = v.getUserId() + "-adminAccessKey"; String secretKey = v.getUserId() + "-adminSecretKey"; response = RGW_ADMIN.createS3CredentialForSubUser(userId, subUserId, accessKey, secretKey); assertTrue( response .stream() .anyMatch( v1 -> absSubUserId.equals(v1.getUserId()) && accessKey.equals(v1.getAccessKey()) && secretKey.equals(v1.getSecretKey()))); // sub user not exist // Ceph version 11.2.0 (f223e27eeb35991352ebc1f67423d4ebc252adb7) // Create a orphan key without user in RGW_ADMIN.createS3CredentialForSubUser(userId, "XXXXXXX"); }); } @Test public void removeS3CredentialFromSubUser() throws Exception { testWithASubUser( v -> { String absSubUserId = v.getSubusers().get(0).getId(); // In forms of "foo:bar" String userId = absSubUserId.split(":")[0]; String subUserId = absSubUserId.split(":")[1]; List<S3Credential> response = RGW_ADMIN.createS3CredentialForSubUser(userId, subUserId); S3Credential keyToDelete = response.stream().filter(vv -> absSubUserId.equals(vv.getUserId())).findFirst().get(); // basic RGW_ADMIN.removeS3CredentialFromSubUser(userId, subUserId, keyToDelete.getAccessKey()); assertFalse( RGW_ADMIN .getUserInfo(userId) .get() .getS3Credentials() .stream() .anyMatch( k -> keyToDelete .getAccessKey() .equals(k.getAccessKey()))); // Should not contain this key anymore // key not exist try { RGW_ADMIN.removeS3CredentialFromSubUser( userId, subUserId, UUID.randomUUID().toString()); fail(); } catch (RgwAdminException e) { // ceph version 11.2.0 (f223e27eeb35991352ebc1f67423d4ebc252adb7) assertEquals("InvalidAccessKeyId", e.getMessage()); assertEquals(403, e.status()); } }); } @Test public void createSwiftCredentialForSubUser() throws Exception { testWithASubUser( v -> { SwiftCredential swiftCredential; // basic String absSubUserId = v.getSubusers().get(0).getId(); // In forms of "foo:bar" String userId = absSubUserId.split(":")[0]; String subUserId = absSubUserId.split(":")[1]; swiftCredential = RGW_ADMIN.createSwiftCredentialForSubUser(userId, subUserId); assertTrue(absSubUserId.equals(swiftCredential.getUserId())); assertNotNull(swiftCredential.getUsername()); assertNotNull(swiftCredential.getPassword()); // specify the key String password = v.getUserId() + "-secret"; swiftCredential = RGW_ADMIN.createSwiftCredentialForSubUser(userId, subUserId, password); assertTrue(absSubUserId.equals(swiftCredential.getUserId())); assertNotNull(swiftCredential.getUsername()); assertNotNull(swiftCredential.getPassword()); assertEquals(password, swiftCredential.getPassword()); // sub user not exist // Create a orphan key without user in ceph version 11.2.0 // (f223e27eeb35991352ebc1f67423d4ebc252adb7) RGW_ADMIN.createSwiftCredentialForSubUser(userId, subUserId); }); } @Test public void removeSwiftCredentialFromSubUser() throws Exception { testWithASubUser( v -> { String absSubUserId = v.getSubusers().get(0).getId(); // In forms of "foo:bar" String userId = absSubUserId.split(":")[0]; String subUserId = absSubUserId.split(":")[1]; RGW_ADMIN.createSwiftCredentialForSubUser(userId, subUserId); // basic RGW_ADMIN.removeSwiftCredentialFromSubUser(userId, subUserId); assertFalse( RGW_ADMIN .getUserInfo(userId) .get() .getSwiftCredentials() .stream() .anyMatch( k -> absSubUserId.equals( k.getUserId()))); // The sub user should not have swift key/secret }); } @Test @Ignore("See trimUsage()") public void trimUserUsage() throws Exception {} @Test public void trimUsage() throws Exception { testWithAUser( v -> { createSomeObjects(v); String userId = v.getUserId(); UsageInfo response; response = RGW_ADMIN.getUserUsage(userId).get(); if (response.getSummary().stream().noneMatch(vv -> userId.equals(vv.getUser()))) { fail("No usage log corresponding to the given user id...need more sleep?"); } RGW_ADMIN.trimUserUsage(userId, null); // Usage data are generated in the async way, hope it will be available after wait. try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } response = RGW_ADMIN.getUserUsage(userId).get(); if (response.getSummary().stream().anyMatch(vv -> userId.equals(vv.getUser()))) { fail("Exist usage log corresponding to the given user id...trim log failed"); } }); } @Test @Ignore("See getUsage()") public void getUserUsage() throws Exception {} @Test public void getUsage() throws Exception { testWithAUser( v -> { String userId = v.getUserId(); // Do something to let usage log generated. createSomeObjects(v); UsageInfo response; response = RGW_ADMIN.getUsage(null).get(); if (response.getSummary().stream().noneMatch(vv -> userId.equals(vv.getUser()))) { fail("No usage log corresponding to the given user id...need more sleep?"); } response = RGW_ADMIN.getUserUsage(userId, null).get(); if (response.getSummary().stream().noneMatch(vv -> userId.equals(vv.getUser()))) { fail("No usage log corresponding to the given user id...need more sleep?"); } }); } @Test public void setSubUserPermission() throws Exception { testWithASubUser( su -> { SubUser subUser = su.getSubusers().get(0); for (SubUser.Permission permissionToSet : SubUser.Permission.values()) { List<SubUser> response = RGW_ADMIN.setSubUserPermission( subUser.getParentUserId(), subUser.getRelativeSubUserId(), permissionToSet); SubUser result = response.stream().filter(r -> subUser.getId().equals(r.getId())).findFirst().get(); assertEquals(permissionToSet, result.getPermission()); } }); } @Test public void modifySubUser() throws Exception { testWithAUser( v -> { String subUserId = UUID.randomUUID().toString(); // basic List<SubUser> response = RGW_ADMIN.createSubUser(v.getUserId(), subUserId, null); assertEquals(SubUser.Permission.NONE, response.get(0).getPermission()); response = RGW_ADMIN.modifySubUser(v.getUserId(), subUserId, ImmutableMap.of("access", "full")); assertEquals(SubUser.Permission.FULL, response.get(0).getPermission()); }); } @Test public void removeSubUser() throws Exception { testWithAUser( v -> { String subUserId = UUID.randomUUID().toString(); // basic RGW_ADMIN.createSubUser( v.getUserId(), subUserId, SubUser.Permission.FULL, CredentialType.SWIFT); User response2 = RGW_ADMIN.getUserInfo(v.getUserId()).get(); assertEquals(1, response2.getSwiftCredentials().size()); RGW_ADMIN.removeSubUser(v.getUserId(), subUserId); response2 = RGW_ADMIN.getUserInfo(v.getUserId()).get(); assertEquals(0, response2.getSwiftCredentials().size()); }); } @Test public void createSubUser() { testWithAUser( u -> { String userId = u.getUserId(); String subUserId = "SUB-" + UUID.randomUUID().toString(); String absSubUserId = String.join(":", userId, subUserId); // basic SubUser.Permission permission = SubUser.Permission.FULL; SubUser response = RGW_ADMIN.createSubUser(userId, subUserId, permission, CredentialType.SWIFT); assertEquals(permission, response.getPermission()); Optional<SwiftCredential> keyResponse = RGW_ADMIN .getUserInfo(userId) .get() .getSwiftCredentials() .stream() .filter(k -> absSubUserId.equals(k.getUserId())) .findFirst(); assertTrue(keyResponse.isPresent()); }); } @Ignore("Works in v11.2.0-kraken or above.") @Test public void _createSubUser() throws Exception { testWithAUser( v -> { String subUserId = UUID.randomUUID().toString(); // basic List<SubUser> response = RGW_ADMIN.createSubUser( v.getUserId(), subUserId, ImmutableMap.of("key-type", "s3", "access", "full")); assertEquals(1, response.size()); String fullSubUserId = v.getUserId() + ":" + subUserId; assertEquals(fullSubUserId, response.get(0).getId()); assertEquals(SubUser.Permission.FULL, response.get(0).getPermission()); // exist in get user info response User response2 = RGW_ADMIN.getUserInfo(v.getUserId()).get(); assertEquals(fullSubUserId, response2.getSubusers().get(0).getId()); // test subuser in s3 S3Credential key = response2 .getS3Credentials() .stream() .filter(e -> fullSubUserId.equals(e.getUserId())) .findFirst() .get(); AmazonS3 s3 = createS3(key.getAccessKey(), key.getSecretKey()); s3.listBuckets(); String bucketName = UUID.randomUUID().toString().toLowerCase(); s3.createBucket(bucketName); s3.putObject(bucketName, "qqq", "qqqq"); s3.listObjects(bucketName); s3.getObject(bucketName, "qqq"); }); } @Test public void checkBucketIndex() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); // not exist RGW_ADMIN.checkBucketIndex(bucketName, true, true); s3.createBucket(bucketName); // Do not know how to check the behavior... Optional result = RGW_ADMIN.checkBucketIndex(bucketName, true, true); assertTrue(result.isPresent()); }); } @Ignore("See getAndSetUserQuota()") @Test public void getUserQuota() throws Exception {} @Ignore("See getAndSetUserQuota()") @Test public void setUserQuota() throws Exception {} @Ignore("See getAndSetBucketQuota()") @Test public void getBucketQuota() throws Exception {} @Ignore("See getAndSetBucketQuota()") @Test public void setBucketQuota() throws Exception {} @Test @Ignore("See userCapability()") public void addUserCapability() throws Exception {} @Test public void userCapability() throws Exception { testWithASubUser( v -> { String userId = v.getUserId(); List<Cap> userCaps = Arrays.asList( new Cap(Cap.Type.USAGE, Cap.Perm.READ_WRITE), new Cap(Cap.Type.USERS, Cap.Perm.WRITE)); List<Cap> retUserCaps; // add retUserCaps = RGW_ADMIN.addUserCapability(userId, userCaps); assertEquals(userCaps, retUserCaps); // remove List<Cap> toRemove = userCaps.subList(0, 1); List<Cap> toRemain = userCaps.subList(1, 2); retUserCaps = RGW_ADMIN.removeUserCapability(userId, toRemove); assertEquals(toRemain, retUserCaps); }); } @Test @Ignore("See userCapability()") public void removeUserCapability() throws Exception {} @Test public void removeBucket() throws Exception { String bucketName = "testremovebkbk" + UUID.randomUUID().toString(); // remove bucket not exist Thread.sleep(3000); RGW_ADMIN.removeBucket(bucketName); testWithAUser( v -> { String userId = "testremovebk" + UUID.randomUUID().toString(); User response = RGW_ADMIN.createUser(userId); AmazonS3 s3 = createS3( response.getS3Credentials().get(0).getAccessKey(), response.getS3Credentials().get(0).getSecretKey()); s3.createBucket(bucketName); ByteArrayInputStream input = new ByteArrayInputStream("Hello World!".getBytes()); s3.putObject(bucketName, "hello.txt", input, new ObjectMetadata()); RGW_ADMIN.removeBucket(bucketName); try { s3.headBucket(new HeadBucketRequest(bucketName)); fail(); } catch (Exception e) { assertTrue("Not Found".equals(((AmazonS3Exception) e).getErrorMessage())); } }); } @Test public void unlinkBucket() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); // not exist RGW_ADMIN.unlinkBucket(bucketName, userId); s3.createBucket(bucketName); // basic RGW_ADMIN.unlinkBucket(bucketName, userId); assertEquals(0, s3.listBuckets().size()); // head is ok... s3.headBucket(new HeadBucketRequest(bucketName)); // again RGW_ADMIN.unlinkBucket(bucketName, userId); }); } @Test public void linkBucket() throws Exception { testWithAUser( v -> { String userId = "linkbkusr" + UUID.randomUUID().toString(); String bucketName = "linkbkusrbk" + UUID.randomUUID().toString(); User response = RGW_ADMIN.createUser(userId); AmazonS3 s3 = createS3( response.getS3Credentials().get(0).getAccessKey(), response.getS3Credentials().get(0).getSecretKey()); s3.createBucket(bucketName); BucketInfo _response = RGW_ADMIN.getBucketInfo(bucketName).get(); // basic String bucketId = _response.getId(); RGW_ADMIN.linkBucket(bucketName, bucketId, adminUserId); BucketInfo __response = RGW_ADMIN.getBucketInfo(bucketName).get(); assertEquals(adminUserId, __response.getOwner()); // execute again // Ceph 9.2.x throw exception; ceph 10.2.2 returns 404 so no exception will show. // exception.expect(RuntimeException.class); RGW_ADMIN.linkBucket(bucketName, bucketId, adminUserId); // bad argument // exception.expect(RuntimeException.class); RGW_ADMIN.linkBucket(bucketName + "qq", bucketId, adminUserId); // exception.expect(RuntimeException.class); RGW_ADMIN.linkBucket(bucketName, bucketId, adminUserId + "qqq"); // exception.expect(RuntimeException.class); RGW_ADMIN.linkBucket(bucketName, bucketId + "qq", adminUserId); }); } @Test public void listBucketInfo() throws Exception { testWithASubUser( v -> { AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); for (int i = 0; i < 3; i++) { s3.createBucket(UUID.randomUUID().toString().toLowerCase()); } List<BucketInfo> response; // all buckets response = RGW_ADMIN.listBucketInfo(); assertTrue(response.size() >= 3); // bucket belong to the user response = RGW_ADMIN.listBucketInfo(v.getUserId()); assertEquals(3, response.size()); }); } @Test public void listBucket() throws Exception { testWithASubUser( v -> { AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); for (int i = 0; i < 3; i++) { s3.createBucket(UUID.randomUUID().toString().toLowerCase()); } List<String> response; // all buckets response = RGW_ADMIN.listBucket(); assertTrue(response.size() >= 3); // bucket belong to the user response = RGW_ADMIN.listBucket(v.getUserId()); assertEquals(3, response.size()); }); } @Test public void getBucketInfo() throws Exception { testWithASubUser( v -> { AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = UUID.randomUUID().toString().toLowerCase(); s3.createBucket(bucketName); Optional<BucketInfo> response = RGW_ADMIN.getBucketInfo(bucketName); assertTrue(response.isPresent()); }); } @Test public void modifyUser() throws Exception { String userId = "testModifyUserId"; RGW_ADMIN.createUser(userId); // basic RGW_ADMIN.modifyUser(userId, ImmutableMap.of("max-buckets", String.valueOf(Integer.MAX_VALUE))); User response = RGW_ADMIN.getUserInfo(userId).get(); assertEquals(Integer.valueOf(Integer.MAX_VALUE), response.getMaxBuckets()); // user not exist RGW_ADMIN.modifyUser( userId + "qqqq", ImmutableMap.of("max-buckets", String.valueOf(Integer.MAX_VALUE))); // ignore call with wrong arguments RGW_ADMIN.modifyUser(userId, ImmutableMap.of("QQQQQ", String.valueOf(Integer.MAX_VALUE))); RGW_ADMIN.modifyUser(userId, ImmutableMap.of("max-buckets", "you-know-my-name")); assertEquals(Integer.valueOf(Integer.MAX_VALUE), response.getMaxBuckets()); } @Test public void removeUser() throws Exception { // The operation is success if the user is not exist in the system after the operation is // executed. String userId = "testRemoveUserId"; RGW_ADMIN.createUser(userId); RGW_ADMIN.removeUser(userId); assertFalse(RGW_ADMIN.getUserInfo(userId).isPresent()); // The operation does not throw exception even if the user is not exist in the beginning. RGW_ADMIN.removeUser(userId); } @Test public void createUser() throws Exception { String userId = "bobx" + UUID.randomUUID().toString(); try { // basic User response = RGW_ADMIN.createUser(userId); assertEquals(userId, response.getUserId()); assertNotNull(response.getS3Credentials().get(0).getAccessKey()); assertNotNull(response.getS3Credentials().get(0).getSecretKey()); assertEquals(Integer.valueOf(0), response.getSuspended()); assertEquals(Integer.valueOf(1000), response.getMaxBuckets()); // create exist one should act like modification response = RGW_ADMIN.createUser(userId, ImmutableMap.of("max-buckets", "1")); assertEquals(Integer.valueOf(1), response.getMaxBuckets()); } finally { RGW_ADMIN.removeUser(userId); } } @Test public void getUserInfo() throws Exception { // basic User response = RGW_ADMIN.getUserInfo(adminUserId).get(); assertEquals(Integer.valueOf(0), response.getSuspended()); assertEquals(adminUserId, response.getUserId()); List<Cap> caps = Arrays.asList( new Cap(Cap.Type.USERS, Cap.Perm.READ_WRITE), new Cap(Cap.Type.BUCKETS, Cap.Perm.READ_WRITE)); assertTrue(response.getCaps().containsAll(caps)); // not exist assertFalse(RGW_ADMIN.getUserInfo(UUID.randomUUID().toString()).isPresent()); } @Test public void suspendUser() throws Exception { testWithASubUser( v -> { String userId = v.getUserId(); User response; // suspend RGW_ADMIN.suspendUser(userId, true); response = RGW_ADMIN.getUserInfo(userId).get(); assertEquals(Integer.valueOf(1), response.getSuspended()); // resume RGW_ADMIN.suspendUser(userId, false); response = RGW_ADMIN.getUserInfo(userId).get(); assertEquals(Integer.valueOf(0), response.getSuspended()); }); } @Test public void userQuotaMaxObjects() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); Quota quota; // max object = 2 RGW_ADMIN.setUserQuota(userId, 2, -1); quota = RGW_ADMIN.getUserQuota(userId).get(); assertEquals(true, quota.getEnabled()); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); s3.createBucket(bucketName); // allow 1st,2ed obj s3.putObject(bucketName, userId + "1", "qqqq"); s3.putObject(bucketName, userId + "2", "qqqq"); // deny 3rd obj try { s3.putObject(bucketName, userId + "3", "qqqq"); fail(); } catch (AmazonS3Exception e) { assertEquals("QuotaExceeded", e.getErrorCode()); } }); } /* * radosgw implementation note: * The behavior of the quota evaluation is taking effect in the unit of 4KiB, i.e., isExceed = ( ceil(TO_USED_SIZE_IN_BYTE/4096) > floor(maxSize/4) ? ) * For example, when mazSize is 5, put a object with 4096 bytes will be ok, but put with 4096 + 1 bytes will be blocked. * (Assume that the used size is 0 before taking the action.) */ @Test public void userQuotaMaxSize() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); Quota quota; // max size = 6 bytes RGW_ADMIN.setUserQuota(userId, -1, 12); quota = RGW_ADMIN.getUserQuota(userId).get(); assertEquals(true, quota.getEnabled()); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); s3.createBucket(bucketName); // ok, ok, ok, since the total to used size exceed 12KiB s3.putObject(bucketName, userId + "1", createString(4096)); s3.putObject(bucketName, userId + "2", createString(4096)); s3.putObject(bucketName, userId + "3", createString(4096)); // not ok, since the total to used size exceed 12KiB +1 try { s3.putObject(bucketName, userId + "4", createString(1)); fail(); } catch (AmazonS3Exception e) { assertEquals("QuotaExceeded", e.getErrorCode()); } }); } @Test public void getAndSetUserQuota() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); Quota quota; // default false quota = RGW_ADMIN.getUserQuota(userId).get(); assertEquals(false, quota.getEnabled()); assertEquals(Long.valueOf(-1), quota.getMaxObjects()); assertTrue( quota.getMaxSizeKb() == -1 // jewel || quota.getMaxSizeKb() == 0 // kraken ); // set quota RGW_ADMIN.setUserQuota(userId, 1, 1); quota = RGW_ADMIN.getUserQuota(userId).get(); assertEquals(true, quota.getEnabled()); assertEquals(Long.valueOf(1), quota.getMaxObjects()); assertEquals(Long.valueOf(1), quota.getMaxSizeKb()); }); // user not exist try { RGW_ADMIN.getUserQuota(UUID.randomUUID().toString()); fail("user not exist should throw exception"); } catch (RgwAdminException e) { assertTrue( "InvalidArgument".equals(e.getMessage()) || // kraken "NoSuchUser".equals(e.getMessage()) // luminous ); } RGW_ADMIN.setUserQuota(UUID.randomUUID().toString(), 1, 1); } @Test public void getAndSetBucketQuota() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); s3.createBucket(bucketName); Quota quota; // default false quota = RGW_ADMIN.getBucketQuota(userId).get(); assertEquals(false, quota.getEnabled()); assertEquals(Long.valueOf(-1), quota.getMaxObjects()); assertTrue( quota.getMaxSizeKb() == -1 // jewel || quota.getMaxSizeKb() == 0 // kraken ); // set quota RGW_ADMIN.setBucketQuota(userId, 1, 1); // shown by getBucketQuota() quota = RGW_ADMIN.getBucketQuota(userId).get(); assertEquals(true, quota.getEnabled()); assertEquals(Long.valueOf(1), quota.getMaxObjects()); assertEquals(Long.valueOf(1), quota.getMaxSizeKb()); // not shown by getBucketInfo() quota = RGW_ADMIN.getBucketInfo(bucketName).get().getBucketQuota(); assertEquals(false, quota.getEnabled()); assertEquals(Long.valueOf(-1), quota.getMaxObjects()); assertTrue( quota.getMaxSizeKb() == -1 // jewel || quota.getMaxSizeKb() == 0 // kraken ); }); // user not exist try { RGW_ADMIN.getBucketQuota(UUID.randomUUID().toString()); fail("user not exist should throw exception"); } catch (RgwAdminException e) { assertTrue( "InvalidArgument".equals(e.getMessage()) || // kraken "NoSuchUser".equals(e.getMessage()) // luminous ); } RGW_ADMIN.setBucketQuota(UUID.randomUUID().toString(), 1, 1); } @Test public void getAndSetSpecificBucketQuota() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); s3.createBucket(bucketName); Quota quota; // default false quota = RGW_ADMIN.getBucketInfo(bucketName).get().getBucketQuota(); assertEquals(false, quota.getEnabled()); assertEquals(Long.valueOf(-1), quota.getMaxObjects()); assertTrue( quota.getMaxSizeKb() == -1 // jewel || quota.getMaxSizeKb() == 0 // kraken ); // set quota RGW_ADMIN.setIndividualBucketQuota(userId, bucketName, 1, 1); // not shown by getBucketQuota() quota = RGW_ADMIN.getBucketQuota(userId).get(); assertEquals(false, quota.getEnabled()); assertEquals(Long.valueOf(-1), quota.getMaxObjects()); assertTrue( quota.getMaxSizeKb() == -1 // jewel || quota.getMaxSizeKb() == 0 // kraken ); // not shown by getBucketInfo() quota = RGW_ADMIN.getBucketInfo(bucketName).get().getBucketQuota(); assertEquals(true, quota.getEnabled()); assertEquals(Long.valueOf(1), quota.getMaxObjects()); assertEquals(Long.valueOf(1), quota.getMaxSizeKb()); }); } @Test public void getObjectPolicy() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); String objectKey = userId.toLowerCase(); s3.createBucket(bucketName); s3.putObject(bucketName, objectKey, "qqq"); String resp = RGW_ADMIN.getObjectPolicy(bucketName, objectKey).get(); assertFalse(Strings.isNullOrEmpty(resp)); }); } @Test public void getBucketPolicy() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); s3.createBucket(bucketName); String resp = RGW_ADMIN.getBucketPolicy(bucketName).get(); assertFalse(Strings.isNullOrEmpty(resp)); }); } @Test public void removeObject() throws Exception { testWithAUser( (v) -> { String userId = v.getUserId(); AmazonS3 s3 = createS3( v.getS3Credentials().get(0).getAccessKey(), v.getS3Credentials().get(0).getSecretKey()); String bucketName = userId.toLowerCase(); s3.createBucket(bucketName); String objectKey = userId.toLowerCase(); s3.putObject(bucketName, objectKey, "qqq"); // basic RGW_ADMIN.removeObject(bucketName, objectKey); try { s3.getObjectMetadata(bucketName, objectKey); fail(); } catch (AmazonS3Exception e) { assertEquals(404, e.getStatusCode()); } // not exist RGW_ADMIN.removeObject(bucketName, objectKey); }); } }
package org.workdocx.cryptolite; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.KeyPair; import java.security.PrivateKey; import java.security.PublicKey; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * Test for {@link DigitalSignature}. * * @author David Carboni * */ public class DigitalSignatureTest { private DigitalSignature digitalSignature; private static KeyPair keyPair; /** * Generates a {@link KeyPair} and instantiates a {@link DigitalSignature}. */ @BeforeClass public static void setUpBeforeClass() { keyPair = Keys.newKeyPair(); } /** * Generates a {@link KeyPair} and instantiates a {@link DigitalSignature}. */ @Before public void setUp() { digitalSignature = new DigitalSignature(); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#sign(java.lang.String, java.security.PrivateKey)} * . */ @Test public void testSignStringPrivateKey() { // Given String content = Random.generateId(); PrivateKey privateKey = keyPair.getPrivate(); // When String signature = digitalSignature.sign(content, privateKey); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); assertTrue(digitalSignature.verify(content, keyPair.getPublic(), signature)); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#sign(java.lang.String, java.security.PrivateKey)} * . */ @Test public void testSignStringPrivateKeyFail() { // Given String content = Random.generateId(); String changedContent = content + "X"; PrivateKey privateKey = keyPair.getPrivate(); // When String signature = digitalSignature.sign(content, privateKey); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); assertFalse(digitalSignature.verify(changedContent, keyPair.getPublic(), signature)); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#sign(java.io.InputStream, java.security.PrivateKey)} * . * * @throws IOException * If a file IO error occurs. */ @Test public void testSignInputStreamPrivateKey() throws IOException { // Given File file = FileUtils.newFile(); InputStream content = new FileInputStream(file); PrivateKey privateKey = keyPair.getPrivate(); // When String signature = digitalSignature.sign(content, privateKey); content.close(); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); content = new FileInputStream(file); assertTrue(digitalSignature.verify(content, keyPair.getPublic(), signature)); content.close(); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#sign(java.io.InputStream, java.security.PrivateKey)} * . * * @throws IOException * If a file IO error occurs. */ @Test(expected = RuntimeException.class) public void testSignInputStreamPrivateKeyException() throws IOException { // Given File file = FileUtils.newFile(); InputStream content = new FileInputStream(file); PrivateKey privateKey = keyPair.getPrivate(); // When content.close(); digitalSignature.sign(content, privateKey); // Then // We should have the expected exception. } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#sign(java.io.InputStream, java.security.PrivateKey)} * . * * @throws IOException * If a file IO error occurs. */ @Test public void testSignInputStreamPrivateKeyFail() throws IOException { // Given File file = FileUtils.newFile(); File fileChanged = FileUtils.newFile(); InputStream content = new FileInputStream(file); PrivateKey privateKey = keyPair.getPrivate(); // When String signature = digitalSignature.sign(content, privateKey); content.close(); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); content = new FileInputStream(fileChanged); assertFalse(digitalSignature.verify(content, keyPair.getPublic(), signature)); content.close(); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#verify(java.lang.String, java.security.PublicKey, java.lang.String)} * . */ @Test public void testVerifyStringPublicKeyString() { // Given String content = Random.generateId(); PublicKey publicKey = keyPair.getPublic(); String signature = digitalSignature.sign(content, keyPair.getPrivate()); // When boolean result = digitalSignature.verify(content, publicKey, signature); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); assertTrue(result); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#verify(java.lang.String, java.security.PublicKey, java.lang.String)} * . */ @Test public void testVerifyStringPublicKeyStringFail() { // Given String content = Random.generateId(); String changedContent = content + "X"; PublicKey publicKey = keyPair.getPublic(); String signature = digitalSignature.sign(content, keyPair.getPrivate()); // When boolean result = digitalSignature.verify(changedContent, publicKey, signature); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); assertFalse(result); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#verify(java.io.InputStream, java.security.PublicKey, java.lang.String)} * . * * @throws IOException * If a file IO error occurs. */ @Test public void testVerifyInputStreamPublicKeyString() throws IOException { // Given File file = FileUtils.newFile(); InputStream content = new FileInputStream(file); PrivateKey privateKey = keyPair.getPrivate(); String signature = digitalSignature.sign(content, privateKey); content.close(); // When content = new FileInputStream(file); boolean result = digitalSignature.verify(content, keyPair.getPublic(), signature); content.close(); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); assertTrue(result); } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#verify(java.io.InputStream, java.security.PublicKey, java.lang.String)} * . * * @throws IOException * If a file IO error occurs. */ @Test(expected = RuntimeException.class) public void testVerifyInputStreamPublicKeyStringException() throws IOException { // Given File file = FileUtils.newFile(); InputStream content = new FileInputStream(file); PrivateKey privateKey = keyPair.getPrivate(); String signature = digitalSignature.sign(content, privateKey); content.close(); // When content = new FileInputStream(file); content.close(); digitalSignature.verify(content, keyPair.getPublic(), signature); // Then // We should have the expected exception. } /** * Test method for * {@link org.workdocx.cryptolite.DigitalSignature#verify(java.io.InputStream, java.security.PublicKey, java.lang.String)} * . * * @throws IOException * If a file IO error occurs. */ @Test public void testVerifyInputStreamPublicKeyStringFail() throws IOException { // Given File file = FileUtils.newFile(); File fileChanged = FileUtils.newFile(); InputStream content = new FileInputStream(file); PrivateKey privateKey = keyPair.getPrivate(); String signature = digitalSignature.sign(content, privateKey); content.close(); // When content = new FileInputStream(fileChanged); boolean result = digitalSignature.verify(content, keyPair.getPublic(), signature); content.close(); // Then System.out.println("Signature: " + signature + " (" + signature.length() + ")"); assertFalse(result); } }
package org.jcoderz.commons.taskdefs; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * This task is used to modify a deployment descriptor, making a * copy of the given entity beans with their name changed from * FooEntity to FooReaderEntity. It also modifies the accompanying * weblogic specific deployment descriptors. * @author Albrecht Messner */ public class MakeReadonlyBeans extends Task { private static final String STYLE_GENERIC = "make-readonly-bean-generic.xsl"; private static final String STYLE_WEBLOGIC = "make-readonly-bean-wl.xsl"; private static final String STYLE_WEBLOGIC_CMP = "make-readonly-bean-wlcmp.xsl"; private static final String STYLE_GENERATE_UTIL = "generate-readonly-entity-util.xsl"; /** The output directory. */ private File mDestDir; /** The generic deployment descriptor (ejb-jar.xml) to transform. */ private File mGenericDeploymentDescriptor = null; /** * The weblogic ejb deployment descriptor (weblogic-ejb-jar.xml) to * transform. */ private File mWlsDeploymentDescriptor = null; /** * The weblogic RDBMS deployment descriptor (weblogic-cmp-rdbms-jar.xml) * to transform. */ private File mWlsCmpDeploymentDescriptor = null; /** List of all beans that need to be made read-only. */ private final List mReadonlyBeans = new ArrayList(); /** force output of target files even if they already exist. */ private boolean mForce = false; /** terminate ant build on error. */ private boolean mFailOnError = false; /** The directory to which generated source files should be written. */ private File mSourceDestDir; /** * Set the destination directory into which the XSL result * files should be copied to. This parameter is required. * @param dir the name of the destination directory. **/ public void setDestdir (File dir) { mDestDir = dir; } public void setSourceDestdir (File dir) { mSourceDestDir = dir; } /** * Sets the force output of target files flag to the given value. * * @param b Whether we should force the generation of output files. */ public void setForce (boolean b) { mForce = b; } /** * Set whether we should fail on an error. * * @param b Whether we should fail on an error. */ public void setFailonerror (boolean b) { mFailOnError = b; } public void setDeploymentDescriptor (File f) { mGenericDeploymentDescriptor = f; } public void setWeblogicDeploymentDescriptor (File f) { mWlsDeploymentDescriptor = f; } public void setWeblogicCmpDeploymentDescriptor (File f) { mWlsCmpDeploymentDescriptor = f; } public ReadOnlyBean createReadOnlyBean () { final ReadOnlyBean bn = new ReadOnlyBean(); mReadonlyBeans.add(bn); return bn; } /** {@inheritDoc} */ public void execute () throws BuildException { try { checkFilesAndDirectories(); if (mForce || checkIfBuildRequired()) { final File genericDdTarget = new File(mDestDir, mGenericDeploymentDescriptor.getName()); transform(mGenericDeploymentDescriptor, genericDdTarget, STYLE_GENERIC); transform(mWlsDeploymentDescriptor, new File(mDestDir, mWlsDeploymentDescriptor.getName()), STYLE_WEBLOGIC); transform(mWlsCmpDeploymentDescriptor, new File(mDestDir, mWlsCmpDeploymentDescriptor.getName()), STYLE_WEBLOGIC_CMP); transform(genericDdTarget, new File(mDestDir, "generate-utils-stdout.txt"), STYLE_GENERATE_UTIL); } else { log("All files are up-to-date.", Project.MSG_INFO); } } catch (BuildException e) { if (mFailOnError) { throw e; } log(e.getMessage(), Project.MSG_ERR); } } private String createListOfReadonlyBeans () { final StringBuffer sbuf = new StringBuffer(); for (final Iterator it = mReadonlyBeans.iterator(); it.hasNext(); ) { if (sbuf.length() == 0) { sbuf.append('|'); } final ReadOnlyBean bean = (ReadOnlyBean) it.next(); sbuf.append(bean.getName()); sbuf.append('|'); } if (sbuf.length() == 0) { sbuf.append("||"); } return sbuf.toString(); } private boolean checkIfBuildRequired () { final File genericOutFile = new File(mDestDir, mGenericDeploymentDescriptor.getName()); final File weblogicOutFile = new File(mDestDir, mWlsDeploymentDescriptor.getName()); final File weblogicCmpOutFile = new File(mDestDir, mWlsCmpDeploymentDescriptor.getName()); boolean buildRequired = false; if (! genericOutFile.exists() || genericOutFile.lastModified() < mGenericDeploymentDescriptor.lastModified()) { buildRequired = true; } if (! weblogicOutFile.exists() || weblogicOutFile.lastModified() < mWlsDeploymentDescriptor.lastModified()) { buildRequired = true; } if (! weblogicCmpOutFile.exists() || weblogicCmpOutFile.lastModified() < mWlsCmpDeploymentDescriptor.lastModified()) { buildRequired = true; } return buildRequired; } private void checkFilesAndDirectories () { checkFile("genericDeploymentDescriptor", mGenericDeploymentDescriptor); checkFile("weblogicDeploymentDescriptor", mWlsDeploymentDescriptor); checkFile("weblogicCmpDeploymentDescriptor", mWlsCmpDeploymentDescriptor); checkDirectory("destdir", mDestDir); checkDirectory("sourceDestdir", mSourceDestDir); } private void checkFile (String paramName, File file) { if (file == null) { throw new BuildException( "Mandatory attribute '" + paramName + "' is missing."); } if (! file.exists()) { throw new BuildException("File '" + file + "' does not exist"); } } private void checkDirectory (String paramName, File directory) { if (directory == null) { throw new BuildException( "Mandatory attribute '" + paramName + "' missing."); } if (! directory.exists()) { throw new BuildException( "Output directory '" + directory + "' does not exist."); } if (! directory.isDirectory()) { throw new BuildException("'" + directory + "' is not a directory"); } } /** * Execute the XSL transformation. * @throws BuildException if an error during transformation occurs. */ private void transform (File inFile, File outFile, String xslFile) throws BuildException { try { // Xalan2 transformator is required, // that why we explicit use this factory final TransformerFactory factory = new org.apache.xalan.processor.TransformerFactoryImpl(); factory.setURIResolver(new JarArchiveUriResolver(this)); final InputStream xslStream = LogMessageGenerator.class.getResourceAsStream(xslFile); final Transformer transformer = factory.newTransformer(new StreamSource(xslStream)); transformer.setParameter("outdir", mDestDir.getAbsolutePath()); transformer.setParameter("srcdir", mSourceDestDir.getAbsolutePath()); transformer.setParameter("bean-names", createListOfReadonlyBeans()); final StreamResult out = new StreamResult(outFile); transformer.transform(getSaxSource(inFile), out); } catch (Exception e) { throw new BuildException("Error during transformation: " + e, e); } } private SAXSource getSaxSource (File xmlFile) throws SAXException, FileNotFoundException { final XMLReader xr = getXmlReader(); xr.setEntityResolver(new DummyEntityResolver(this)); final FileInputStream fileInStream = new FileInputStream(xmlFile); final InputSource inSource = new InputSource(fileInStream); return new SAXSource(xr, inSource); } private static XMLReader getXmlReader() throws SAXException { XMLReader result; try { result = XMLReaderFactory.createXMLReader( "org.apache.xerces.parsers.SAXParser"); } catch (Exception ex) { // log this? result = XMLReaderFactory.createXMLReader(); } return result; } public final class ReadOnlyBean { private String mName; /** * @return Returns the beanName. */ public String getName () { return mName; } /** * @param beanName The beanName to set. */ public void setName (String beanName) { mName = beanName; } } }
package au.com.noojee.acceloapi.cache; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import au.com.noojee.acceloapi.AcceloApi; import au.com.noojee.acceloapi.AcceloException; import au.com.noojee.acceloapi.dao.gson.GsonForAccelo; import au.com.noojee.acceloapi.entities.AcceloEntity; import au.com.noojee.acceloapi.filter.AcceloFilter; /** * Manages the caching of queries when accessing the Accelo REST API. By default we hold 10,000 queries with a 10 minute * expiry. When a query is run we also inject each of the individual entities that are returned into the cache so an * access attempt by the entities id will return from cache. The cache is a singleton use AcceloCache.getInstance() to * access it. * * @author bsutton */ @SuppressWarnings("rawtypes") public class AcceloCache { private static Logger logger = LogManager.getLogger(); // We cache queries and the set of entities that are returned. // We also create extra entries for each id so that // any subsequent queries by the entities id will find that entity. static private LoadingCache<CacheKey, List> queryCache; /* * counts the no. of times we get a cache misses since the last resetMissCounter call. */ private int missCounter = 0; static private AcceloCache self; synchronized static public AcceloCache getInstance() { if (self == null) self = new AcceloCache(); return self; } private AcceloCache() { LoadingCache<CacheKey, List> tmp = CacheBuilder.newBuilder() .maximumSize(10000) .expireAfterAccess(10, TimeUnit.MINUTES) .removalListener(notification -> { logger.error( "Cache eviction of " + notification.getKey() + " because: " + notification.getCause()); }) .build(new CacheLoader<CacheKey, List>() { @Override public List<AcceloEntity> load(CacheKey key) throws AcceloException { AcceloCache.this.missCounter++; return AcceloCache.this.runAccelQuery(key); } }); queryCache = tmp; } protected List<AcceloEntity> runAccelQuery(CacheKey key) throws AcceloException { long startTime = System.nanoTime(); @SuppressWarnings("unchecked") List<AcceloEntity> list = AcceloApi.getInstance().getAll(key.getEndPoint(), key.getFilter(), key.getFields(), key.getResponseListClass()); long elapsedTime = System.nanoTime() - startTime; logger.error("Cache miss for " + key.toString() + " Entities returned: " + list.size() + " Total Cache misses: " + this.missCounter + " elapsed time (ms):" + elapsedTime / 1000000); // We now insert the list of ids back into the cache to maximize hits // when getById is called. populateIds(key, list); return list; } /** * Push each of the entities back into the cache so that a getById call will result in a cache hit. * * @param originalKey * @param list * @throws AcceloException */ @SuppressWarnings("unchecked") private void populateIds(CacheKey originalKey, List<AcceloEntity> list) throws AcceloException { CacheKey idKey; // Check if the filter was already for an id, in which case we do // nothing. if (!originalKey.getFilter().isIDFilter()) { for (AcceloEntity entity : list) { AcceloFilter filter = new AcceloFilter(); filter.where(filter.eq(entity.getIdFilterField(), entity.getId())); idKey = new SingleEntityCacheKey(originalKey.getEndPoint(), filter, originalKey.getFields(), originalKey.getResponseListClass(), entity.getClass(), entity.getId()); put(idKey, Arrays.asList(entity)); } } } @SuppressWarnings("unchecked") public List<? extends AcceloEntity> get(CacheKey cacheKey) throws AcceloException { List<AcceloEntity> list; try { List<AcceloEntity> cachedList = queryCache.getIfPresent(cacheKey); if (cachedList == null || cacheKey.getFilter().isRefreshCache()) { if (cachedList != null) queryCache.invalidate(cacheKey); // Now go out and fetch the new list. list = queryCache.get(cacheKey); // delete any ids that no longer exist in the list returned by the query. if (cachedList != null) { List<AcceloEntity> badEntities = cachedList.stream().filter(entity -> !list.contains(entity)) .collect(Collectors.toList()); // evict any of the badEntities badEntities.stream().forEach(entity -> { queryCache.invalidate(entity); logger.debug("Evicting: " + entity); }); } } else list = cachedList; } catch (ExecutionException e) { throw (AcceloException) e.getCause(); } // We always return a cloned list as we don't want anyone changing the data in the cache accidentally. List<AcceloEntity> listCopy = list.stream().map(e -> copy(e)).collect(Collectors.toList()); logger.error("Request for : " + cacheKey + " entities returned: " + list.size()); return listCopy; // return Collections.unmodifiableList(list.c); } @SuppressWarnings("unchecked") private AcceloEntity copy(AcceloEntity rhs) { String json = GsonForAccelo.toJson(rhs); AcceloEntity copy = GsonForAccelo.fromJson(json, rhs.getClass()); return copy; } void put(CacheKey key, List<AcceloEntity> list) { queryCache.put(key, list); } public void resetMissCounter() { this.missCounter = 0; } /** * Returns the no. of cache misses since the last call to resetMissCounter; * * @return */ public int getMissCounter() { return this.missCounter; } /** * Flush every entity/query from the cache. */ public void flushCache() { queryCache.invalidateAll(); this.missCounter = 0; } /* * Flush the list of entities from the cache. */ public void flushEntities(List<? extends AcceloEntity> entities) { entities.stream().forEach(e -> flushEntity(e)); } /** * Flush the given key from the cache. * * @param key */ public void flushQuery(CacheKey key) { queryCache.invalidate(key); } public void flushEntity(AcceloEntity entity) { flushEntity(entity, false); } /* * Flushes the given entity from the cache. search the cache for any CacheKeys that are the same type as entity. * This should find both single entities inserted by populateIds as well as entities contained as part of a queries * list. If flushQueries is true then we will also flush any queries that contain the entity. */ @SuppressWarnings("unchecked") public void flushEntity(AcceloEntity entity, boolean flushQueries) { queryCache.asMap().keySet().stream().filter(k -> k.getEntityClass() == entity.getClass()) .forEach(k -> { // For a single entity added by populateid then we want to remove it. if (k instanceof SingleEntityCacheKey) { SingleEntityCacheKey seck = (SingleEntityCacheKey) k; if (seck.getId() == entity.getId()) queryCache.invalidate(k); } else { // For a query we want to prune out the deleted entity. // Get the list from the cache for the key. // this could be a list of 0, 1 or many List<? extends AcceloEntity> list; try { if (flushQueries) queryCache.invalidate(k); // we have been instructed to take out the whole query. else { list = queryCache.get(k); list.remove(entity); // Even if the list is now empty we don't invalidate the cache key as we support // negative caching. i.e. if a query returns zero results don't run it again. } } catch (ExecutionException e) { logger.error(e, e); } } }); } /** * Finds the entity (by its id and type) any where in the cache and updates it. * * @param entity */ @SuppressWarnings("unchecked") public void updateEntity(AcceloEntity entity) { queryCache.asMap().keySet().stream().filter(k -> k.getEntityClass() == entity.getClass()) .forEach(k -> { // For a single entity added by populateid then we want to remove it. if (k instanceof SingleEntityCacheKey) { SingleEntityCacheKey seck = (SingleEntityCacheKey) k; if (seck.getId() == entity.getId()) { // replace the entity with the new one. queryCache.put(k, Arrays.asList(entity)); } } else { // For a query we want to prune out the deleted entity. // Get the list from the cache for the key. // this could be a list of 0, 1 or many List<AcceloEntity> list; try { list = queryCache.get(k); // find and remove the old version of the entity. AcceloEntity element = list.stream().filter(e -> e.getId() == entity.getId()) .findFirst() .get(); list.remove(element); // add the new version of the entity. list.add(entity); } catch (ExecutionException e) { logger.error(e, e); } } }); } }
package com.github.davidcarboni.cryptolite; import org.apache.commons.lang.RandomStringUtils; import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; /** * This class provides random functions, such as Salt, ID and password * generation. It also allows you to get a singleton {@link SecureRandom} * instance. * * @author David Carboni */ public class Random { /** * The length of IDs: {@value #ID_BITS}. */ public static final int ID_BITS = 256; /** * The algorithm for the {@link SecureRandom} instance: {@value #ALGORITHM}. */ public static final String ALGORITHM = "SHA1PRNG"; /** * The length of salt values: {@value #SALT_BYTES}. */ public static final int SALT_BYTES = 16; // Work out the right number of bytes for random IDs: private static final int bitsInAByte = 8; private static final int idLengthBytes = ID_BITS / bitsInAByte; // Characters for pasword generation: private static final String passwordCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static SecureRandom secureRandom; public static SecureRandom getInstance() { // Create if necessary: if (secureRandom == null) { // NB according to the javadoc, getInstance produces an appropriate // SecureRandom, which will be seeded on the first call to // nextBytes(): // "Note that the returned instance of SecureRandom has not been // seeded. A call to the setSeed method will seed the SecureRandom // object. // If a call is not made to setSeed, the first call to the nextBytes // method will force the SecureRandom object to seed itself." try { secureRandom = SecureRandom.getInstance(ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Algorithm unavailable: " + ALGORITHM, e); } } return secureRandom; } /** * Convenience method to instantiate and populate a byte array of the specified * length. * * @param length The length of the array. * @return {@link SecureRandom#nextBytes(byte[])} */ public static byte[] bytes(int length) { byte[] bytes = new byte[length]; getInstance().nextBytes(bytes); return bytes; } /** * Convenience method to instantiate an {@link InputStream} of random data of the specified * length. * * @param length The length of the stream. * @return {@link SecureRandom#nextBytes(byte[])} */ public static InputStream inputStream(final long length) { return new InputStream() { int count; @Override public int read() throws IOException { if (count++ < length) { return ((int) bytes(1)[0]) & 0xff; // For Java 8: return Byte.toUnsignedInt(bytes(1)[0]); } else { return -1; } } }; } /** * @return A 256-bit (32 byte) random ID as a hexadecimal string. */ public static String id() { byte[] idBytes = bytes(idLengthBytes); return ByteArray.toHexString(idBytes); } /** * Convenience method to generate a random password. * * This method no longer uses Apache * {@link RandomStringUtils#random(int, int, int, boolean, boolean, char[], java.util.Random)} * , because the implementation of that method calls * {@link java.util.Random#nextInt()}, which is not overridden by the * {@link SecureRandom} returned by {@link #getInstance()}. * * That means passwords wouldn't be generated using cryptographically strong * pseudo random numbers, despite passing a {@link SecureRandom}. * * @param length The length of the password to be returned. * @return A String of the specified length, composed of uppercase letters, * lowercase letters and numbers. */ public static String password(int length) { StringBuilder result = new StringBuilder(); while (result.length() < length) { byte[] buffer = bytes(length); int i = 0; do { // There are 62 possible password characters, // So we mask out the leftmost 2 bits to get a value between 0 // and 63. That way most indices correspond to a character: int index = buffer[i++] & 0x3F; if (index < passwordCharacters.length()) { result.append(passwordCharacters.charAt(index)); } } while (result.length() < length && i < buffer.length); } return result.toString(); } /** * Generates a random salt value. If a salt value is needed by an API call, * the JavaDoc of that method should reference this method. Other than than, * it should not be necessary to call this in normal usage of this library. * * @return A {@value #SALT_BYTES}-byte random salt value as a base64-encoded * string (for easy storage). */ public static String salt() { byte[] salt = bytes(SALT_BYTES); return ByteArray.toBase64String(salt); } }
package org.netmelody.jarnia.github; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import com.google.common.base.Predicate; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import static com.google.common.collect.Iterables.find; public final class GithubFetcher { private final JsonParser jsonParser = new JsonParser(); public String fetchLatestShaFor() { return fetchLatestShaFor("netmelody", "ci-eye", "master"); } public String fetchLatestShaFor(String owner, String repo, String branch) { final String url = String.format("https://api.github.com/repos/%s/%s/branches", owner, repo); String result; result = fetch(url); final JsonElement json = jsonParser.parse(result); JsonArray branches = json.getAsJsonArray(); return find(branches, isBranchNamed(branch)).getAsJsonObject().get("commit").getAsJsonObject().get("sha").getAsString(); } private String fetch(final String url) { final SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); final ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(schemeRegistry); connectionManager.setMaxTotal(200); connectionManager.setDefaultMaxPerRoute(20); final HttpParams params = new BasicHttpParams(); params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000); DefaultHttpClient client = new DefaultHttpClient(connectionManager, params); try { final HttpGet httpget = new HttpGet(url); httpget.setHeader("Accept", "application/json"); final ResponseHandler<String> responseHandler = new BasicResponseHandler(); final String result = client.execute(httpget, responseHandler); client.getConnectionManager().shutdown(); return result; } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { return ""; } throw new IllegalStateException(e); } catch (Exception e) { throw new IllegalStateException(e); } } private Predicate<JsonElement> isBranchNamed(final String branchName) { return new Predicate<JsonElement>() { @Override public boolean apply(JsonElement input) { return branchName.equals(input.getAsJsonObject().get("name").getAsString()); } }; } }
package net.yeputons.android239.rubikscube; import java.util.ArrayList; public class SequenceRecorder { private class OriginalFaceInfo implements Cloneable { public int originalFace; // During transformation we applied wasSwapped first, revA&revB then. public boolean wasSwapped, revA, revB; public boolean isReversed; public OriginalFaceInfo clone() { OriginalFaceInfo other = new OriginalFaceInfo(); other.originalFace = originalFace; other.wasSwapped = wasSwapped; other.revA = revA; other.revB = revB; other.isReversed = isReversed; return other; } public void rotateClockwise() { wasSwapped = !wasSwapped; { boolean neA = revB, neB = revA; revA = neA; revB = neB; } revA = !revA; } public void flipVer() { revA = !revA; isReversed = !isReversed; } } private RubiksCube cube; private ArrayList<Integer> sequence; private OriginalFaceInfo[] currentRotation; public SequenceRecorder(RubiksCube start, ArrayList<Integer> sequence) { cube = start.clone(); this.sequence = sequence; currentRotation = new OriginalFaceInfo[6]; for (int i = 0; i < 6; i++) { currentRotation[i] = new OriginalFaceInfo(); currentRotation[i].originalFace = i; } rotateY(); rotateY(); rotateY(); rotateY(); for (int i = 0; i < 6; i++) { if (currentRotation[i].originalFace != i || currentRotation[i].wasSwapped || currentRotation[i].revA || currentRotation[i].revB || currentRotation[i].isReversed) throw new AssertionError("Botva"); } } public int getColor(int face, int a, int b) { OriginalFaceInfo info = currentRotation[face]; if (info.wasSwapped) { int na = b, nb = a; a = na; b = nb; } if (info.revA) a = 2 - a; if (info.revB) b = 2 - b; return cube.getColor(info.originalFace, a, b); } public void performRotation(int face) { OriginalFaceInfo info = currentRotation[face]; int cnt = info.isReversed ? 3 : 1; for (int i = 0; i < cnt; i++) { cube.performRotation(info.originalFace, 1); sequence.add(info.originalFace); } } public void flipVer() { { OriginalFaceInfo t = currentRotation[RubiksCube.LEFT]; currentRotation[RubiksCube.LEFT] = currentRotation[RubiksCube.RIGHT]; currentRotation[RubiksCube.RIGHT] = t; //currentRotation[RubiksCube.LEFT].isReversed = !currentRotation[RubiksCube.LEFT].isReversed; //currentRotation[RubiksCube.RIGHT].isReversed = !currentRotation[RubiksCube.RIGHT].isReversed; } for (int i = 0; i < 6; i++) if (i != RubiksCube.LEFT && i != RubiksCube.RIGHT) { currentRotation[i].flipVer(); } } public void rotateY() { OriginalFaceInfo[] old = new OriginalFaceInfo[6]; for (int i = 0; i < 6; i++) { old[i] = currentRotation[i].clone(); } currentRotation[RubiksCube.FRONT] = old[RubiksCube.LEFT]; currentRotation[RubiksCube.LEFT] = old[RubiksCube.BACK]; currentRotation[RubiksCube.BACK] = old[RubiksCube.RIGHT]; currentRotation[RubiksCube.RIGHT] = old[RubiksCube.FRONT]; currentRotation[RubiksCube.FRONT].isReversed = !currentRotation[RubiksCube.FRONT].isReversed; currentRotation[RubiksCube.BACK].isReversed = !currentRotation[RubiksCube.BACK].isReversed; currentRotation[RubiksCube.LEFT].revA = !currentRotation[RubiksCube.LEFT].revA; currentRotation[RubiksCube.RIGHT].revA = !currentRotation[RubiksCube.RIGHT].revA; currentRotation[RubiksCube.TOP].rotateClockwise(); currentRotation[RubiksCube.BOTTOM].rotateClockwise(); } }
package org.objectweb.proactive.core.component.asmgen; /** * Utility class for bytecode generation operations. * * @author Matthieu Morel * */ public class Utils { public static final String GENERATED_DEFAULT_PREFIX = "Generated_"; public static final String REPRESENTATIVE_DEFAULT_SUFFIX = "_representative"; public static final String COMPOSITE_REPRESENTATIVE_SUFFIX = "_composite"; public static final String STUB_DEFAULT_PACKAGE = null; public static String convertClassNameToRepresentativeClassName( String classname) { if (classname.length() == 0) { return classname; } int n = classname.lastIndexOf('.'); if (n == -1) { // no package return STUB_DEFAULT_PACKAGE + GENERATED_DEFAULT_PREFIX + classname; } else { return STUB_DEFAULT_PACKAGE + classname.substring(0, n + 1) + GENERATED_DEFAULT_PREFIX + classname.substring(n + 1); } } public static String getMetaObjectClassName( String functionalInterfaceName, String javaInterfaceName) { // just a way to have an identifier (possibly not unique ? ... but readable) return (GENERATED_DEFAULT_PREFIX + javaInterfaceName.replace('.', '_') + "_" + functionalInterfaceName.replace('.', '/').replace('-', '_')); } public static String getMetaObjectComponentRepresentativeClassName( String functionalInterfaceName, String javaInterfaceName) { // just a way to have an identifier (possibly not unique ... but readable) return (getMetaObjectClassName(functionalInterfaceName, javaInterfaceName) + REPRESENTATIVE_DEFAULT_SUFFIX); } }
package som.interpreter.nodes.dispatch; import som.interpreter.objectstorage.FieldAccess.AbstractFieldRead; import som.interpreter.objectstorage.FieldAccess.AbstractWriteFieldNode; import som.vmobjects.SObject; import som.vmobjects.SObject.SMutableObject; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.frame.VirtualFrame; import com.oracle.truffle.api.nodes.InvalidAssumptionException; public abstract class CachedSlotAccessNode extends AbstractDispatchNode { @Child protected AbstractFieldRead read; public CachedSlotAccessNode(final AbstractFieldRead read) { this.read = read; } public static final class CachedSlotRead extends CachedSlotAccessNode { @Child protected AbstractDispatchNode nextInCache; private final DispatchGuard guard; public CachedSlotRead(final AbstractFieldRead read, final DispatchGuard guard, final AbstractDispatchNode nextInCache) { super(read); this.guard = guard; this.nextInCache = nextInCache; assert nextInCache != null; } @Override public Object executeDispatch(final VirtualFrame frame, final Object[] arguments) { try { // TODO: make sure this cast is always eliminated, otherwise, we need two versions mut/immut if (guard.entryMatches(arguments[0])) { return read.read(frame, ((SObject) arguments[0])); } else { return nextInCache.executeDispatch(frame, arguments); } } catch (InvalidAssumptionException e) { CompilerDirectives.transferToInterpreter(); return replace(nextInCache). executeDispatch(frame, arguments); } } @Override public int lengthOfDispatchChain() { return 1 + nextInCache.lengthOfDispatchChain(); } } public static final class LexicallyBoundMutableSlotWrite extends AbstractDispatchNode { @Child protected AbstractWriteFieldNode write; public LexicallyBoundMutableSlotWrite(final AbstractWriteFieldNode write) { this.write = write; } @Override public Object executeDispatch(final VirtualFrame frame, final Object[] arguments) { SMutableObject rcvr = (SMutableObject) arguments[0]; return write.write(rcvr, arguments[1]); } @Override public int lengthOfDispatchChain() { return 1; } } public static final class CachedSlotWrite extends AbstractDispatchNode { @Child protected AbstractDispatchNode nextInCache; @Child protected AbstractWriteFieldNode write; private final DispatchGuard guard; public CachedSlotWrite(final AbstractWriteFieldNode write, final DispatchGuard guard, final AbstractDispatchNode nextInCache) { this.write = write; this.guard = guard; this.nextInCache = nextInCache; } @Override public Object executeDispatch(final VirtualFrame frame, final Object[] arguments) { try { if (guard.entryMatches(arguments[0])) { return write.write((SMutableObject) arguments[0], arguments[1]); } else { return nextInCache.executeDispatch(frame, arguments); } } catch (InvalidAssumptionException e) { CompilerDirectives.transferToInterpreter(); return replace(nextInCache).executeDispatch(frame, arguments); } } @Override public int lengthOfDispatchChain() { return 1 + nextInCache.lengthOfDispatchChain(); } } }