diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/com/data2semantics/hubble/client/view/patientlisting/PatientListing.java b/src/com/data2semantics/hubble/client/view/patientlisting/PatientListing.java index 44a0d16..be6aeeb 100644 --- a/src/com/data2semantics/hubble/client/view/patientlisting/PatientListing.java +++ b/src/com/data2semantics/hubble/client/view/patientlisting/PatientListing.java @@ -1,75 +1,75 @@ package com.data2semantics.hubble.client.view.patientlisting; import java.util.ArrayList; import com.data2semantics.hubble.client.helpers.Helper; import com.data2semantics.hubble.client.view.View; import com.google.gwt.user.client.rpc.AsyncCallback; import com.smartgwt.client.types.SelectionStyle; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.grid.events.SelectionChangedHandler; import com.smartgwt.client.widgets.grid.events.SelectionEvent; public class PatientListing extends ListGrid { View view; public static int WIDTH = 180; public static int HEIGHT = 400; public PatientListing(final View view) { this.view = view; setWidth(WIDTH); setHeight(HEIGHT); setEmptyMessage("Loading data"); setSelectionType(SelectionStyle.SINGLE); ListGridField nameField = new ListGridField("patientId", "Patient"); setFields(nameField); setLeaveScrollbarGap(false); addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent event) { ListGridRecord[] records = getSelectedRecords(); if (records.length > 0) { getView().showPatientInfo(records[0].getAttributeAsString("patientId")); getView().showRecommendation(records[0].getAttributeAsString("patientId")); // getView().addSouth(new WidgetsContainer(view, // records[0].getAttributeAsString("patientId"))); // getView().addSouth(new AnnotationDetails(view, // records[0].getAttributeAsString("patientId"))); // getView().addSouth(new RecommendationColumnTree(view, // records[0].getAttributeAsString("patientId"))); } } }); // draw(); getView().getServerSideApi().getPatients(new AsyncCallback<ArrayList<String>>() { public void onFailure(Throwable e) { getView().onError(e.getMessage()); } public void onSuccess(ArrayList<String> patients) { ArrayList<ListGridRecord> records = new ArrayList<ListGridRecord>(); - if (records.size() > 0) { + if (patients.size() > 0) { for (String patientId: patients) { ListGridRecord row = new ListGridRecord(); row.setAttribute("patientId", patientId); records.add(row); } } else { getView().onError("No patients found"); } setData(Helper.getListGridRecordArray(records)); selectRecord(0); redraw(); } }); } public View getView() { return view; } }
true
true
public PatientListing(final View view) { this.view = view; setWidth(WIDTH); setHeight(HEIGHT); setEmptyMessage("Loading data"); setSelectionType(SelectionStyle.SINGLE); ListGridField nameField = new ListGridField("patientId", "Patient"); setFields(nameField); setLeaveScrollbarGap(false); addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent event) { ListGridRecord[] records = getSelectedRecords(); if (records.length > 0) { getView().showPatientInfo(records[0].getAttributeAsString("patientId")); getView().showRecommendation(records[0].getAttributeAsString("patientId")); // getView().addSouth(new WidgetsContainer(view, // records[0].getAttributeAsString("patientId"))); // getView().addSouth(new AnnotationDetails(view, // records[0].getAttributeAsString("patientId"))); // getView().addSouth(new RecommendationColumnTree(view, // records[0].getAttributeAsString("patientId"))); } } }); // draw(); getView().getServerSideApi().getPatients(new AsyncCallback<ArrayList<String>>() { public void onFailure(Throwable e) { getView().onError(e.getMessage()); } public void onSuccess(ArrayList<String> patients) { ArrayList<ListGridRecord> records = new ArrayList<ListGridRecord>(); if (records.size() > 0) { for (String patientId: patients) { ListGridRecord row = new ListGridRecord(); row.setAttribute("patientId", patientId); records.add(row); } } else { getView().onError("No patients found"); } setData(Helper.getListGridRecordArray(records)); selectRecord(0); redraw(); } }); }
public PatientListing(final View view) { this.view = view; setWidth(WIDTH); setHeight(HEIGHT); setEmptyMessage("Loading data"); setSelectionType(SelectionStyle.SINGLE); ListGridField nameField = new ListGridField("patientId", "Patient"); setFields(nameField); setLeaveScrollbarGap(false); addSelectionChangedHandler(new SelectionChangedHandler() { public void onSelectionChanged(SelectionEvent event) { ListGridRecord[] records = getSelectedRecords(); if (records.length > 0) { getView().showPatientInfo(records[0].getAttributeAsString("patientId")); getView().showRecommendation(records[0].getAttributeAsString("patientId")); // getView().addSouth(new WidgetsContainer(view, // records[0].getAttributeAsString("patientId"))); // getView().addSouth(new AnnotationDetails(view, // records[0].getAttributeAsString("patientId"))); // getView().addSouth(new RecommendationColumnTree(view, // records[0].getAttributeAsString("patientId"))); } } }); // draw(); getView().getServerSideApi().getPatients(new AsyncCallback<ArrayList<String>>() { public void onFailure(Throwable e) { getView().onError(e.getMessage()); } public void onSuccess(ArrayList<String> patients) { ArrayList<ListGridRecord> records = new ArrayList<ListGridRecord>(); if (patients.size() > 0) { for (String patientId: patients) { ListGridRecord row = new ListGridRecord(); row.setAttribute("patientId", patientId); records.add(row); } } else { getView().onError("No patients found"); } setData(Helper.getListGridRecordArray(records)); selectRecord(0); redraw(); } }); }
diff --git a/impl/src/main/java/org/jboss/webbeans/BeanValidator.java b/impl/src/main/java/org/jboss/webbeans/BeanValidator.java index 293c9cc91..7f1ba45a3 100644 --- a/impl/src/main/java/org/jboss/webbeans/BeanValidator.java +++ b/impl/src/main/java/org/jboss/webbeans/BeanValidator.java @@ -1,190 +1,190 @@ /* * JBoss, Home of Professional Open Source * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.webbeans; import java.lang.annotation.Annotation; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Set; import javax.context.Dependent; import javax.event.Event; import javax.event.Fires; import javax.inject.AmbiguousDependencyException; import javax.inject.DefinitionException; import javax.inject.InconsistentSpecializationException; import javax.inject.Instance; import javax.inject.New; import javax.inject.NullableDependencyException; import javax.inject.Obtains; import javax.inject.UnproxyableDependencyException; import javax.inject.UnsatisfiedDependencyException; import javax.inject.UnserializableDependencyException; import javax.inject.manager.Bean; import javax.inject.manager.InjectionPoint; import org.jboss.webbeans.bean.NewEnterpriseBean; import org.jboss.webbeans.bean.NewSimpleBean; import org.jboss.webbeans.bean.RIBean; import org.jboss.webbeans.injection.resolution.ResolvableAnnotatedClass; import org.jboss.webbeans.introspector.AnnotatedItem; import org.jboss.webbeans.metadata.MetaDataCache; import org.jboss.webbeans.util.Beans; import org.jboss.webbeans.util.ListComparator; import org.jboss.webbeans.util.Names; import org.jboss.webbeans.util.Proxies; import org.jboss.webbeans.util.Reflections; /** * Checks a list of beans for DeploymentExceptions and their subclasses * * @author Nicklas Karlsson * */ public class BeanValidator { private final ManagerImpl manager; public BeanValidator(ManagerImpl manager) { this.manager = manager; } /** * Validates the beans * * @param beans The beans to validate */ public void validate() { final List<Bean<?>> specializedBeans = new ArrayList<Bean<?>>(); for (Bean<?> bean : manager.getBeans()) { for (InjectionPoint injectionPoint : bean.getInjectionPoints()) { if (injectionPoint.getAnnotation(New.class) != null && injectionPoint.getBindings().size() > 1) { throw new DefinitionException("The injection point " + injectionPoint + " is annotated with @New which cannot be combined with other binding types"); } if (injectionPoint.getType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType(); for (Type type : parameterizedType.getActualTypeArguments()) { if (type instanceof TypeVariable) { throw new DefinitionException("Injection point cannot have a type variable type parameter " + injectionPoint); } if (type instanceof WildcardType) { throw new DefinitionException("Injection point cannot have a wildcard type parameter " + injectionPoint); } } } checkFacadeInjectionPoint(injectionPoint, Obtains.class, Instance.class); checkFacadeInjectionPoint(injectionPoint, Fires.class, Event.class); Annotation[] bindings = injectionPoint.getBindings().toArray(new Annotation[0]); AnnotatedItem<?, ?> annotatedItem = ResolvableAnnotatedClass.of(injectionPoint.getType(), bindings); Set<?> resolvedBeans = manager.resolveByType(annotatedItem, injectionPoint, bindings); if (resolvedBeans.isEmpty()) { throw new UnsatisfiedDependencyException("The injection point " + injectionPoint + " with binding types " + Names.annotationsToString(injectionPoint.getBindings()) + " in " + bean + " has unsatisfied dependencies with binding types "); } if (resolvedBeans.size() > 1) { throw new AmbiguousDependencyException("The injection point " + injectionPoint + " with binding types " + Names.annotationsToString(injectionPoint.getBindings()) + " in " + bean + " has ambiguous dependencies"); } Bean<?> resolvedBean = (Bean<?>) resolvedBeans.iterator().next(); if (manager.getServices().get(MetaDataCache.class).getScopeModel(resolvedBean.getScopeType()).isNormal() && !Proxies.isTypeProxyable(injectionPoint.getType())) { throw new UnproxyableDependencyException("The injection point " + injectionPoint + " has non-proxyable dependencies"); } if (Reflections.isPrimitive(annotatedItem.getRawType()) && resolvedBean.isNullable()) { throw new NullableDependencyException("The injection point " + injectionPoint + " has nullable dependencies"); } if (Beans.isPassivatingBean(bean, manager) && !resolvedBean.isSerializable() && resolvedBean.getScopeType().equals(Dependent.class)) { - throw new UnserializableDependencyException("The bean " + bean + " declares a passivating scopes but has non-serializable dependency: " + resolvedBean); + throw new UnserializableDependencyException("The bean " + bean + " declares a passivating scope but has non-serializable dependency: " + resolvedBean); } } if (bean instanceof RIBean && !(bean instanceof NewSimpleBean) && !(bean instanceof NewEnterpriseBean)) { RIBean<?> abstractBean = (RIBean<?>) bean; if (abstractBean.isSpecializing()) { if (!hasHigherPrecedence(bean.getDeploymentType(), abstractBean.getSpecializedBean().getDeploymentType())) { throw new InconsistentSpecializationException("Specializing bean must have a higher precedence deployment type than the specialized bean: " + bean); } if (specializedBeans.contains(abstractBean.getSpecializedBean())) { throw new InconsistentSpecializationException("Two beans cannot specialize the same bean: " + bean); } specializedBeans.add(abstractBean.getSpecializedBean()); } } boolean normalScoped = manager.getServices().get(MetaDataCache.class).getScopeModel(bean.getScopeType()).isNormal(); if (normalScoped && !Beans.isBeanProxyable(bean)) { throw new UnproxyableDependencyException("Normal scoped bean " + bean + " is not proxyable"); } } } private boolean hasHigherPrecedence(Class<? extends Annotation> deploymentType, Class<? extends Annotation> otherDeploymentType) { Comparator<Class<? extends Annotation>> comparator = new ListComparator<Class<? extends Annotation>>(manager.getEnabledDeploymentTypes()); return comparator.compare(deploymentType, otherDeploymentType) > 0; } private void checkFacadeInjectionPoint(InjectionPoint injectionPoint, Class<? extends Annotation> annotationType, Class<?> type) { if (injectionPoint.isAnnotationPresent(annotationType)) { if (injectionPoint.getType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType(); if (!type.isAssignableFrom((Class<?>) parameterizedType.getRawType())) { throw new DefinitionException("An injection point annotated " + annotationType + " must have type " + type + " " + injectionPoint); } if (parameterizedType.getActualTypeArguments()[0] instanceof TypeVariable) { throw new DefinitionException("An injection point annotated " + annotationType + " cannot have a type variable type parameter " + injectionPoint); } if (parameterizedType.getActualTypeArguments()[0] instanceof WildcardType) { throw new DefinitionException("An injection point annotated " + annotationType + " cannot have a wildcard type parameter " + injectionPoint); } } else { throw new DefinitionException("An injection point annotated " + annotationType + " must have a type parameter " + injectionPoint); } } } }
true
true
public void validate() { final List<Bean<?>> specializedBeans = new ArrayList<Bean<?>>(); for (Bean<?> bean : manager.getBeans()) { for (InjectionPoint injectionPoint : bean.getInjectionPoints()) { if (injectionPoint.getAnnotation(New.class) != null && injectionPoint.getBindings().size() > 1) { throw new DefinitionException("The injection point " + injectionPoint + " is annotated with @New which cannot be combined with other binding types"); } if (injectionPoint.getType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType(); for (Type type : parameterizedType.getActualTypeArguments()) { if (type instanceof TypeVariable) { throw new DefinitionException("Injection point cannot have a type variable type parameter " + injectionPoint); } if (type instanceof WildcardType) { throw new DefinitionException("Injection point cannot have a wildcard type parameter " + injectionPoint); } } } checkFacadeInjectionPoint(injectionPoint, Obtains.class, Instance.class); checkFacadeInjectionPoint(injectionPoint, Fires.class, Event.class); Annotation[] bindings = injectionPoint.getBindings().toArray(new Annotation[0]); AnnotatedItem<?, ?> annotatedItem = ResolvableAnnotatedClass.of(injectionPoint.getType(), bindings); Set<?> resolvedBeans = manager.resolveByType(annotatedItem, injectionPoint, bindings); if (resolvedBeans.isEmpty()) { throw new UnsatisfiedDependencyException("The injection point " + injectionPoint + " with binding types " + Names.annotationsToString(injectionPoint.getBindings()) + " in " + bean + " has unsatisfied dependencies with binding types "); } if (resolvedBeans.size() > 1) { throw new AmbiguousDependencyException("The injection point " + injectionPoint + " with binding types " + Names.annotationsToString(injectionPoint.getBindings()) + " in " + bean + " has ambiguous dependencies"); } Bean<?> resolvedBean = (Bean<?>) resolvedBeans.iterator().next(); if (manager.getServices().get(MetaDataCache.class).getScopeModel(resolvedBean.getScopeType()).isNormal() && !Proxies.isTypeProxyable(injectionPoint.getType())) { throw new UnproxyableDependencyException("The injection point " + injectionPoint + " has non-proxyable dependencies"); } if (Reflections.isPrimitive(annotatedItem.getRawType()) && resolvedBean.isNullable()) { throw new NullableDependencyException("The injection point " + injectionPoint + " has nullable dependencies"); } if (Beans.isPassivatingBean(bean, manager) && !resolvedBean.isSerializable() && resolvedBean.getScopeType().equals(Dependent.class)) { throw new UnserializableDependencyException("The bean " + bean + " declares a passivating scopes but has non-serializable dependency: " + resolvedBean); } } if (bean instanceof RIBean && !(bean instanceof NewSimpleBean) && !(bean instanceof NewEnterpriseBean)) { RIBean<?> abstractBean = (RIBean<?>) bean; if (abstractBean.isSpecializing()) { if (!hasHigherPrecedence(bean.getDeploymentType(), abstractBean.getSpecializedBean().getDeploymentType())) { throw new InconsistentSpecializationException("Specializing bean must have a higher precedence deployment type than the specialized bean: " + bean); } if (specializedBeans.contains(abstractBean.getSpecializedBean())) { throw new InconsistentSpecializationException("Two beans cannot specialize the same bean: " + bean); } specializedBeans.add(abstractBean.getSpecializedBean()); } } boolean normalScoped = manager.getServices().get(MetaDataCache.class).getScopeModel(bean.getScopeType()).isNormal(); if (normalScoped && !Beans.isBeanProxyable(bean)) { throw new UnproxyableDependencyException("Normal scoped bean " + bean + " is not proxyable"); } } }
public void validate() { final List<Bean<?>> specializedBeans = new ArrayList<Bean<?>>(); for (Bean<?> bean : manager.getBeans()) { for (InjectionPoint injectionPoint : bean.getInjectionPoints()) { if (injectionPoint.getAnnotation(New.class) != null && injectionPoint.getBindings().size() > 1) { throw new DefinitionException("The injection point " + injectionPoint + " is annotated with @New which cannot be combined with other binding types"); } if (injectionPoint.getType() instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType(); for (Type type : parameterizedType.getActualTypeArguments()) { if (type instanceof TypeVariable) { throw new DefinitionException("Injection point cannot have a type variable type parameter " + injectionPoint); } if (type instanceof WildcardType) { throw new DefinitionException("Injection point cannot have a wildcard type parameter " + injectionPoint); } } } checkFacadeInjectionPoint(injectionPoint, Obtains.class, Instance.class); checkFacadeInjectionPoint(injectionPoint, Fires.class, Event.class); Annotation[] bindings = injectionPoint.getBindings().toArray(new Annotation[0]); AnnotatedItem<?, ?> annotatedItem = ResolvableAnnotatedClass.of(injectionPoint.getType(), bindings); Set<?> resolvedBeans = manager.resolveByType(annotatedItem, injectionPoint, bindings); if (resolvedBeans.isEmpty()) { throw new UnsatisfiedDependencyException("The injection point " + injectionPoint + " with binding types " + Names.annotationsToString(injectionPoint.getBindings()) + " in " + bean + " has unsatisfied dependencies with binding types "); } if (resolvedBeans.size() > 1) { throw new AmbiguousDependencyException("The injection point " + injectionPoint + " with binding types " + Names.annotationsToString(injectionPoint.getBindings()) + " in " + bean + " has ambiguous dependencies"); } Bean<?> resolvedBean = (Bean<?>) resolvedBeans.iterator().next(); if (manager.getServices().get(MetaDataCache.class).getScopeModel(resolvedBean.getScopeType()).isNormal() && !Proxies.isTypeProxyable(injectionPoint.getType())) { throw new UnproxyableDependencyException("The injection point " + injectionPoint + " has non-proxyable dependencies"); } if (Reflections.isPrimitive(annotatedItem.getRawType()) && resolvedBean.isNullable()) { throw new NullableDependencyException("The injection point " + injectionPoint + " has nullable dependencies"); } if (Beans.isPassivatingBean(bean, manager) && !resolvedBean.isSerializable() && resolvedBean.getScopeType().equals(Dependent.class)) { throw new UnserializableDependencyException("The bean " + bean + " declares a passivating scope but has non-serializable dependency: " + resolvedBean); } } if (bean instanceof RIBean && !(bean instanceof NewSimpleBean) && !(bean instanceof NewEnterpriseBean)) { RIBean<?> abstractBean = (RIBean<?>) bean; if (abstractBean.isSpecializing()) { if (!hasHigherPrecedence(bean.getDeploymentType(), abstractBean.getSpecializedBean().getDeploymentType())) { throw new InconsistentSpecializationException("Specializing bean must have a higher precedence deployment type than the specialized bean: " + bean); } if (specializedBeans.contains(abstractBean.getSpecializedBean())) { throw new InconsistentSpecializationException("Two beans cannot specialize the same bean: " + bean); } specializedBeans.add(abstractBean.getSpecializedBean()); } } boolean normalScoped = manager.getServices().get(MetaDataCache.class).getScopeModel(bean.getScopeType()).isNormal(); if (normalScoped && !Beans.isBeanProxyable(bean)) { throw new UnproxyableDependencyException("Normal scoped bean " + bean + " is not proxyable"); } } }
diff --git a/spoon-sample/tests/src/main/java/com/example/spoon/ordering/tests/LoginActivityTest.java b/spoon-sample/tests/src/main/java/com/example/spoon/ordering/tests/LoginActivityTest.java index c884d77..9cdb28c 100644 --- a/spoon-sample/tests/src/main/java/com/example/spoon/ordering/tests/LoginActivityTest.java +++ b/spoon-sample/tests/src/main/java/com/example/spoon/ordering/tests/LoginActivityTest.java @@ -1,184 +1,184 @@ package com.example.spoon.ordering.tests; import android.app.Instrumentation; import android.content.IntentFilter; import android.test.ActivityInstrumentationTestCase2; import android.widget.Button; import android.widget.EditText; import com.example.spoon.ordering.LoginActivity; import com.example.spoon.ordering.R; import com.squareup.spoon.Spoon; import java.util.Random; import static android.app.Instrumentation.ActivityMonitor; import static org.fest.assertions.api.ANDROID.assertThat; public class LoginActivityTest extends ActivityInstrumentationTestCase2<LoginActivity> { public LoginActivityTest() { super(LoginActivity.class); } private Instrumentation instrumentation; private LoginActivity activity; private EditText username; private EditText password; private Button login; @Override protected void setUp() throws Exception { super.setUp(); instrumentation = getInstrumentation(); activity = getActivity(); username = (EditText) activity.findViewById(R.id.username); password = (EditText) activity.findViewById(R.id.password); login = (Button) activity.findViewById(R.id.login); } public void testEmptyForm_ShowsBothErrors() { Spoon.screenshot(activity, "initial_state"); // Make sure the initial state does not show any errors. assertThat(username).hasNoError(); assertThat(password).hasNoError(); // Click the "login" button. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { login.performClick(); } }); instrumentation.waitForIdleSync(); Spoon.screenshot(activity, "login_clicked"); // Verify errors were shown for both input fields. assertThat(username).hasError(R.string.required); assertThat(password).hasError(R.string.required); } public void testBlankPassword_ShowsError() { Spoon.screenshot(activity, "initial_state"); // Make sure the initial state does not show any errors. assertThat(username).hasNoError(); assertThat(password).hasNoError(); // Type a value into the username field. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { username.setText("jake"); } }); instrumentation.waitForIdleSync(); Spoon.screenshot(activity, "username_entered"); // Click the "login" button. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { login.performClick(); } }); Spoon.screenshot(activity, "login_clicked"); // Verify error was shown only for password field. assertThat(username).hasNoError(); assertThat(password).hasError(R.string.required); } public void testBlankUsername_ShowsError() { Spoon.screenshot(activity, "initial_state"); // Make sure the initial state does not show any errors. assertThat(username).hasNoError(); assertThat(password).hasNoError(); // Type a value into the password field. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { password.setText("secretpassword"); } }); Spoon.screenshot(activity, "password_entered"); // Click the "login" button. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { login.performClick(); } }); instrumentation.waitForIdleSync(); Spoon.screenshot(activity, "login_clicked"); // Verify error was shown only for username field. assertThat(username).hasError(R.string.required); assertThat(password).hasNoError(); } public void testPasswordTooShort_ShowsError() { Spoon.screenshot(activity, "initial_state"); // Make sure the initial state does not show any errors. assertThat(username).hasNoError(); assertThat(password).hasNoError(); // Type a value into the username and password field. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { username.setText("jake"); password.setText("secret"); } }); Spoon.screenshot(activity, "values_entered"); // Click the "login" button. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { login.performClick(); } }); instrumentation.waitForIdleSync(); Spoon.screenshot(activity, "login_clicked"); // Verify error was shown only for username field. assertThat(username).hasNoError(); assertThat(password).hasError(R.string.password_length); } public void testValidValues_StartsNewActivity() { IntentFilter filter = new IntentFilter(); ActivityMonitor monitor = instrumentation.addMonitor(filter, null, false); Spoon.screenshot(activity, "initial_state"); // Make sure the initial state does not show any errors. assertThat(username).hasNoError(); assertThat(password).hasNoError(); // Type a value into the username and password field. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { username.setText("jake"); password.setText("secretpassword"); } }); Spoon.screenshot(activity, "values_entered"); // Click the "login" button. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { login.performClick(); } }); instrumentation.waitForIdleSync(); // Verify new activity was shown. assertThat(monitor).hasHits(1); Spoon.screenshot(monitor.getLastActivity(), "next_activity_shown"); // For fun (and to make the output more interesting), randomly fail! if (new Random().nextInt(4) == 0) { - throw new AssertionError("Someone set up us the bomb!"); + throw new AssertionError("Somebody set up us the bomb."); } } }
true
true
public void testValidValues_StartsNewActivity() { IntentFilter filter = new IntentFilter(); ActivityMonitor monitor = instrumentation.addMonitor(filter, null, false); Spoon.screenshot(activity, "initial_state"); // Make sure the initial state does not show any errors. assertThat(username).hasNoError(); assertThat(password).hasNoError(); // Type a value into the username and password field. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { username.setText("jake"); password.setText("secretpassword"); } }); Spoon.screenshot(activity, "values_entered"); // Click the "login" button. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { login.performClick(); } }); instrumentation.waitForIdleSync(); // Verify new activity was shown. assertThat(monitor).hasHits(1); Spoon.screenshot(monitor.getLastActivity(), "next_activity_shown"); // For fun (and to make the output more interesting), randomly fail! if (new Random().nextInt(4) == 0) { throw new AssertionError("Someone set up us the bomb!"); } }
public void testValidValues_StartsNewActivity() { IntentFilter filter = new IntentFilter(); ActivityMonitor monitor = instrumentation.addMonitor(filter, null, false); Spoon.screenshot(activity, "initial_state"); // Make sure the initial state does not show any errors. assertThat(username).hasNoError(); assertThat(password).hasNoError(); // Type a value into the username and password field. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { username.setText("jake"); password.setText("secretpassword"); } }); Spoon.screenshot(activity, "values_entered"); // Click the "login" button. instrumentation.runOnMainSync(new Runnable() { @Override public void run() { login.performClick(); } }); instrumentation.waitForIdleSync(); // Verify new activity was shown. assertThat(monitor).hasHits(1); Spoon.screenshot(monitor.getLastActivity(), "next_activity_shown"); // For fun (and to make the output more interesting), randomly fail! if (new Random().nextInt(4) == 0) { throw new AssertionError("Somebody set up us the bomb."); } }
diff --git a/src/chalmers/dax021308/ecosystem/view/ControlView.java b/src/chalmers/dax021308/ecosystem/view/ControlView.java index df6f3f6..4c2eca5 100644 --- a/src/chalmers/dax021308/ecosystem/view/ControlView.java +++ b/src/chalmers/dax021308/ecosystem/view/ControlView.java @@ -1,88 +1,87 @@ package chalmers.dax021308.ecosystem.view; import javax.swing.JPanel; import javax.swing.JButton; import chalmers.dax021308.ecosystem.model.environment.EcoWorld; import chalmers.dax021308.ecosystem.model.util.Log; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; import net.miginfocom.swing.MigLayout; /** * The view that holds the controls for starting, stopping and pausing a simulation. * A panel that is part of the frame that holds the entire application. * * @author Hanna * */ public class ControlView extends JPanel { private static final long serialVersionUID = 5134812517352174052L; /** * Create the panel. */ public ControlView(final EcoWorld ew) { JButton btnStart = new JButton("Start"); btnStart.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { ew.start(); } catch (IllegalStateException ex) { Log.v("EcoWorld already stopped"); } } }); - setLayout(new MigLayout("", "[63px][61px][69px]", "[25px]")); + setLayout(new MigLayout("", "[63px][61px][69px][][][]", "[25px]")); add(btnStart, "cell 0 0,alignx left,aligny top"); JButton btnStop = new JButton("Stop"); btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.stop(); } catch (IllegalStateException ex) { Log.v("EcoWorld already stopped"); } } }); - btnStop.setFont(new Font("Tahoma", Font.PLAIN, 14)); - add(btnStop, "cell 1 0,alignx left,aligny top"); JButton btnPause = new JButton("Pause"); btnPause.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnPause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.pause(); } catch (IllegalStateException ex) { //Don't care. } - new NewSimulationView(ew); } }); - add(btnPause, "cell 2 0,alignx left,aligny top"); + add(btnPause, "flowx,cell 1 0,alignx left,aligny top"); + btnStop.setFont(new Font("Tahoma", Font.PLAIN, 14)); + add(btnStop, "cell 1 0,alignx left,aligny top"); JButton btnStartNew = new JButton("Start new Simulation"); btnStartNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.stop(); } catch (IllegalStateException ex) { //Don't care. } new NewSimulationView(ew); } }); btnStartNew.setFont(new Font("Tahoma", Font.PLAIN, 14)); - add(btnStartNew, "cell 1 0,alignx left,aligny top"); + add(btnStartNew, "cell 5 0,alignx left,aligny top"); } }
false
true
public ControlView(final EcoWorld ew) { JButton btnStart = new JButton("Start"); btnStart.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { ew.start(); } catch (IllegalStateException ex) { Log.v("EcoWorld already stopped"); } } }); setLayout(new MigLayout("", "[63px][61px][69px]", "[25px]")); add(btnStart, "cell 0 0,alignx left,aligny top"); JButton btnStop = new JButton("Stop"); btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.stop(); } catch (IllegalStateException ex) { Log.v("EcoWorld already stopped"); } } }); btnStop.setFont(new Font("Tahoma", Font.PLAIN, 14)); add(btnStop, "cell 1 0,alignx left,aligny top"); JButton btnPause = new JButton("Pause"); btnPause.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnPause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.pause(); } catch (IllegalStateException ex) { //Don't care. } new NewSimulationView(ew); } }); add(btnPause, "cell 2 0,alignx left,aligny top"); JButton btnStartNew = new JButton("Start new Simulation"); btnStartNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.stop(); } catch (IllegalStateException ex) { //Don't care. } new NewSimulationView(ew); } }); btnStartNew.setFont(new Font("Tahoma", Font.PLAIN, 14)); add(btnStartNew, "cell 1 0,alignx left,aligny top"); }
public ControlView(final EcoWorld ew) { JButton btnStart = new JButton("Start"); btnStart.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnStart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { ew.start(); } catch (IllegalStateException ex) { Log.v("EcoWorld already stopped"); } } }); setLayout(new MigLayout("", "[63px][61px][69px][][][]", "[25px]")); add(btnStart, "cell 0 0,alignx left,aligny top"); JButton btnStop = new JButton("Stop"); btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.stop(); } catch (IllegalStateException ex) { Log.v("EcoWorld already stopped"); } } }); JButton btnPause = new JButton("Pause"); btnPause.setFont(new Font("Tahoma", Font.PLAIN, 14)); btnPause.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.pause(); } catch (IllegalStateException ex) { //Don't care. } } }); add(btnPause, "flowx,cell 1 0,alignx left,aligny top"); btnStop.setFont(new Font("Tahoma", Font.PLAIN, 14)); add(btnStop, "cell 1 0,alignx left,aligny top"); JButton btnStartNew = new JButton("Start new Simulation"); btnStartNew.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { ew.stop(); } catch (IllegalStateException ex) { //Don't care. } new NewSimulationView(ew); } }); btnStartNew.setFont(new Font("Tahoma", Font.PLAIN, 14)); add(btnStartNew, "cell 5 0,alignx left,aligny top"); }
diff --git a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java index e69ca8d5..4de854f9 100644 --- a/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java +++ b/core/src/com/google/zxing/qrcode/decoder/DecodedBitStreamParser.java @@ -1,235 +1,238 @@ /* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing.qrcode.decoder; import com.google.zxing.ReaderException; import java.io.UnsupportedEncodingException; /** * <p>QR Codes can encode text as bits in one of several modes, and can use multiple modes * in one QR Code. This class decodes the bits back into text.</p> * * <p>See ISO 18004:2006, 6.4.3 - 6.4.7</p> * * @author [email protected] (Sean Owen) */ final class DecodedBitStreamParser { /** * See ISO 18004:2006, 6.4.4 Table 5 */ private static final char[] ALPHANUMERIC_CHARS = new char[]{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*', '+', '-', '.', '/', ':' }; private static final String SHIFT_JIS = "Shift_JIS"; private static final boolean ASSUME_SHIFT_JIS; private static final String UTF8 = "UTF-8"; private static final String ISO88591 = "ISO-8859-1"; static { String platformDefault = System.getProperty("file.encoding"); ASSUME_SHIFT_JIS = SHIFT_JIS.equalsIgnoreCase(platformDefault) || "EUC-JP".equalsIgnoreCase(platformDefault); } private DecodedBitStreamParser() { } static String decode(byte[] bytes, Version version) throws ReaderException { BitSource bits = new BitSource(bytes); StringBuffer result = new StringBuffer(); Mode mode; do { // While still another segment to read... mode = Mode.forBits(bits.readBits(4)); // mode is encoded by 4 bits if (!mode.equals(Mode.TERMINATOR)) { // How many characters will follow, encoded in this mode? int count = bits.readBits(mode.getCharacterCountBits(version)); if (mode.equals(Mode.NUMERIC)) { decodeNumericSegment(bits, result, count); } else if (mode.equals(Mode.ALPHANUMERIC)) { decodeAlphanumericSegment(bits, result, count); } else if (mode.equals(Mode.BYTE)) { decodeByteSegment(bits, result, count); } else if (mode.equals(Mode.KANJI)) { decodeKanjiSegment(bits, result, count); } else { throw new ReaderException("Unsupported mode indicator"); } } } while (!mode.equals(Mode.TERMINATOR)); // I thought it wasn't allowed to leave extra bytes after the terminator but it happens /* int bitsLeft = bits.available(); if (bitsLeft > 0) { if (bitsLeft > 6 || bits.readBits(bitsLeft) != 0) { throw new ReaderException("Excess bits or non-zero bits after terminator mode indicator"); } } */ return result.toString(); } private static void decodeKanjiSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Each character will require 2 bytes. Read the characters as 2-byte pairs // and decode as Shift_JIS afterwards byte[] buffer = new byte[2 * count]; int offset = 0; while (count > 0) { // Each 13 bits encodes a 2-byte character int twoBytes = bits.readBits(13); int assembledTwoBytes = ((twoBytes / 0x0C0) << 8) | (twoBytes % 0x0C0); if (assembledTwoBytes < 0x01F00) { // In the 0x8140 to 0x9FFC range assembledTwoBytes += 0x08140; } else { // In the 0xE040 to 0xEBBF range assembledTwoBytes += 0x0C140; } buffer[offset] = (byte) (assembledTwoBytes >> 8); buffer[offset + 1] = (byte) assembledTwoBytes; offset += 2; count--; } // Shift_JIS may not be supported in some environments: try { result.append(new String(buffer, SHIFT_JIS)); } catch (UnsupportedEncodingException uee) { throw new ReaderException(SHIFT_JIS + " encoding is not supported on this device"); } } private static void decodeByteSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { byte[] readBytes = new byte[count]; if (count << 3 > bits.available()) { throw new ReaderException("Count too large: " + count); } for (int i = 0; i < count; i++) { readBytes[i] = (byte) bits.readBits(8); } // The spec isn't clear on this mode; see // section 6.4.5: t does not say which encoding to assuming // upon decoding. I have seen ISO-8859-1 used as well as // Shift_JIS -- without anything like an ECI designator to // give a hint. String encoding = guessEncoding(readBytes); try { result.append(new String(readBytes, encoding)); } catch (UnsupportedEncodingException uce) { throw new ReaderException(uce.toString()); } } private static void decodeAlphanumericSegment(BitSource bits, StringBuffer result, int count) { // Read two characters at a time while (count > 1) { int nextTwoCharsBits = bits.readBits(11); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits / 45]); result.append(ALPHANUMERIC_CHARS[nextTwoCharsBits % 45]); count -= 2; } if (count == 1) { // special case: one character left result.append(ALPHANUMERIC_CHARS[bits.readBits(6)]); } } private static void decodeNumericSegment(BitSource bits, StringBuffer result, int count) throws ReaderException { // Read three digits at a time while (count >= 3) { // Each 10 bits encodes three digits int threeDigitsBits = bits.readBits(10); if (threeDigitsBits >= 1000) { throw new ReaderException("Illegal value for 3-digit unit: " + threeDigitsBits); } result.append(ALPHANUMERIC_CHARS[threeDigitsBits / 100]); result.append(ALPHANUMERIC_CHARS[(threeDigitsBits / 10) % 10]); result.append(ALPHANUMERIC_CHARS[threeDigitsBits % 10]); count -= 3; } if (count == 2) { // Two digits left over to read, encoded in 7 bits int twoDigitsBits = bits.readBits(7); if (twoDigitsBits >= 100) { throw new ReaderException("Illegal value for 2-digit unit: " + twoDigitsBits); } result.append(ALPHANUMERIC_CHARS[twoDigitsBits / 10]); result.append(ALPHANUMERIC_CHARS[twoDigitsBits % 10]); } else if (count == 1) { // One digit left over to read int digitBits = bits.readBits(4); if (digitBits >= 10) { throw new ReaderException("Illegal value for digit unit: " + digitBits); } result.append(ALPHANUMERIC_CHARS[digitBits]); } } private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; + boolean canBeISO88591 = true; for (int i = 0; i < length; i++) { int value = bytes[i] & 0xFF; if (value >= 0x80 && value <= 0x9F && i < length - 1) { + canBeISO88591 = false; // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, // just double check that it is followed by a byte that's valid in // the Shift_JIS encoding int nextValue = bytes[i + 1] & 0xFF; if ((value & 0x1) == 0) { - // if even, - if (nextValue >= 0x9F && nextValue <= 0xFC) { - return SHIFT_JIS; + // if even, next value should be in [0x9F,0xFC] + // if not, we'll guess UTF-8 + if (nextValue < 0x9F || nextValue > 0xFC) { + return UTF8; } } else { - if (nextValue >= 0x40 && nextValue <= 0x9E) { - return SHIFT_JIS; + // if odd, next value should be in [0x40,0x9E] + // if not, we'll guess UTF-8 + if (nextValue < 0x40 || nextValue > 0x9E) { + return UTF8; } } - // otherwise we're going to take a guess that it's UTF-8 - return UTF8; } } - return ISO88591; + return canBeISO88591 ? ISO88591 : SHIFT_JIS; } }
false
true
private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; for (int i = 0; i < length; i++) { int value = bytes[i] & 0xFF; if (value >= 0x80 && value <= 0x9F && i < length - 1) { // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, // just double check that it is followed by a byte that's valid in // the Shift_JIS encoding int nextValue = bytes[i + 1] & 0xFF; if ((value & 0x1) == 0) { // if even, if (nextValue >= 0x9F && nextValue <= 0xFC) { return SHIFT_JIS; } } else { if (nextValue >= 0x40 && nextValue <= 0x9E) { return SHIFT_JIS; } } // otherwise we're going to take a guess that it's UTF-8 return UTF8; } } return ISO88591; }
private static String guessEncoding(byte[] bytes) { if (ASSUME_SHIFT_JIS) { return SHIFT_JIS; } // Does it start with the UTF-8 byte order mark? then guess it's UTF-8 if (bytes.length > 3 && bytes[0] == (byte) 0xEF && bytes[1] == (byte) 0xBB && bytes[2] == (byte) 0xBF) { return UTF8; } // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS, // which should be by far the most common encodings. ISO-8859-1 // should not have bytes in the 0x80 - 0x9F range, while Shift_JIS // uses this as a first byte of a two-byte character. If we see this // followed by a valid second byte in Shift_JIS, assume it is Shift_JIS. // If we see something else in that second byte, we'll make the risky guess // that it's UTF-8. int length = bytes.length; boolean canBeISO88591 = true; for (int i = 0; i < length; i++) { int value = bytes[i] & 0xFF; if (value >= 0x80 && value <= 0x9F && i < length - 1) { canBeISO88591 = false; // ISO-8859-1 shouldn't use this, but before we decide it is Shift_JIS, // just double check that it is followed by a byte that's valid in // the Shift_JIS encoding int nextValue = bytes[i + 1] & 0xFF; if ((value & 0x1) == 0) { // if even, next value should be in [0x9F,0xFC] // if not, we'll guess UTF-8 if (nextValue < 0x9F || nextValue > 0xFC) { return UTF8; } } else { // if odd, next value should be in [0x40,0x9E] // if not, we'll guess UTF-8 if (nextValue < 0x40 || nextValue > 0x9E) { return UTF8; } } } } return canBeISO88591 ? ISO88591 : SHIFT_JIS; }
diff --git a/hudson-core/src/main/java/hudson/model/AbstractProject.java b/hudson-core/src/main/java/hudson/model/AbstractProject.java index c728489d..d936f4df 100644 --- a/hudson-core/src/main/java/hudson/model/AbstractProject.java +++ b/hudson-core/src/main/java/hudson/model/AbstractProject.java @@ -1,2173 +1,2178 @@ /******************************************************************************* * * Copyright (c) 2004-2011 Oracle Corporation. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * * Kohsuke Kawaguchi, Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot, Luca Domenico Milanesio, * R. Tyler Ballance, Stephen Connolly, Tom Huybrechts, id:cactusman, Yahoo! Inc., Anton Kozak, Nikita Levyankov * * *******************************************************************************/ package hudson.model; import antlr.ANTLRException; import hudson.AbortException; import hudson.CopyOnWrite; import hudson.FeedAdapter; import hudson.FilePath; import hudson.Launcher; import hudson.Util; import hudson.cli.declarative.CLIMethod; import hudson.cli.declarative.CLIResolver; import hudson.diagnosis.OldDataMonitor; import hudson.model.Cause.LegacyCodeCause; import hudson.model.Cause.RemoteCause; import hudson.model.Cause.UserCause; import hudson.model.Descriptor.FormException; import hudson.model.Fingerprint.RangeSet; import hudson.model.Queue.Executable; import hudson.model.Queue.Task; import hudson.model.Queue.WaitingItem; import hudson.model.RunMap.Constructor; import hudson.model.labels.LabelAtom; import hudson.model.labels.LabelExpression; import hudson.util.CascadingUtil; import hudson.util.DescribableListUtil; import org.eclipse.hudson.api.model.IProjectProperty; import org.eclipse.hudson.api.model.project.property.BooleanProjectProperty; import org.eclipse.hudson.api.model.project.property.IntegerProjectProperty; import hudson.model.queue.CauseOfBlockage; import hudson.model.queue.SubTask; import hudson.model.queue.SubTaskContributor; import hudson.scm.ChangeLogSet; import hudson.scm.ChangeLogSet.Entry; import hudson.scm.NullSCM; import hudson.scm.PollingResult; import hudson.scm.SCM; import hudson.scm.SCMRevisionState; import hudson.scm.SCMS; import hudson.search.SearchIndexBuilder; import hudson.security.Permission; import hudson.slaves.WorkspaceList; import hudson.tasks.BuildStep; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.BuildTrigger; import hudson.tasks.BuildWrapperDescriptor; import hudson.tasks.Mailer; import hudson.tasks.Publisher; import hudson.triggers.SCMTrigger; import hudson.triggers.Trigger; import hudson.triggers.TriggerDescriptor; import hudson.util.AutoCompleteSeeder; import hudson.util.DescribableList; import hudson.util.EditDistance; import hudson.util.FormValidation; import hudson.widgets.BuildHistoryWidget; import hudson.widgets.HistoryWidget; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.Vector; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.eclipse.hudson.api.model.IAbstractProject; import org.eclipse.hudson.api.model.project.property.SCMProjectProperty; import org.eclipse.hudson.api.model.project.property.StringProjectProperty; import org.eclipse.hudson.api.model.project.property.TriggerProjectProperty; import org.kohsuke.args4j.Argument; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.stapler.ForwardToView; import org.kohsuke.stapler.HttpRedirect; import org.kohsuke.stapler.HttpResponse; import org.kohsuke.stapler.HttpResponses; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; import static hudson.scm.PollingResult.BUILD_NOW; import static hudson.scm.PollingResult.NO_CHANGES; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; /** * Base implementation of {@link Job}s that build software. * * For now this is primarily the common part of {@link Project} and MavenModule. * * @author Kohsuke Kawaguchi * @see AbstractBuild */ public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem, IAbstractProject { public static final String CONCURRENT_BUILD_PROPERTY_NAME = "concurrentBuild"; public static final String CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME = "cleanWorkspaceRequired"; public static final String BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME = "blockBuildWhenDownstreamBuilding"; public static final String BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME = "blockBuildWhenUpstreamBuilding"; public static final String QUIET_PERIOD_PROPERTY_NAME = "quietPeriod"; public static final String SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME = "scmCheckoutRetryCount"; public static final String CUSTOM_WORKSPACE_PROPERTY_NAME = "customWorkspace"; public static final String JDK_PROPERTY_NAME = "jdk"; public static final String SCM_PROPERTY_NAME = "scm"; public static final String HAS_QUIET_PERIOD_PROPERTY_NAME = "hasQuietPeriod"; public static final String HAS_SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME = "hasScmCheckoutRetryCount"; /** * {@link SCM} associated with the project. * To allow derived classes to link {@link SCM} config to elsewhere, * access to this variable should always go through {@link #getScm()}. * @deprecated as of 2.2.0 * don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ @Deprecated private volatile SCM scm = new NullSCM(); /** * State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}. */ private volatile transient SCMRevisionState pollingBaseline = null; /** * All the builds keyed by their build number. */ protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>(); /** * The quiet period. Null to delegate to the system default. * @deprecated as of 2.2.0 * don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. * */ @Deprecated private volatile Integer quietPeriod = null; /** * The retry count. Null to delegate to the system default. * @deprecated as of 2.2.0 * don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ @Deprecated private volatile Integer scmCheckoutRetryCount = null; /** * If this project is configured to be only built on a certain label, * this value will be set to that label. * * For historical reasons, this is called 'assignedNode'. Also for * a historical reason, null to indicate the affinity * with the master node. * * @see #canRoam */ private String assignedNode; /** * Node list is dropdown or textfield */ private Boolean advancedAffinityChooser; /** * True if this project can be built on any node. * * <p> * This somewhat ugly flag combination is so that we can migrate * existing Hudson installations nicely. */ private volatile boolean canRoam; /** * True to suspend new builds. */ protected volatile boolean disabled; /** * True to keep builds of this project in queue when downstream projects are building. * * @deprecated as of 2.2.0. Don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ @Deprecated protected volatile boolean blockBuildWhenDownstreamBuilding; /** * True to keep builds of this project in queue when upstream projects are building. * * @deprecated as of 2.2.0. Don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ @Deprecated protected volatile boolean blockBuildWhenUpstreamBuilding; /** * Identifies {@link JDK} to be used. * Null if no explicit configuration is required. * * <p> * Can't store {@link JDK} directly because {@link Hudson} and {@link Project} * are saved independently. * * @see Hudson#getJDK(String) * @deprecated as of 2.2.0 * don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ @Deprecated private volatile String jdk; /** * @deprecated since 2007-01-29. */ @Deprecated private transient boolean enableRemoteTrigger; private volatile BuildAuthorizationToken authToken = null; /** * List of all {@link Trigger}s for this project. * * @deprecated as of 2.2.0 * * don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ protected List<Trigger<?>> triggers = new Vector<Trigger<?>>(); /** * {@link Action}s contributed from subsidiary objects associated with * {@link AbstractProject}, such as from triggers, builders, publishers, etc. * * We don't want to persist them separately, and these actions * come and go as configuration change, so it's kept separate. */ @CopyOnWrite protected transient volatile List<Action> transientActions = new Vector<Action>(); /** * @deprecated as of 2.2.0 Don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ @Deprecated private boolean concurrentBuild; /** * True to clean the workspace prior to each build. * * @deprecated as of 2.2.0 don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}. * Use getter/setter for accessing to this field. */ @Deprecated private volatile boolean cleanWorkspaceRequired; protected AbstractProject(ItemGroup parent, String name) { super(parent, name); if (Hudson.getInstance() != null && !Hudson.getInstance().getNodes().isEmpty()) { // if a new job is configured with Hudson that already has slave nodes // make it roamable by default canRoam = true; } } @Override public void onCreatedFromScratch() { super.onCreatedFromScratch(); // solicit initial contributions, especially from TransientProjectActionFactory updateTransientActions(); setCreationTime(new GregorianCalendar().getTimeInMillis()); User user = User.current(); if (user != null){ setCreatedBy(user.getId()); grantProjectMatrixPermissions(user); } } @Override public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { super.onLoad(parent, name); this.builds = new RunMap<R>(); this.builds.load(this, new Constructor<R>() { public R create(File dir) throws IOException { return loadBuild(dir); } }); // boolean! Can't tell if xml file contained false.. if (enableRemoteTrigger) OldDataMonitor.report(this, "1.77"); for (Trigger t : getTriggerDescribableList()) { t.start(this,false); } if(scm==null) scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists. if(transientActions==null) transientActions = new Vector<Action>(); // happens when loaded from disk updateTransientActions(); getTriggerDescribableList().setOwner(this); } @Override protected void buildProjectProperties() throws IOException { super.buildProjectProperties(); convertBlockBuildWhenUpstreamBuildingProperty(); convertBlockBuildWhenDownstreamBuildingProperty(); convertConcurrentBuildProperty(); convertCleanWorkspaceRequiredProperty(); convertQuietPeriodProperty(); convertScmCheckoutRetryCountProperty(); convertJDKProperty(); convertTriggerProperties(); } void convertBlockBuildWhenUpstreamBuildingProperty() throws IOException { if (null == getProperty(BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME)) { setBlockBuildWhenUpstreamBuilding(blockBuildWhenUpstreamBuilding); blockBuildWhenUpstreamBuilding = false; } } void convertBlockBuildWhenDownstreamBuildingProperty() throws IOException { if (null == getProperty(BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME)) { setBlockBuildWhenDownstreamBuilding(blockBuildWhenDownstreamBuilding); blockBuildWhenDownstreamBuilding = false; } } void convertConcurrentBuildProperty() throws IOException { if (null == getProperty(CONCURRENT_BUILD_PROPERTY_NAME)) { setConcurrentBuild(concurrentBuild); concurrentBuild = false; } } void convertCleanWorkspaceRequiredProperty() throws IOException { if (null == getProperty(CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME)) { setCleanWorkspaceRequired(cleanWorkspaceRequired); cleanWorkspaceRequired = false; } } void convertQuietPeriodProperty() throws IOException { if (null != quietPeriod && null == getProperty(QUIET_PERIOD_PROPERTY_NAME)) { setQuietPeriod(quietPeriod); quietPeriod = null; } } void convertScmCheckoutRetryCountProperty() throws IOException { if (null != scmCheckoutRetryCount && null == getProperty(SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME)) { setScmCheckoutRetryCount(scmCheckoutRetryCount); scmCheckoutRetryCount = null; } } void convertJDKProperty() throws IOException { if (null != jdk && null == getProperty(JDK_PROPERTY_NAME)) { setJDK(jdk); jdk = null; } } void convertScmProperty() throws IOException { if (null != scm && null == getProperty(SCM_PROPERTY_NAME)) { setScm(scm); scm = null; } } void convertTriggerProperties() { if (triggers != null) { setTriggers(triggers); triggers = null; } } @Override protected void performDelete() throws IOException, InterruptedException { // prevent a new build while a delete operation is in progress makeDisabled(true); FilePath ws = getWorkspace(); if(ws!=null) { Node on = getLastBuiltOn(); getScm().processWorkspaceBeforeDeletion(this, ws, on); if(on!=null) on.getFileSystemProvisioner().discardWorkspace(this,ws); } super.performDelete(); } /** * Does this project perform concurrent builds? * @since 1.319 */ @Exported public boolean isConcurrentBuild() { return Hudson.CONCURRENT_BUILD && CascadingUtil.getBooleanProjectProperty(this, CONCURRENT_BUILD_PROPERTY_NAME).getValue(); } public void setConcurrentBuild(boolean b) throws IOException { CascadingUtil.getBooleanProjectProperty(this, CONCURRENT_BUILD_PROPERTY_NAME).setValue(b); save(); } public boolean isCleanWorkspaceRequired() { return CascadingUtil.getBooleanProjectProperty(this, CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME).getValue(); } public void setCleanWorkspaceRequired(boolean cleanWorkspaceRequired) { CascadingUtil.getBooleanProjectProperty(this, CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME).setValue(cleanWorkspaceRequired); } /** * If this project is configured to be always built on this node, * return that {@link Node}. Otherwise null. */ public Label getAssignedLabel() { if(canRoam) return null; if(assignedNode==null) return Hudson.getInstance().getSelfLabel(); return Hudson.getInstance().getLabel(assignedNode); } /** * Gets the textual representation of the assigned label as it was entered by the user. */ public String getAssignedLabelString() { if (canRoam || assignedNode==null) return null; try { LabelExpression.parseExpression(assignedNode); return assignedNode; } catch (ANTLRException e) { // must be old label or host name that includes whitespace or other unsafe chars return LabelAtom.escape(assignedNode); } } /** * Sets the assigned label. */ public void setAssignedLabel(Label l) throws IOException { if(l==null) { canRoam = true; assignedNode = null; } else { canRoam = false; if(l==Hudson.getInstance().getSelfLabel()) assignedNode = null; else assignedNode = l.getExpression(); } save(); } /** * Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}. */ public void setAssignedNode(Node l) throws IOException { setAssignedLabel(l.getSelfLabel()); } /** * Gets whether this project is using the advanced affinity chooser UI. * * @return true - advanced chooser, false - simple textfield. */ public boolean isAdvancedAffinityChooser() { //For newly created project advanced chooser is not used. //Set value to false in order to avoid NullPointerException if (null == advancedAffinityChooser) { advancedAffinityChooser = false; } return advancedAffinityChooser; } /** * Sets whether this project is using the advanced affinity chooser UI. * * @param b true - advanced chooser, false - otherwise */ public void setAdvancedAffinityChooser(boolean b) throws IOException { advancedAffinityChooser = b; save(); } /** * Get the term used in the UI to represent this kind of {@link AbstractProject}. * Must start with a capital letter. */ @Override public String getPronoun() { return Messages.AbstractProject_Pronoun(); } /** * Returns the root project value. * * @return the root project value. */ public AbstractProject getRootProject() { if (this.getParent() instanceof Hudson) { return this; } else { return ((AbstractProject) this.getParent()).getRootProject(); } } /** * Gets the directory where the module is checked out. * * @return * null if the workspace is on a slave that's not connected. * @deprecated as of 1.319 * To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}. * For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called * from {@link Executor}, and otherwise the workspace of the last build. * * <p> * If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}. * If you are calling this method to serve a file from the workspace, doing a form validation, etc., then * use {@link #getSomeWorkspace()} */ public final FilePath getWorkspace() { AbstractBuild b = getBuildForDeprecatedMethods(); return b != null ? b.getWorkspace() : null; } /** * Various deprecated methods in this class all need the 'current' build. This method returns * the build suitable for that purpose. * * @return An AbstractBuild for deprecated methods to use. */ private AbstractBuild getBuildForDeprecatedMethods() { Executor e = Executor.currentExecutor(); if(e!=null) { Executable exe = e.getCurrentExecutable(); if (exe instanceof AbstractBuild) { AbstractBuild b = (AbstractBuild) exe; if(b.getProject()==this) return b; } } R lb = getLastBuild(); if(lb!=null) return lb; return null; } /** * Gets a workspace for some build of this project. * * <p> * This is useful for obtaining a workspace for the purpose of form field validation, where exactly * which build the workspace belonged is less important. The implementation makes a cursory effort * to find some workspace. * * @return * null if there's no available workspace. * @since 1.319 */ public final FilePath getSomeWorkspace() { R b = getSomeBuildWithWorkspace(); return b!=null ? b.getWorkspace() : null; } /** * Gets some build that has a live workspace. * * @return null if no such build exists. */ public final R getSomeBuildWithWorkspace() { int cnt=0; for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) { FilePath ws = b.getWorkspace(); if (ws!=null) return b; } return null; } /** * Returns the root directory of the checked-out module. * <p> * This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt> * and so on exists. * * @deprecated as of 1.319 * See {@link #getWorkspace()} for a migration strategy. */ public FilePath getModuleRoot() { AbstractBuild b = getBuildForDeprecatedMethods(); return b != null ? b.getModuleRoot() : null; } /** * Returns the root directories of all checked-out modules. * <p> * Some SCMs support checking out multiple modules into the same workspace. * In these cases, the returned array will have a length greater than one. * @return The roots of all modules checked out from the SCM. * * @deprecated as of 1.319 * See {@link #getWorkspace()} for a migration strategy. */ public FilePath[] getModuleRoots() { AbstractBuild b = getBuildForDeprecatedMethods(); return b != null ? b.getModuleRoots() : null; } public int getQuietPeriod() { IntegerProjectProperty property = CascadingUtil.getIntegerProjectProperty(this, QUIET_PERIOD_PROPERTY_NAME); Integer value = property.getValue(); return property.getDefaultValue().equals(value) ? Hudson.getInstance().getQuietPeriod() : value; } /** * Sets the custom quiet period of this project, or revert to the global default if null is given. * * @param seconds quiet period * @throws IOException if any. */ public void setQuietPeriod(Integer seconds) throws IOException { CascadingUtil.getIntegerProjectProperty(this, QUIET_PERIOD_PROPERTY_NAME).setValue(seconds); save(); } public int getScmCheckoutRetryCount() { IntegerProjectProperty property = CascadingUtil.getIntegerProjectProperty(this, SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME); Integer value = property.getValue(); return property.getDefaultValue().equals(value) ? Hudson.getInstance().getScmCheckoutRetryCount() : value; } public void setScmCheckoutRetryCount(Integer retryCount) { CascadingUtil.getIntegerProjectProperty(this, SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME).setValue(retryCount); } /** * Sets scmCheckoutRetryCount, Uses {@link NumberUtils#isNumber(String)} for checking retryCount param. * If it is not valid number, null will be set. * * @param scmCheckoutRetryCount retry count. * @throws IOException if any. */ protected void setScmCheckoutRetryCount(String scmCheckoutRetryCount) throws IOException { Integer retryCount = null; if (NumberUtils.isNumber(scmCheckoutRetryCount)) { retryCount = NumberUtils.createInteger(scmCheckoutRetryCount); } setScmCheckoutRetryCount(retryCount); } /** * @return true if quiet period was configured. * @deprecated as of 2.1.2 * This method was used only on UI side. No longer required. */ // ugly name because of EL public boolean getHasCustomQuietPeriod() { return null != CascadingUtil.getIntegerProjectProperty(this, QUIET_PERIOD_PROPERTY_NAME).getValue(); } /** * Sets quietPeriod, Uses {@link NumberUtils#isNumber(String)} for checking seconds param. If seconds is not valid * number, null will be set. * * @param seconds quiet period. * @throws IOException if any. */ protected void setQuietPeriod(String seconds) throws IOException { Integer period = null; if (NumberUtils.isNumber(seconds)) { period = NumberUtils.createInteger(seconds); } setQuietPeriod(period); } /** * Checks whether scmRetryCount is configured * * @return true if yes, false - otherwise. * @deprecated as of 2.1.2 */ public boolean hasCustomScmCheckoutRetryCount(){ return null != CascadingUtil.getIntegerProjectProperty(this, SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME).getValue(); } @Override public boolean isBuildable() { return !isDisabled() && !isHoldOffBuildUntilSave(); } /** * Used in <tt>sidepanel.jelly</tt> to decide whether to display * the config/delete/build links. */ public boolean isConfigurable() { return true; } public boolean blockBuildWhenDownstreamBuilding() { return CascadingUtil.getBooleanProjectProperty(this, BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME).getValue(); } public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException { CascadingUtil.getBooleanProjectProperty(this, BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME).setValue(b); save(); } public boolean blockBuildWhenUpstreamBuilding() { return CascadingUtil.getBooleanProjectProperty(this, BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME).getValue(); } public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException { CascadingUtil.getBooleanProjectProperty(this, BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME).setValue(b); save(); } public boolean isDisabled() { return disabled; } /** * Validates the retry count Regex */ public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{ // retry count is optional so this is ok if(value == null || value.trim().equals("")) return FormValidation.ok(); if (!value.matches("[0-9]*")) { return FormValidation.error("Invalid retry count"); } return FormValidation.ok(); } /** * Marks the build as disabled. */ public void makeDisabled(boolean b) throws IOException { if(disabled==b) return; // noop this.disabled = b; if(b) Hudson.getInstance().getQueue().cancel(this); save(); } public void disable() throws IOException { makeDisabled(true); } public void enable() throws IOException { makeDisabled(false); } @Override public BallColor getIconColor() { if(isDisabled()) return BallColor.DISABLED; else return super.getIconColor(); } /** * effectively deprecated. Since using updateTransientActions correctly * under concurrent environment requires a lock that can too easily cause deadlocks. * * <p> * Override {@link #createTransientActions()} instead. */ protected void updateTransientActions() { transientActions = createTransientActions(); } protected List<Action> createTransientActions() { Vector<Action> ta = new Vector<Action>(); for (JobProperty<? super P> p : properties) ta.addAll(p.getJobActions((P)this)); for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all()) ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null return ta; } /** * Returns the live list of all {@link Publisher}s configured for this project. * * <p> * This method couldn't be called <tt>getPublishers()</tt> because existing methods * in sub-classes return different inconsistent types. */ public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList(); @Override public void addProperty(JobProperty<? super P> jobProp) throws IOException { super.addProperty(jobProp); updateTransientActions(); } public List<ProminentProjectAction> getProminentActions() { List<Action> a = getActions(); List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>(); for (Action action : a) { if(action instanceof ProminentProjectAction) pa.add((ProminentProjectAction) action); } return pa; } @Override public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException { super.doConfigSubmit(req,rsp); updateTransientActions(); Set<AbstractProject> upstream = Collections.emptySet(); if(req.getParameter("pseudoUpstreamTrigger")!=null) { upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class)); } // dependency setting might have been changed by the user, so rebuild. Hudson.getInstance().rebuildDependencyGraph(); // reflect the submission of the pseudo 'upstream build trriger'. // this needs to be done after we release the lock on 'this', // or otherwise we could dead-lock for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) { // Don't consider child projects such as MatrixConfiguration: if (!p.isConfigurable()) continue; boolean isUpstream = upstream.contains(p); synchronized(p) { // does 'p' include us in its BuildTrigger? DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList(); BuildTrigger trigger = pl.get(BuildTrigger.class); List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects(); if(isUpstream) { if(!newChildProjects.contains(this)) newChildProjects.add(this); } else { newChildProjects.remove(this); } if(newChildProjects.isEmpty()) { pl.remove(BuildTrigger.class); } else { // here, we just need to replace the old one with the new one, // but there was a regression (we don't know when it started) that put multiple BuildTriggers // into the list. // for us not to lose the data, we need to merge them all. List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class); BuildTrigger existing; switch (existingList.size()) { case 0: existing = null; break; case 1: existing = existingList.get(0); break; default: pl.removeAll(BuildTrigger.class); Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>(); for (BuildTrigger bt : existingList) combinedChildren.addAll(bt.getChildProjects()); existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold()); pl.add(existing); break; } if(existing!=null && existing.hasSame(newChildProjects)) continue; // no need to touch pl.replace(new BuildTrigger(newChildProjects, existing==null?Result.SUCCESS:existing.getThreshold())); } p.putAllProjectProperties(DescribableListUtil.convertToProjectProperties(pl, p), false); } } // notify the queue as the project might be now tied to different node Hudson.getInstance().getQueue().scheduleMaintenance(); // this is to reflect the upstream build adjustments done above Hudson.getInstance().rebuildDependencyGraph(); } /** * @deprecated * Use {@link #scheduleBuild(Cause)}. Since 1.283 */ public boolean scheduleBuild() { return scheduleBuild(new LegacyCodeCause()); } /** * @deprecated * Use {@link #scheduleBuild(int, Cause)}. Since 1.283 */ public boolean scheduleBuild(int quietPeriod) { return scheduleBuild(quietPeriod, new LegacyCodeCause()); } /** * Schedules a build of this project. * * @return * true if the project is actually added to the queue. * false if the queue contained it and therefore the add() * was noop */ public boolean scheduleBuild(Cause c) { return scheduleBuild(getQuietPeriod(), c); } public boolean scheduleBuild(int quietPeriod, Cause c) { return scheduleBuild(quietPeriod, c, new Action[0]); } /** * Schedules a build. * * Important: the actions should be persistable without outside references (e.g. don't store * references to this project). To provide parameters for a parameterized project, add a ParametersAction. If * no ParametersAction is provided for such a project, one will be created with the default parameter values. * * @param quietPeriod the quiet period to observer * @param c the cause for this build which should be recorded * @param actions a list of Actions that will be added to the build * @return whether the build was actually scheduled */ public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) { return scheduleBuild2(quietPeriod,c,actions)!=null; } /** * Schedules a build of this project, and returns a {@link Future} object * to wait for the completion of the build. * * @param actions * For the convenience of the caller, this array can contain null, and those will be silently ignored. */ public Future<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) { return scheduleBuild2(quietPeriod,c,Arrays.asList(actions)); } /** * Schedules a build of this project, and returns a {@link Future} object * to wait for the completion of the build. * * @param actions * For the convenience of the caller, this collection can contain null, and those will be silently ignored. * @since 1.383 */ public Future<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) { if (!isBuildable()) return null; List<Action> queueActions = new ArrayList<Action>(actions); if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) { queueActions.add(new ParametersAction(getDefaultParametersValues())); } if (c != null) { queueActions.add(new CauseAction(c)); } WaitingItem i = Hudson.getInstance().getQueue().schedule(this, quietPeriod, queueActions); if(i!=null) return (Future)i.getFuture(); return null; } private List<ParameterValue> getDefaultParametersValues() { ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class); ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>(); /* * This check is made ONLY if someone will call this method even if isParametrized() is false. */ if(paramDefProp == null) return defValues; /* Scan for all parameter with an associated default values */ for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions()) { ParameterValue defaultValue = paramDefinition.getDefaultParameterValue(); if(defaultValue != null) defValues.add(defaultValue); } return defValues; } /** * Schedules a build, and returns a {@link Future} object * to wait for the completion of the build. * * <p> * Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked * as deprecated. */ public Future<R> scheduleBuild2(int quietPeriod) { return scheduleBuild2(quietPeriod, new LegacyCodeCause()); } /** * Schedules a build of this project, and returns a {@link Future} object * to wait for the completion of the build. */ public Future<R> scheduleBuild2(int quietPeriod, Cause c) { return scheduleBuild2(quietPeriod, c, new Action[0]); } /** * Schedules a polling of this project. */ public boolean schedulePolling() { if(isDisabled()) return false; SCMTrigger scmt = getTrigger(SCMTrigger.class); if(scmt==null) return false; scmt.run(); return true; } /** * Returns true if the build is in the queue. */ @Override public boolean isInQueue() { return Hudson.getInstance().getQueue().contains(this); } @Override public Queue.Item getQueueItem() { return Hudson.getInstance().getQueue().getItem(this); } /** * @return name of jdk chosen for current project. Could taken from parent */ public String getJDKName() { return CascadingUtil.getStringProjectProperty(this, JDK_PROPERTY_NAME).getValue(); } /** * @return JDK that this project is configured with, or null. */ public JDK getJDK() { return Hudson.getInstance().getJDK(getJDKName()); } /** * Overwrites the JDK setting. */ public void setJDK(JDK jdk) throws IOException { setJDK(jdk.getName()); save(); } public void setJDK(String jdk) { CascadingUtil.getStringProjectProperty(this, JDK_PROPERTY_NAME).setValue(jdk); } public BuildAuthorizationToken getAuthToken() { return authToken; } @Override public SortedMap<Integer, ? extends R> _getRuns() { return builds.getView(); } @Override public void removeRun(R run) { this.builds.remove(run); } /** * Determines Class&lt;R>. */ protected abstract Class<R> getBuildClass(); // keep track of the previous time we started a build private transient long lastBuildStartTime; /** * Creates a new build of this project for immediate execution. */ protected synchronized R newBuild() throws IOException { // make sure we don't start two builds in the same second // so the build directories will be different too long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime; if (timeSinceLast < 1000) { try { Thread.sleep(1000 - timeSinceLast); } catch (InterruptedException e) { } } lastBuildStartTime = System.currentTimeMillis(); try { R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this); builds.put(lastBuild); return lastBuild; } catch (InstantiationException e) { throw new Error(e); } catch (IllegalAccessException e) { throw new Error(e); } catch (InvocationTargetException e) { throw handleInvocationTargetException(e); } catch (NoSuchMethodException e) { throw new Error(e); } } private IOException handleInvocationTargetException(InvocationTargetException e) { Throwable t = e.getTargetException(); if(t instanceof Error) throw (Error)t; if(t instanceof RuntimeException) throw (RuntimeException)t; if(t instanceof IOException) return (IOException)t; throw new Error(t); } /** * Loads an existing build record from disk. */ protected R loadBuild(File dir) throws IOException { try { return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir); } catch (InstantiationException e) { throw new Error(e); } catch (IllegalAccessException e) { throw new Error(e); } catch (InvocationTargetException e) { throw handleInvocationTargetException(e); } catch (NoSuchMethodException e) { throw new Error(e); } } /** * {@inheritDoc} * * <p> * Note that this method returns a read-only view of {@link Action}s. * {@link BuildStep}s and others who want to add a project action * should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}. * * @see TransientProjectActionFactory */ @Override public synchronized List<Action> getActions() { // add all the transient actions, too List<Action> actions = new Vector<Action>(super.getActions()); actions.addAll(transientActions); // return the read only list to cause a failure on plugins who try to add an action here return Collections.unmodifiableList(actions); } /** * Gets the {@link Node} where this project was last built on. * * @return * null if no information is available (for example, * if no build was done yet.) */ public Node getLastBuiltOn() { // where was it built on? AbstractBuild b = getLastBuild(); if(b==null) return null; else return b.getBuiltOn(); } public Object getSameNodeConstraint() { return this; // in this way, any member that wants to run with the main guy can nominate the project itself } public final Task getOwnerTask() { return this; } /** * {@inheritDoc} * * <p> * A project must be blocked if its own previous build is in progress, * or if the blockBuildWhenUpstreamBuilding option is true and an upstream * project is building, but derived classes can also check other conditions. */ public boolean isBuildBlocked() { return getCauseOfBlockage()!=null; } public String getWhyBlocked() { CauseOfBlockage cb = getCauseOfBlockage(); return cb!=null ? cb.getShortDescription() : null; } /** * Blocked because the previous build is already in progress. */ public static class BecauseOfBuildInProgress extends CauseOfBlockage { private final AbstractBuild<?,?> build; public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) { this.build = build; } @Override public String getShortDescription() { Executor e = build.getExecutor(); String eta = ""; if (e != null) eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime()); int lbn = build.getNumber(); return Messages.AbstractProject_BuildInProgress(lbn, eta); } } /** * Because the downstream build is in progress, and we are configured to wait for that. */ public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage { //TODO: review and check whether we can do it private public final AbstractProject<?,?> up; public AbstractProject getUp() { return up; } public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) { this.up = up; } @Override public String getShortDescription() { return Messages.AbstractProject_DownstreamBuildInProgress(up.getName()); } } /** * Because the upstream build is in progress, and we are configured to wait for that. */ public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage { //TODO: review and check whether we can do it private public final AbstractProject<?,?> up; public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) { this.up = up; } public AbstractProject getUp() { return up; } @Override public String getShortDescription() { return Messages.AbstractProject_UpstreamBuildInProgress(up.getName()); } } public CauseOfBlockage getCauseOfBlockage() { if (isBuilding() && !isConcurrentBuild()) return new BecauseOfBuildInProgress(getLastBuild()); if (blockBuildWhenDownstreamBuilding()) { AbstractProject<?,?> bup = getBuildingDownstream(); if (bup!=null) return new BecauseOfDownstreamBuildInProgress(bup); } else if (blockBuildWhenUpstreamBuilding()) { AbstractProject<?,?> bup = getBuildingUpstream(); if (bup!=null) return new BecauseOfUpstreamBuildInProgress(bup); } return null; } /** * Returns the project if any of the downstream project (or itself) is either * building or is in the queue. * <p> * This means eventually there will be an automatic triggering of * the given project (provided that all builds went smoothly.) */ protected AbstractProject getBuildingDownstream() { DependencyGraph graph = Hudson.getInstance().getDependencyGraph(); Set<AbstractProject> tups = graph.getTransitiveDownstream(this); tups.add(this); for (AbstractProject tup : tups) { if(tup!=this && (tup.isBuilding() || tup.isInQueue())) return tup; } return null; } /** * Returns the project if any of the upstream project (or itself) is either * building or is in the queue. * <p> * This means eventually there will be an automatic triggering of * the given project (provided that all builds went smoothly.) */ protected AbstractProject getBuildingUpstream() { DependencyGraph graph = Hudson.getInstance().getDependencyGraph(); Set<AbstractProject> tups = graph.getTransitiveUpstream(this); tups.add(this); for (AbstractProject tup : tups) { if(tup!=this && (tup.isBuilding() || tup.isInQueue())) return tup; } return null; } public List<SubTask> getSubTasks() { List<SubTask> r = new ArrayList<SubTask>(); r.add(this); for (SubTaskContributor euc : SubTaskContributor.all()) r.addAll(euc.forProject(this)); for (JobProperty<? super P> p : properties) r.addAll(p.getSubTasks()); return r; } public R createExecutable() throws IOException { if(isDisabled()) return null; return newBuild(); } public void checkAbortPermission() { checkPermission(AbstractProject.ABORT); } public boolean hasAbortPermission() { return hasPermission(AbstractProject.ABORT); } /** * Gets the {@link Resource} that represents the workspace of this project. * Useful for locking and mutual exclusion control. * * @deprecated as of 1.319 * Projects no longer have a fixed workspace, ands builds will find an available workspace via * {@link WorkspaceList} for each build (furthermore, that happens after a build is started.) * So a {@link Resource} representation for a workspace at the project level no longer makes sense. * * <p> * If you need to lock a workspace while you do some computation, see the source code of * {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}. */ public Resource getWorkspaceResource() { return new Resource(getFullDisplayName()+" workspace"); } /** * List of necessary resources to perform the build of this project. */ public ResourceList getResourceList() { final Set<ResourceActivity> resourceActivities = getResourceActivities(); final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size()); for (ResourceActivity activity : resourceActivities) { if (activity != this && activity != null) { // defensive infinite recursion and null check resourceLists.add(activity.getResourceList()); } } return ResourceList.union(resourceLists); } /** * Set of child resource activities of the build of this project (override in child projects). * @return The set of child resource activities of the build of this project. */ protected Set<ResourceActivity> getResourceActivities() { return Collections.emptySet(); } public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException { SCM scm = getScm(); if(scm==null) return true; // no SCM FilePath workspace = build.getWorkspace(); workspace.mkdirs(); boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile); calcPollingBaseline(build, launcher, listener); return r; } /** * Pushes the baseline up to the newly checked out revision. */ private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { SCMRevisionState baseline = build.getAction(SCMRevisionState.class); if (baseline==null) { try { baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener); } catch (AbstractMethodError e) { baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling } if (baseline!=null) build.addAction(baseline); } pollingBaseline = baseline; } /** * For reasons I don't understand, if I inline this method, AbstractMethodError escapes try/catch block. */ private SCMRevisionState safeCalcRevisionsFromBuild(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException { return getScm()._calcRevisionsFromBuild(build, launcher, listener); } /** * Checks if there's any update in SCM, and returns true if any is found. * * @deprecated as of 1.346 * Use {@link #poll(TaskListener)} instead. */ public boolean pollSCMChanges( TaskListener listener ) { return poll(listener).hasChanges(); } /** * Checks if there's any update in SCM, and returns true if any is found. * * <p> * The implementation is responsible for ensuring mutual exclusion between polling and builds * if necessary. * * @since 1.345 */ public PollingResult poll( TaskListener listener ) { SCM scm = getScm(); if (scm==null) { listener.getLogger().println(Messages.AbstractProject_NoSCM()); return NO_CHANGES; } if (isDisabled()) { listener.getLogger().println(Messages.AbstractProject_Disabled()); return NO_CHANGES; } R lb = getLastBuild(); if (lb==null) { listener.getLogger().println(Messages.AbstractProject_NoBuilds()); return isInQueue() ? NO_CHANGES : BUILD_NOW; } if (pollingBaseline==null) { R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this for (R r=lb; r!=null; r=r.getPreviousBuild()) { SCMRevisionState s = r.getAction(SCMRevisionState.class); if (s!=null) { pollingBaseline = s; break; } if (r==success) break; // searched far enough } // NOTE-NO-BASELINE: // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline // as action, so we need to compute it. This happens later. } try { if (scm.requiresWorkspaceForPolling()) { // lock the workspace of the last build FilePath ws=lb.getWorkspace(); if (ws==null || !ws.exists()) { // workspace offline. build now, or nothing will ever be built Label label = getAssignedLabel(); if (label != null && label.isSelfLabel()) { // if the build is fixed on a node, then attempting a build will do us // no good. We should just wait for the slave to come back. listener.getLogger().println(Messages.AbstractProject_NoWorkspace()); return NO_CHANGES; } listener.getLogger().println( ws==null ? Messages.AbstractProject_WorkspaceOffline() : Messages.AbstractProject_NoWorkspace()); if (isInQueue()) { listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace()); return NO_CHANGES; } else { listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace()); return BUILD_NOW; } } else { - WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList(); + Node node = lb.getBuiltOn(); + if (node == null || node.toComputer() == null) { + LOGGER.log(Level.FINE, "Node on which this job previously was built is not available now, build is started on an available node"); + return isInQueue() ? NO_CHANGES : BUILD_NOW; + } + WorkspaceList l = node.toComputer().getWorkspaceList(); // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace. // this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319. // // OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace, // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces) // by having multiple workspaces WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild); Launcher launcher = ws.createLauncher(listener); try { LOGGER.fine("Polling SCM changes of " + getName()); if (pollingBaseline==null) // see NOTE-NO-BASELINE above calcPollingBaseline(lb,launcher,listener); PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline); pollingBaseline = r.remote; return r; } finally { lease.release(); } } } else { // polling without workspace LOGGER.fine("Polling SCM changes of " + getName()); if (pollingBaseline==null) // see NOTE-NO-BASELINE above calcPollingBaseline(lb,null,listener); PollingResult r = scm.poll(this, null, null, listener, pollingBaseline); pollingBaseline = r.remote; return r; } } catch (AbortException e) { listener.getLogger().println(e.getMessage()); listener.fatalError(Messages.AbstractProject_Aborted()); LOGGER.log(Level.FINE, "Polling "+this+" aborted",e); return NO_CHANGES; } catch (IOException e) { e.printStackTrace(listener.fatalError(e.getMessage())); return NO_CHANGES; } catch (InterruptedException e) { e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted())); return NO_CHANGES; } } /** * Returns true if this user has made a commit to this project. * * @since 1.191 */ public boolean hasParticipant(User user) { for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild()) if(build.hasParticipant(user)) return true; return false; } @Exported public SCM getScm() { return (SCM) getProperty(SCM_PROPERTY_NAME, SCMProjectProperty.class).getValue(); } @SuppressWarnings("unchecked") public void setScm(SCM scm) throws IOException { getProperty(SCM_PROPERTY_NAME, SCMProjectProperty.class).setValue(scm); save(); } /** * Adds a new {@link Trigger} to this {@link Project} if not active yet. */ @SuppressWarnings("unchecked") public void addTrigger(Trigger<?> trigger) throws IOException { CascadingUtil.getTriggerProjectProperty(this, trigger.getDescriptor().getJsonSafeClassName()).setValue(trigger); } public void removeTrigger(TriggerDescriptor trigger) throws IOException { CascadingUtil.getTriggerProjectProperty(this, trigger.getJsonSafeClassName()).setValue(null); } protected final synchronized <T extends Describable<T>> void addToList( T item, List<T> collection ) throws IOException { for( int i=0; i<collection.size(); i++ ) { if(collection.get(i).getDescriptor()==item.getDescriptor()) { // replace collection.set(i, item); save(); return; } } // add collection.add(item); save(); updateTransientActions(); } protected final synchronized <T extends Describable<T>> void removeFromList(Descriptor<T> item, List<T> collection) throws IOException { for( int i=0; i< collection.size(); i++ ) { if(collection.get(i).getDescriptor()==item) { // found it collection.remove(i); save(); updateTransientActions(); return; } } } public synchronized Map<TriggerDescriptor,Trigger> getTriggers() { return (Map)Descriptor.toMap(getTriggerDescribableList()); } /** * @return list of {@link Trigger} elements. */ public List<Trigger<?>> getTriggersList() { return getTriggerDescribableList().toList(); } /** * @return describable list of trigger elements. */ public DescribableList<Trigger<?>, TriggerDescriptor> getTriggerDescribableList() { return DescribableListUtil.convertToDescribableList(Trigger.for_(this), this, TriggerProjectProperty.class); } /** * Gets the specific trigger, or null if the propert is not configured for this job. */ public <T extends Trigger> T getTrigger(Class<T> clazz) { for (Trigger p : getTriggersList()) { if(clazz.isInstance(p)) return clazz.cast(p); } return null; } public void setTriggers(List<Trigger<?>> triggerList) { for (Trigger trigger : triggerList) { CascadingUtil.getTriggerProjectProperty(this, trigger.getDescriptor().getJsonSafeClassName()).setValue(trigger); } } // // // fingerprint related // // /** * True if the builds of this project produces {@link Fingerprint} records. */ public abstract boolean isFingerprintConfigured(); /** * Gets the other {@link AbstractProject}s that should be built * when a build of this project is completed. */ @Exported public final List<AbstractProject> getDownstreamProjects() { return Hudson.getInstance().getDependencyGraph().getDownstream(this); } @Exported public final List<AbstractProject> getUpstreamProjects() { return Hudson.getInstance().getDependencyGraph().getUpstream(this); } /** * Returns only those upstream projects that defines {@link BuildTrigger} to this project. * This is a subset of {@link #getUpstreamProjects()} * * @return A List of upstream projects that has a {@link BuildTrigger} to this project. */ public final List<AbstractProject> getBuildTriggerUpstreamProjects() { ArrayList<AbstractProject> result = new ArrayList<AbstractProject>(); for (AbstractProject<?,?> ap : getUpstreamProjects()) { BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class); if (buildTrigger != null) if (buildTrigger.getChildProjects().contains(this)) result.add(ap); } return result; } /** * Gets all the upstream projects including transitive upstream projects. * * @since 1.138 */ public final Set<AbstractProject> getTransitiveUpstreamProjects() { return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this); } /** * Gets all the downstream projects including transitive downstream projects. * * @since 1.138 */ public final Set<AbstractProject> getTransitiveDownstreamProjects() { return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this); } /** * Gets the dependency relationship map between this project (as the source) * and that project (as the sink.) * * @return * can be empty but not null. build number of this project to the build * numbers of that project. */ public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) { TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR); checkAndRecord(that, r, this.getBuilds()); // checkAndRecord(that, r, that.getBuilds()); return r; } /** * Helper method for getDownstreamRelationship. * * For each given build, find the build number range of the given project and put that into the map. */ private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) { for (R build : builds) { RangeSet rs = build.getDownstreamRelationship(that); if(rs==null || rs.isEmpty()) continue; int n = build.getNumber(); RangeSet value = r.get(n); if(value==null) r.put(n,rs); else value.add(rs); } } /** * Builds the dependency graph. * @see DependencyGraph */ protected abstract void buildDependencyGraph(DependencyGraph graph); @Override protected SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = super.makeSearchIndex(); if(isBuildable() && hasPermission(Hudson.ADMINISTER)) sib.add("build","build"); return sib; } @Override protected HistoryWidget createHistoryWidget() { return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER); } public boolean isParameterized() { return getProperty(ParametersDefinitionProperty.class) != null; } // // // actions // // /** * Schedules a new build command. */ public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { BuildAuthorizationToken.checkPermission(this, authToken, req, rsp); // if a build is parameterized, let that take over ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class); if (pp != null) { pp._doBuild(req,rsp); return; } if (!isBuildable()) throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable")); Hudson.getInstance().getQueue().schedule(this, getDelay(req), getBuildCause(req)); rsp.forwardToPreviousPage(req); } /** * Computes the build cause, using RemoteCause or UserCause as appropriate. */ /*package*/ CauseAction getBuildCause(StaplerRequest req) { Cause cause; if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) { // Optional additional cause text when starting via token String causeText = req.getParameter("cause"); cause = new RemoteCause(req.getRemoteAddr(), causeText); } else { cause = new UserCause(); } return new CauseAction(cause); } /** * Computes the delay by taking the default value and the override in the request parameter into the account. */ public int getDelay(StaplerRequest req) throws ServletException { String delay = req.getParameter("delay"); if (delay==null) return getQuietPeriod(); try { // TODO: more unit handling if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3); if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4); return Integer.parseInt(delay); } catch (NumberFormatException e) { throw new ServletException("Invalid delay parameter value: "+delay); } } /** * Supports build trigger with parameters via an HTTP GET or POST. * Currently only String parameters are supported. */ public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { BuildAuthorizationToken.checkPermission(this, authToken, req, rsp); ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class); if (pp != null) { pp.buildWithParameters(req,rsp); } else { throw new IllegalStateException("This build is not parameterized!"); } } /** * Schedules a new SCM polling command. */ public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { BuildAuthorizationToken.checkPermission(this, authToken, req, rsp); schedulePolling(); rsp.forwardToPreviousPage(req); } /** * Cancels a scheduled build. */ public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { checkPermission(BUILD); Hudson.getInstance().getQueue().cancel(this); rsp.forwardToPreviousPage(req); } @Override protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { super.submit(req,rsp); makeDisabled(null != req.getParameter("disable")); setCascadingProjectName(StringUtils.trimToNull(req.getParameter("cascadingProjectName"))); setJDK(req.getParameter("jdk")); setQuietPeriod(null != req.getParameter(HAS_QUIET_PERIOD_PROPERTY_NAME) ? req.getParameter("quiet_period") : null); setScmCheckoutRetryCount(null != req.getParameter(HAS_SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME) ? req.getParameter("scmCheckoutRetryCount") : null); setBlockBuildWhenDownstreamBuilding(null != req.getParameter("blockBuildWhenDownstreamBuilding")); setBlockBuildWhenUpstreamBuilding(null != req.getParameter("blockBuildWhenUpstreamBuilding")); if (req.getParameter("hasSlaveAffinity") != null) { // New logic for handling whether this choice came from the dropdown or textfield. if ("basic".equals(req.getParameter("affinityChooser"))) { assignedNode = Util.fixEmptyAndTrim(req.getParameter("slave")); advancedAffinityChooser = false; } else { assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString")); advancedAffinityChooser = true; } } else { assignedNode = null; advancedAffinityChooser = false; } setCleanWorkspaceRequired(null != req.getParameter("cleanWorkspaceRequired")); canRoam = assignedNode==null; setConcurrentBuild(req.getSubmittedForm().has("concurrentBuild")); authToken = BuildAuthorizationToken.create(req); setScm(SCMS.parseSCM(req,this)); buildTriggers(req, req.getSubmittedForm(), Trigger.for_(this)); } /** * @deprecated * As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead. */ protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException { return buildDescribable(req,descriptors); } protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors) throws FormException, ServletException { JSONObject data = req.getSubmittedForm(); List<T> r = new Vector<T>(); for (Descriptor<T> d : descriptors) { String safeName = d.getJsonSafeClassName(); if (req.getParameter(safeName) != null) { T instance = d.newInstance(req, data.getJSONObject(safeName)); r.add(instance); } } return r; } protected void buildTriggers(StaplerRequest req, JSONObject json, List<TriggerDescriptor> descriptors) throws FormException { for (TriggerDescriptor d : descriptors) { String propertyName = d.getJsonSafeClassName(); CascadingUtil.setChildrenTrigger(this, d, propertyName, req, json); } } /** * Serves the workspace files. */ public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { checkPermission(AbstractProject.WORKSPACE); FilePath ws = getSomeWorkspace(); if ((ws == null) || (!ws.exists())) { // if there's no workspace, report a nice error message rsp.setStatus(HttpServletResponse.SC_NOT_FOUND); req.getView(this,"noWorkspace.jelly").forward(req,rsp); return null; } else { return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true); } } /** * Wipes out the workspace. */ public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException { if (cleanWorkspace()){ return new HttpRedirect("."); }else{ return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly"); } } public boolean cleanWorkspace() throws IOException, InterruptedException{ checkPermission(BUILD); R b = getSomeBuildWithWorkspace(); FilePath ws = b != null ? b.getWorkspace() : null; if (ws != null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) { ws.deleteRecursive(); return true; } else{ // If we get here, that means the SCM blocked the workspace deletion. return false; } } @CLIMethod(name="disable-job") public HttpResponse doDisable() throws IOException, ServletException { requirePOST(); checkPermission(CONFIGURE); makeDisabled(true); return new HttpRedirect("."); } @CLIMethod(name="enable-job") public HttpResponse doEnable() throws IOException, ServletException { requirePOST(); checkPermission(CONFIGURE); makeDisabled(false); return new HttpRedirect("."); } /** * RSS feed for changes in this project. */ public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { class FeedItem { ChangeLogSet.Entry e; int idx; public FeedItem(Entry e, int idx) { this.e = e; this.idx = idx; } AbstractBuild<?,?> getBuild() { return e.getParent().build; } } List<FeedItem> entries = new ArrayList<FeedItem>(); for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) { int idx=0; for( ChangeLogSet.Entry e : r.getChangeSet()) entries.add(new FeedItem(e,idx++)); } RSS.forwardToRss( getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes", getUrl()+"changes", entries, new FeedAdapter<FeedItem>() { public String getEntryTitle(FeedItem item) { return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")"; } public String getEntryUrl(FeedItem item) { return item.getBuild().getUrl()+"changes#detail"+item.idx; } public String getEntryID(FeedItem item) { return getEntryUrl(item); } public String getEntryDescription(FeedItem item) { StringBuilder buf = new StringBuilder(); for(String path : item.e.getAffectedPaths()) buf.append(path).append('\n'); return buf.toString(); } public Calendar getEntryTimestamp(FeedItem item) { return item.getBuild().getTimestamp(); } public String getEntryAuthor(FeedItem entry) { return Mailer.descriptor().getAdminAddress(); } }, req, rsp ); } /** * {@link AbstractProject} subtypes should implement this base class as a descriptor. * * @since 1.294 */ public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor { /** * {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s * from showing up on their configuration screen. This is often useful when you are building * a workflow/company specific project type, where you want to limit the number of choices * given to the users. * * <p> * Some {@link Descriptor}s define their own schemes for controlling applicability * (such as {@link BuildStepDescriptor#isApplicable(Class)}), * This method works like AND in conjunction with them; * Both this method and that method need to return true in order for a given {@link Descriptor} * to show up for the given {@link Project}. * * <p> * The default implementation returns true for everything. * * @see BuildStepDescriptor#isApplicable(Class) * @see BuildWrapperDescriptor#isApplicable(AbstractProject) * @see TriggerDescriptor#isApplicable(Item) */ @Override public boolean isApplicable(Descriptor descriptor) { return true; } public FormValidation doCheckAssignedLabelString(@QueryParameter String value) { if (Util.fixEmpty(value)==null) return FormValidation.ok(); // nothing typed yet try { Label.parseExpression(value); } catch (ANTLRException e) { return FormValidation.error(e, Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage())); } // TODO: if there's an atom in the expression that is empty, report it if (Hudson.getInstance().getLabel(value).isEmpty()) return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch()); return FormValidation.ok(); } public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) { AutoCompletionCandidates c = new AutoCompletionCandidates(); Set<Label> labels = Hudson.getInstance().getLabels(); List<String> queries = new AutoCompleteSeeder(value).getSeeds(); for (String term : queries) { for (Label l : labels) { if (l.getName().startsWith(term)) { c.add(l.getName()); } } } return c; } } /** * Finds a {@link AbstractProject} that has the name closest to the given name. */ public static AbstractProject findNearest(String name) { List<AbstractProject> projects = Hudson.getInstance().getItems(AbstractProject.class); String[] names = new String[projects.size()]; for( int i=0; i<projects.size(); i++ ) names[i] = projects.get(i).getName(); String nearest = EditDistance.findNearest(name, names); return (AbstractProject)Hudson.getInstance().getItem(nearest); } private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2-o1; } }; private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName()); /** * Permission to abort a build. For now, let's make it the same as {@link #BUILD} */ public static final Permission ABORT = BUILD; /** * Used for CLI binding. */ @CLIResolver public static AbstractProject resolveForCLI( @Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException { AbstractProject item = Hudson.getInstance().getItemByFullName(name, AbstractProject.class); if (item==null) throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName())); return item; } }
true
true
public PollingResult poll( TaskListener listener ) { SCM scm = getScm(); if (scm==null) { listener.getLogger().println(Messages.AbstractProject_NoSCM()); return NO_CHANGES; } if (isDisabled()) { listener.getLogger().println(Messages.AbstractProject_Disabled()); return NO_CHANGES; } R lb = getLastBuild(); if (lb==null) { listener.getLogger().println(Messages.AbstractProject_NoBuilds()); return isInQueue() ? NO_CHANGES : BUILD_NOW; } if (pollingBaseline==null) { R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this for (R r=lb; r!=null; r=r.getPreviousBuild()) { SCMRevisionState s = r.getAction(SCMRevisionState.class); if (s!=null) { pollingBaseline = s; break; } if (r==success) break; // searched far enough } // NOTE-NO-BASELINE: // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline // as action, so we need to compute it. This happens later. } try { if (scm.requiresWorkspaceForPolling()) { // lock the workspace of the last build FilePath ws=lb.getWorkspace(); if (ws==null || !ws.exists()) { // workspace offline. build now, or nothing will ever be built Label label = getAssignedLabel(); if (label != null && label.isSelfLabel()) { // if the build is fixed on a node, then attempting a build will do us // no good. We should just wait for the slave to come back. listener.getLogger().println(Messages.AbstractProject_NoWorkspace()); return NO_CHANGES; } listener.getLogger().println( ws==null ? Messages.AbstractProject_WorkspaceOffline() : Messages.AbstractProject_NoWorkspace()); if (isInQueue()) { listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace()); return NO_CHANGES; } else { listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace()); return BUILD_NOW; } } else { WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList(); // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace. // this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319. // // OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace, // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces) // by having multiple workspaces WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild); Launcher launcher = ws.createLauncher(listener); try { LOGGER.fine("Polling SCM changes of " + getName()); if (pollingBaseline==null) // see NOTE-NO-BASELINE above calcPollingBaseline(lb,launcher,listener); PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline); pollingBaseline = r.remote; return r; } finally { lease.release(); } } } else { // polling without workspace LOGGER.fine("Polling SCM changes of " + getName()); if (pollingBaseline==null) // see NOTE-NO-BASELINE above calcPollingBaseline(lb,null,listener); PollingResult r = scm.poll(this, null, null, listener, pollingBaseline); pollingBaseline = r.remote; return r; } } catch (AbortException e) { listener.getLogger().println(e.getMessage()); listener.fatalError(Messages.AbstractProject_Aborted()); LOGGER.log(Level.FINE, "Polling "+this+" aborted",e); return NO_CHANGES; } catch (IOException e) { e.printStackTrace(listener.fatalError(e.getMessage())); return NO_CHANGES; } catch (InterruptedException e) { e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted())); return NO_CHANGES; } }
public PollingResult poll( TaskListener listener ) { SCM scm = getScm(); if (scm==null) { listener.getLogger().println(Messages.AbstractProject_NoSCM()); return NO_CHANGES; } if (isDisabled()) { listener.getLogger().println(Messages.AbstractProject_Disabled()); return NO_CHANGES; } R lb = getLastBuild(); if (lb==null) { listener.getLogger().println(Messages.AbstractProject_NoBuilds()); return isInQueue() ? NO_CHANGES : BUILD_NOW; } if (pollingBaseline==null) { R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this for (R r=lb; r!=null; r=r.getPreviousBuild()) { SCMRevisionState s = r.getAction(SCMRevisionState.class); if (s!=null) { pollingBaseline = s; break; } if (r==success) break; // searched far enough } // NOTE-NO-BASELINE: // if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline // as action, so we need to compute it. This happens later. } try { if (scm.requiresWorkspaceForPolling()) { // lock the workspace of the last build FilePath ws=lb.getWorkspace(); if (ws==null || !ws.exists()) { // workspace offline. build now, or nothing will ever be built Label label = getAssignedLabel(); if (label != null && label.isSelfLabel()) { // if the build is fixed on a node, then attempting a build will do us // no good. We should just wait for the slave to come back. listener.getLogger().println(Messages.AbstractProject_NoWorkspace()); return NO_CHANGES; } listener.getLogger().println( ws==null ? Messages.AbstractProject_WorkspaceOffline() : Messages.AbstractProject_NoWorkspace()); if (isInQueue()) { listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace()); return NO_CHANGES; } else { listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace()); return BUILD_NOW; } } else { Node node = lb.getBuiltOn(); if (node == null || node.toComputer() == null) { LOGGER.log(Level.FINE, "Node on which this job previously was built is not available now, build is started on an available node"); return isInQueue() ? NO_CHANGES : BUILD_NOW; } WorkspaceList l = node.toComputer().getWorkspaceList(); // if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace. // this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319. // // OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace, // so better throughput is achieved over time (modulo the initial cost of creating that many workspaces) // by having multiple workspaces WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild); Launcher launcher = ws.createLauncher(listener); try { LOGGER.fine("Polling SCM changes of " + getName()); if (pollingBaseline==null) // see NOTE-NO-BASELINE above calcPollingBaseline(lb,launcher,listener); PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline); pollingBaseline = r.remote; return r; } finally { lease.release(); } } } else { // polling without workspace LOGGER.fine("Polling SCM changes of " + getName()); if (pollingBaseline==null) // see NOTE-NO-BASELINE above calcPollingBaseline(lb,null,listener); PollingResult r = scm.poll(this, null, null, listener, pollingBaseline); pollingBaseline = r.remote; return r; } } catch (AbortException e) { listener.getLogger().println(e.getMessage()); listener.fatalError(Messages.AbstractProject_Aborted()); LOGGER.log(Level.FINE, "Polling "+this+" aborted",e); return NO_CHANGES; } catch (IOException e) { e.printStackTrace(listener.fatalError(e.getMessage())); return NO_CHANGES; } catch (InterruptedException e) { e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted())); return NO_CHANGES; } }
diff --git a/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ModuleView.java b/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ModuleView.java index 4185aaae8..2c553d416 100644 --- a/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ModuleView.java +++ b/org.eclipse.riena.navigation.ui.swt/src/org/eclipse/riena/navigation/ui/swt/views/ModuleView.java @@ -1,759 +1,761 @@ /******************************************************************************* * Copyright (c) 2007, 2009 compeople AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.navigation.ui.swt.views; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.riena.core.util.ListenerList; import org.eclipse.riena.navigation.IModuleNode; import org.eclipse.riena.navigation.INavigationNode; import org.eclipse.riena.navigation.ISubModuleNode; import org.eclipse.riena.navigation.listener.ModuleNodeListener; import org.eclipse.riena.navigation.listener.NavigationTreeObserver; import org.eclipse.riena.navigation.listener.SubModuleNodeListener; import org.eclipse.riena.navigation.model.ModuleNode; import org.eclipse.riena.navigation.model.SubModuleNode; import org.eclipse.riena.navigation.ui.swt.binding.InjectSwtViewBindingDelegate; import org.eclipse.riena.navigation.ui.swt.component.ModuleToolTip; import org.eclipse.riena.navigation.ui.swt.component.SubModuleToolTip; import org.eclipse.riena.navigation.ui.swt.lnf.renderer.ModuleGroupRenderer; import org.eclipse.riena.navigation.ui.swt.lnf.renderer.SubModuleTreeItemMarkerRenderer; import org.eclipse.riena.ui.filter.IUIFilter; import org.eclipse.riena.ui.ridgets.controller.IController; import org.eclipse.riena.ui.ridgets.swt.uibinding.AbstractViewBindingDelegate; import org.eclipse.riena.ui.swt.ModuleTitleBar; import org.eclipse.riena.ui.swt.lnf.LnFUpdater; import org.eclipse.riena.ui.swt.lnf.LnfKeyConstants; import org.eclipse.riena.ui.swt.lnf.LnfManager; import org.eclipse.riena.ui.swt.lnf.rienadefault.RienaDefaultLnf; import org.eclipse.riena.ui.swt.utils.SwtUtilities; /** * View of a module. */ public class ModuleView implements INavigationNodeView<SWTModuleController, ModuleNode> { private static final String WINDOW_RIDGET = "windowRidget"; //$NON-NLS-1$ private static final LnFUpdater LNF_UPDATER = new LnFUpdater(); private AbstractViewBindingDelegate binding; private Composite parent; private Composite body; private Tree subModuleTree; private ModuleNode moduleNode; private boolean pressed; private boolean hover; private ModuleTitleBar title; private NavigationTreeObserver navigationTreeObserver; private ListenerList<IComponentUpdateListener> updateListeners; //performance tweaking private boolean cachedActivityState = true; private boolean treeDirty = true; public ModuleView(Composite parent) { this.parent = parent; binding = createBinding(); updateListeners = new ListenerList<IComponentUpdateListener>(IComponentUpdateListener.class); buildView(); } /** * Creates a delegate for the binding of view and controller. * * @return delegate for binding */ protected AbstractViewBindingDelegate createBinding() { return new InjectSwtViewBindingDelegate(); } /** * Builds the composite and the tree of the module view. */ private void buildView() { title = new ModuleTitleBar(getParent(), SWT.NONE); binding.addUIControl(title, WINDOW_RIDGET); layoutTitle(); new ModuleToolTip(title); body = new Composite(getParent(), SWT.DOUBLE_BUFFERED); updateModuleView(); createBodyContent(body); LNF_UPDATER.updateUIControls(body); } private Composite getBody() { return body; } /** * Creates the content of the module body (default: the tree for the * sub-modules). * * @param parent * - body of the module */ protected void createBodyContent(Composite parent) { parent.setLayout(new FormLayout()); subModuleTree = new Tree(parent, SWT.NO_SCROLL | SWT.DOUBLE_BUFFERED); subModuleTree.setLinesVisible(false); RienaDefaultLnf lnf = LnfManager.getLnf(); subModuleTree.setFont(lnf.getFont(LnfKeyConstants.SUB_MODULE_ITEM_FONT)); binding.addUIControl(subModuleTree, "tree"); //$NON-NLS-1$ FormData formData = new FormData(); formData.top = new FormAttachment(0, 0); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.bottom = new FormAttachment(100, 0); subModuleTree.setLayoutData(formData); addListeners(); new SubModuleToolTip(subModuleTree); setTreeBackGround(); } /** * Clips (if necessary) the text of the given tree item and all child items. * * @param gc * @param item * - tree item * @return true: some text was clipped; false: no text was clipped */ private boolean clipSubModuleTexts(GC gc, TreeItem item) { boolean clipped = clipSubModuleText(gc, item); TreeItem[] items = item.getItems(); for (TreeItem childItem : items) { if (clipSubModuleTexts(gc, childItem)) { clipped = true; } } return clipped; } /** * Clips (if necessary) the text of the given tree item. * * @param gc * @param item * - tree item * @return true: text was clipped; false: text was not clipped */ private boolean clipSubModuleText(GC gc, TreeItem item) { boolean clipped = false; Rectangle treeBounds = getTree().getBounds(); Rectangle itemBounds = item.getBounds(); int maxWidth = treeBounds.width - itemBounds.x - 5; String longText = getItemText(item); if (longText != null) { String text = SwtUtilities.clipText(gc, longText, maxWidth); item.setText(text); clipped = !longText.equals(text); } return clipped; } private String getItemText(TreeItem item) { INavigationNode<?> subModule = (INavigationNode<?>) item.getData(); if (subModule != null) { return subModule.getLabel(); } else { return item.getText(); } } /** * Clips (if necessary) the text of the tree items and hides the scroll * bars. * * @param gc */ private void onTreePaint(GC gc) { TreeItem[] items = getTree().getItems(); for (TreeItem item : items) { clipSubModuleTexts(gc, item); } } protected void resize() { fireUpdated(null); } /** * Adds listeners to the sub-module tree. */ private void addListeners() { getTree().addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { treeDirty = true; TreeItem[] selection = getTree().getSelection(); - if (selection[0].getData() instanceof ISubModuleNode) { + if ((selection.length > 0) && (selection[0].getData() instanceof ISubModuleNode)) { ISubModuleNode activeSubModule = (ISubModuleNode) selection[0].getData(); - activeSubModule.activate(); + if (activeSubModule.getParent().isActivated()) { + activeSubModule.activate(); + } } resize(); } }); getTree().addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { onTreePaint(event.gc); } }); getTree().addListener(SWT.Expand, new Listener() { public void handleEvent(Event event) { treeDirty = true; handleExpandCollapse(event, true); } }); getTree().addListener(SWT.Collapse, new Listener() { public void handleEvent(Event event) { treeDirty = true; handleExpandCollapse(event, false); } }); getTree().addListener(SWT.PaintItem, new Listener() { public void handleEvent(Event event) { paintTreeItem(event); } }); } /** * Paints the markers of the given tree item. * * @param event * - the event which occurred */ private void paintTreeItem(Event event) { SubModuleTreeItemMarkerRenderer renderer = getTreeItemRenderer(); renderer.setBounds(event.x, event.y, event.width, event.height); if (event.item instanceof TreeItem) { TreeItem item = (TreeItem) event.item; SubModuleNode node = (SubModuleNode) item.getData(); if (node != null) { renderer.setMarkers(node.getMarkers()); } renderer.paint(event.gc, event.item); } } /** * After a node has been expanded or collapsed the size of the module must * be updated. * * @param event * - the event which occurred * @param expand */ private void handleExpandCollapse(Event event, boolean expand) { if (event.item instanceof TreeItem) { TreeItem item = (TreeItem) event.item; INavigationNode<?> node = (INavigationNode<?>) item.getData(); node.setExpanded(expand); } resize(); } protected void setTreeBackGround() { subModuleTree.setBackground(LnfManager.getLnf().getColor("SubModuleTree.background")); //$NON-NLS-1$ } protected Composite getParent() { return parent; } /** * @see org.eclipse.riena.navigation.ui.swt.views.INavigationNodeView#getNavigationNode() */ public ModuleNode getNavigationNode() { return moduleNode; } /** * @see org.eclipse.riena.navigation.ui.swt.views.INavigationNodeView#bind(org.eclipse.riena.navigation.INavigationNode) */ public void bind(ModuleNode node) { moduleNode = node; navigationTreeObserver = new NavigationTreeObserver(); navigationTreeObserver.addListener(new SubModuleListener()); navigationTreeObserver.addListener(new ModuleListener()); navigationTreeObserver.addListenerTo(moduleNode); if (getNavigationNode().getNavigationNodeController() instanceof IController) { IController controller = (IController) node.getNavigationNodeController(); binding.injectRidgets(controller); binding.bind(controller); controller.afterBind(); } } /** * @see org.eclipse.riena.navigation.ui.swt.views.INavigationNodeView#unbind() */ public void unbind() { if (getNavigationNode().getNavigationNodeController() instanceof IController) { IController controller = (IController) getNavigationNode().getNavigationNodeController(); binding.unbind(controller); } navigationTreeObserver.removeListenerFrom(moduleNode); moduleNode = null; } /** * After adding of removing a sub-module from another sub-module, the module * view must be resized. */ private class SubModuleListener extends SubModuleNodeListener { @Override public void filterAdded(ISubModuleNode source, IUIFilter filter) { super.filterAdded(source, filter); updateModuleView(); } @Override public void filterRemoved(ISubModuleNode source, IUIFilter filter) { super.filterRemoved(source, filter); updateModuleView(); } /** * @see org.eclipse.riena.navigation.listener.NavigationNodeListener#childAdded(org.eclipse.riena.navigation.INavigationNode, * org.eclipse.riena.navigation.INavigationNode) */ @Override public void childAdded(ISubModuleNode source, ISubModuleNode childAdded) { resize(); } /** * @see org.eclipse.riena.navigation.listener.NavigationNodeListener#childRemoved(org.eclipse.riena.navigation.INavigationNode, * org.eclipse.riena.navigation.INavigationNode) */ @Override public void childRemoved(ISubModuleNode source, ISubModuleNode childRemoved) { resize(); } /** * @see org.eclipse.riena.navigation.listener.NavigationNodeListener#activated * (org.eclipse.riena.navigation.INavigationNode) */ @Override public void activated(ISubModuleNode source) { // fix for bug 269221 updateExpanded(source); resize(); } private void updateExpanded(ISubModuleNode node) { final INavigationNode<?> nodeParent = node.getParent(); if (nodeParent instanceof ISubModuleNode) { nodeParent.setExpanded(true); updateExpanded((ISubModuleNode) nodeParent); } } /** * @see org.eclipse.riena.navigation.listener.NavigationNodeListener#markersChanged(org.eclipse.riena.navigation.INavigationNode) */ @Override public void markersChanged(ISubModuleNode source) { getTree().redraw(); } @Override public void labelChanged(ISubModuleNode source) { super.labelChanged(source); getTree().redraw(); } } /** * After adding of removing a sub-module from this module, the module view * must be resized. */ private class ModuleListener extends ModuleNodeListener { @Override public void filterAdded(IModuleNode source, IUIFilter filter) { super.filterAdded(source, filter); updateModuleView(); } @Override public void filterRemoved(IModuleNode source, IUIFilter filter) { super.filterRemoved(source, filter); updateModuleView(); } /** * @see org.eclipse.riena.navigation.listener.NavigationNodeListener#activated(org.eclipse.riena.navigation.INavigationNode) */ @Override public void activated(IModuleNode source) { super.activated(source); updateModuleView(); } /** * @see org.eclipse.riena.navigation.listener.NavigationNodeListener#disposed * (org.eclipse.riena.navigation.INavigationNode) */ @Override public void disposed(IModuleNode source) { super.disposed(source); dispose(); } /** * @see org.eclipse.riena.navigation.listener.NavigationNodeListener#markersChanged(org.eclipse.riena.navigation.INavigationNode) */ @Override public void markersChanged(IModuleNode source) { super.markersChanged(source); title.setMarkers(source.getMarkers()); title.redraw(); } @Override public void labelChanged(IModuleNode source) { super.labelChanged(source); updateModuleView(); } } /** * Disposes this module item. */ public void dispose() { unbind(); // getBody().setVisible(false); // getBody().setBounds(0, 0, 0, 0); SwtUtilities.disposeWidget(title); SwtUtilities.disposeWidget(getBody()); SwtUtilities.disposeWidget(getTree()); } /** * Returns the tree with the sub-module items. * * @return tree */ private Tree getTree() { return subModuleTree; } /** * Returns the height of the open item. * * @return height. */ public int getOpenHeight() { IModuleNode navigationNode = getNavigationNode(); if ((navigationNode != null) && (navigationNode.isActivated())) { int depth = navigationNode.calcDepth(); if (depth == 0) { return 0; } else { int itemHeight = getTree().getItemHeight(); return depth * itemHeight + 1; } } else { return 0; } } /** * Returns a rectangle describing the size and location of this module. * * @return the bounds */ public Rectangle getBounds() { Rectangle bounds = title.getBounds(); if (getNavigationNode().isActivated()) { bounds.height += getBody().getSize().y; } return bounds; } /** * Returns if the module item is pressed or not. * * @param pressed * - true, if mouse over the module and pressed; otherwise false. */ public boolean isPressed() { return pressed; } /** * Sets if the module item is pressed or not.<br> * If the given state differs from the current state, the parent of item is * redrawn. * * @param pressed * - true, if mouse over the module and pressed; otherwise false. */ public void setPressed(boolean pressed) { if (this.pressed != pressed) { this.pressed = pressed; if (!parent.isDisposed()) { parent.redraw(); } } } /** * Returns if the module item is highlighted, because the mouse hovers over * the item. * * @return true, if mouse over the module; otherwise false. */ public boolean isHover() { return hover; } /** * Sets if the module item is highlighted, because the mouse hovers over the * item.<br> * If the given hover state differs from the current state, the parent of * item is redrawn. * * @param hover * - true, if mouse over the module; otherwise false. */ public void setHover(boolean hover) { if (this.hover != hover) { this.hover = hover; if (!parent.isDisposed()) { parent.redraw(); } } } /** * @return the icon */ public String getIcon() { if (getNavigationNode() == null) { return null; } return getNavigationNode().getIcon(); } /** * @return the activated */ public boolean isActivated() { if (getNavigationNode() == null) { return false; } return getNavigationNode().isActivated(); } /** * Returns whether this view is visible or not. * * @return {@code true} if nod if visible; otherwise {@code false} */ public boolean isVisible() { if (getNavigationNode() == null) { return false; } return getNavigationNode().isVisible(); } /** * @return the closeable */ public boolean isCloseable() { if (getNavigationNode() == null) { return false; } return getNavigationNode().isClosable(); } /** * @return the label */ public String getLabel() { if (getNavigationNode() == null) { return null; } return getNavigationNode().getLabel(); } protected void fireUpdated(INavigationNode<?> node) { for (IComponentUpdateListener listener : updateListeners.getListeners()) { listener.update(node); } } /** * @see org.eclipse.riena.navigation.ui.swt.views.INavigationNodeView#addUpdateListener(org.eclipse.riena.navigation.ui.swt.views.IComponentUpdateListener) */ public void addUpdateListener(IComponentUpdateListener listener) { updateListeners.add(listener); } /** * Returns the renderer that paints a module group. * * @return renderer */ private ModuleGroupRenderer getModuleGroupRenderer() { ModuleGroupRenderer renderer = (ModuleGroupRenderer) LnfManager.getLnf().getRenderer( LnfKeyConstants.MODULE_GROUP_RENDERER); if (renderer == null) { renderer = new ModuleGroupRenderer(); } return renderer; } /** * Returns the renderer that paints the markers of a tree item. * * @return renderer */ private SubModuleTreeItemMarkerRenderer getTreeItemRenderer() { SubModuleTreeItemMarkerRenderer renderer = (SubModuleTreeItemMarkerRenderer) LnfManager.getLnf().getRenderer( LnfKeyConstants.SUB_MODULE_TREE_ITEM_MARKER_RENDERER); if (renderer == null) { renderer = new SubModuleTreeItemMarkerRenderer(); } return renderer; } public void updateModuleView() { boolean currentActiveState = false; if (getNavigationNode() != null) { currentActiveState = getNavigationNode().isActivated(); } if (!SwtUtilities.isDisposed(title)) { layoutTitle(); } if (!SwtUtilities.isDisposed(getBody())) { if (getBody().isVisible() != currentActiveState) { getBody().setVisible(currentActiveState); } int height = getOpenHeight(); if (getBody().getSize().y != height) { FormData formData = new FormData(); formData.top = new FormAttachment(title); formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.height = height; getBody().setLayoutData(formData); } } // TODO performance activation disabled because UIFilter didnt work anymore properly, hidden submodule nodes didnt get visible because of redraw problems getParent().layout(); // Performance: Only layout if the activity of the ModuleNode or the tree inside has changed // if (currentActiveState != cachedActivityState || treeDirty) { // getParent().layout(); // cachedActivityState = currentActiveState; // treeDirty = false; // } title.setWindowActive(currentActiveState); } private void layoutTitle() { Control[] children = getParent().getChildren(); FormData formData = new FormData(); int index = -1; for (int i = 0; i < children.length; i++) { if (children[i] == title) { index = i; break; } } if (index == 0) { formData.top = new FormAttachment(0, 0); } else if (index < 0) { formData.top = new FormAttachment(children[children.length - 1], getModuleGroupRenderer() .getModuleModuleGap()); } else { formData.top = new FormAttachment(children[index - 1], getModuleGroupRenderer().getModuleModuleGap()); } formData.left = new FormAttachment(0, 0); formData.right = new FormAttachment(100, 0); formData.height = title.getSize().y; title.setLayoutData(formData); } }
false
true
private void addListeners() { getTree().addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { treeDirty = true; TreeItem[] selection = getTree().getSelection(); if (selection[0].getData() instanceof ISubModuleNode) { ISubModuleNode activeSubModule = (ISubModuleNode) selection[0].getData(); activeSubModule.activate(); } resize(); } }); getTree().addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { onTreePaint(event.gc); } }); getTree().addListener(SWT.Expand, new Listener() { public void handleEvent(Event event) { treeDirty = true; handleExpandCollapse(event, true); } }); getTree().addListener(SWT.Collapse, new Listener() { public void handleEvent(Event event) { treeDirty = true; handleExpandCollapse(event, false); } }); getTree().addListener(SWT.PaintItem, new Listener() { public void handleEvent(Event event) { paintTreeItem(event); } }); }
private void addListeners() { getTree().addListener(SWT.Selection, new Listener() { public void handleEvent(Event event) { treeDirty = true; TreeItem[] selection = getTree().getSelection(); if ((selection.length > 0) && (selection[0].getData() instanceof ISubModuleNode)) { ISubModuleNode activeSubModule = (ISubModuleNode) selection[0].getData(); if (activeSubModule.getParent().isActivated()) { activeSubModule.activate(); } } resize(); } }); getTree().addListener(SWT.Paint, new Listener() { public void handleEvent(Event event) { onTreePaint(event.gc); } }); getTree().addListener(SWT.Expand, new Listener() { public void handleEvent(Event event) { treeDirty = true; handleExpandCollapse(event, true); } }); getTree().addListener(SWT.Collapse, new Listener() { public void handleEvent(Event event) { treeDirty = true; handleExpandCollapse(event, false); } }); getTree().addListener(SWT.PaintItem, new Listener() { public void handleEvent(Event event) { paintTreeItem(event); } }); }
diff --git a/java/server/src/org/openqa/grid/web/utils/BrowserNameUtils.java b/java/server/src/org/openqa/grid/web/utils/BrowserNameUtils.java index b75528513..d4a0a3bc4 100644 --- a/java/server/src/org/openqa/grid/web/utils/BrowserNameUtils.java +++ b/java/server/src/org/openqa/grid/web/utils/BrowserNameUtils.java @@ -1,50 +1,52 @@ /* Copyright 2007-2011 WebDriver committers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.grid.web.utils; import org.openqa.grid.web.Hub; /** * Utilities for dealing with browser names. */ public class BrowserNameUtils { public static String lookupGrid1Environment(String browserString) { String translatedBrowserString = Hub.getGrid1Mapping().get(browserString); return (translatedBrowserString == null) ? browserString : translatedBrowserString; } public static String consoleIconName(String browserString) { String ret = browserString; // Take care of any Grid 1.0 named environment translation. if (browserString.charAt(0) != '*') { browserString = lookupGrid1Environment(browserString); } // Map browser environments to icon names. if ("*iexplore".equals(browserString)) { ret = "internet explorer"; } else if ("*firefox".equals(browserString)) { ret = "firefox"; } else if ("*safari".equals(browserString)) { ret = "safari"; - } + } else if ("*googlechrome".equals(browserString)) { + ret = "chrome"; + } return ret; } }
true
true
public static String consoleIconName(String browserString) { String ret = browserString; // Take care of any Grid 1.0 named environment translation. if (browserString.charAt(0) != '*') { browserString = lookupGrid1Environment(browserString); } // Map browser environments to icon names. if ("*iexplore".equals(browserString)) { ret = "internet explorer"; } else if ("*firefox".equals(browserString)) { ret = "firefox"; } else if ("*safari".equals(browserString)) { ret = "safari"; } return ret; }
public static String consoleIconName(String browserString) { String ret = browserString; // Take care of any Grid 1.0 named environment translation. if (browserString.charAt(0) != '*') { browserString = lookupGrid1Environment(browserString); } // Map browser environments to icon names. if ("*iexplore".equals(browserString)) { ret = "internet explorer"; } else if ("*firefox".equals(browserString)) { ret = "firefox"; } else if ("*safari".equals(browserString)) { ret = "safari"; } else if ("*googlechrome".equals(browserString)) { ret = "chrome"; } return ret; }
diff --git a/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java b/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java index d6afefdd..2ab4a042 100644 --- a/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java +++ b/databus-core/src/main/java/com/inmobi/databus/utils/CalendarHelper.java @@ -1,166 +1,166 @@ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.inmobi.databus.utils; import java.io.File; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.apache.hadoop.fs.Path; import org.apache.log4j.Logger; public class CalendarHelper { static Logger logger = Logger.getLogger(CalendarHelper.class); static String minDirFormatStr = "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator + "HH" + File.separator +"mm"; static final ThreadLocal<DateFormat> minDirFormat = new ThreadLocal<DateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat(minDirFormatStr); } }; // TODO - all date/time should be returned in a common time zone GMT public static Date getDateFromStreamDir(Path streamDirPrefix, Path dir) { String pathStr = dir.toString(); int startIndex = streamDirPrefix.toString().length() + 1; /* logger.debug("StartIndex [" + startIndex + "] PathStr [" + pathStr +"] endIndex [" + (startIndex + minDirFormatStr.length()) + "] length [" + pathStr.length() +"]"); */ String dirString = pathStr.substring(startIndex, startIndex + minDirFormatStr.length()); try { return minDirFormat.get().parse(dirString); } catch (ParseException e) { logger.warn("Could not get date from directory passed", e); } return null; } public static Calendar getDate(String year, String month, String day) { return new GregorianCalendar(new Integer(year).intValue(), new Integer( month).intValue() - 1, new Integer(day).intValue()); } public static Calendar getDate(Integer year, Integer month, Integer day) { return new GregorianCalendar(year.intValue(), month.intValue() - 1, day.intValue()); } public static Calendar getDateHour(String year, String month, String day, String hour) { return new GregorianCalendar(new Integer(year).intValue(), new Integer( month).intValue() - 1, new Integer(day).intValue(), new Integer(hour).intValue(), new Integer(0)); } public static Calendar getDateHourMinute(Integer year, Integer month, Integer day, Integer hour, Integer minute) { return new GregorianCalendar(year.intValue(), month.intValue() - 1, day.intValue(), hour.intValue(), minute.intValue()); } public static String getCurrentMinute() { Calendar calendar; calendar = new GregorianCalendar(); String minute = Integer.toString(calendar.get(Calendar.MINUTE)); return minute; } public static String getCurrentHour() { Calendar calendar; calendar = new GregorianCalendar(); String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)); return hour; } public static Calendar getNowTime() { return new GregorianCalendar(); } private static String getCurrentDayTimeAsString(boolean includeMinute) { return getDayTimeAsString(new GregorianCalendar(), includeMinute, includeMinute); } private static String getDayTimeAsString(Calendar calendar, boolean includeHour, boolean includeMinute) { String minute = null; String hour = null; String fileNameInnYYMMDDHRMNFormat = null; String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = Integer.toString(calendar.get(Calendar.MONTH) + 1); String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)); if (includeHour || includeMinute) { hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)); } if (includeMinute) { minute = Integer.toString(calendar.get(Calendar.MINUTE)); } - if (includeHour) { - fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour; - } else if (includeMinute) { + if (includeMinute) { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour + "-" + minute; + } else if (includeHour) { + fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour; } else { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day; } logger.debug("getCurrentDayTimeAsString :: [" + fileNameInnYYMMDDHRMNFormat + "]"); return fileNameInnYYMMDDHRMNFormat; } public static String getCurrentDayTimeAsString() { return getCurrentDayTimeAsString(true); } public static String getCurrentDayHourAsString() { return getDayTimeAsString(new GregorianCalendar(), true, false); } public static String getCurrentDateAsString() { return getCurrentDayTimeAsString(false); } public static String getDateAsString(Calendar calendar) { return getDayTimeAsString(calendar, false, false); } public static String getDateTimeAsString(Calendar calendar) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); return format.format(calendar.getTime()); } public static Calendar getDateTime(String dateTime) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm"); Calendar calendar = new GregorianCalendar(); try { calendar.setTime(format.parse(dateTime)); } catch(Exception e){ } return calendar; } }
false
true
private static String getDayTimeAsString(Calendar calendar, boolean includeHour, boolean includeMinute) { String minute = null; String hour = null; String fileNameInnYYMMDDHRMNFormat = null; String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = Integer.toString(calendar.get(Calendar.MONTH) + 1); String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)); if (includeHour || includeMinute) { hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)); } if (includeMinute) { minute = Integer.toString(calendar.get(Calendar.MINUTE)); } if (includeHour) { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour; } else if (includeMinute) { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour + "-" + minute; } else { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day; } logger.debug("getCurrentDayTimeAsString :: [" + fileNameInnYYMMDDHRMNFormat + "]"); return fileNameInnYYMMDDHRMNFormat; }
private static String getDayTimeAsString(Calendar calendar, boolean includeHour, boolean includeMinute) { String minute = null; String hour = null; String fileNameInnYYMMDDHRMNFormat = null; String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = Integer.toString(calendar.get(Calendar.MONTH) + 1); String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)); if (includeHour || includeMinute) { hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)); } if (includeMinute) { minute = Integer.toString(calendar.get(Calendar.MINUTE)); } if (includeMinute) { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour + "-" + minute; } else if (includeHour) { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day + "-" + hour; } else { fileNameInnYYMMDDHRMNFormat = year + "-" + month + "-" + day; } logger.debug("getCurrentDayTimeAsString :: [" + fileNameInnYYMMDDHRMNFormat + "]"); return fileNameInnYYMMDDHRMNFormat; }
diff --git a/trunk/GeoBeagle/src/com/google/code/geobeagle/activity/main/view/OnClickListenerCacheDetails.java b/trunk/GeoBeagle/src/com/google/code/geobeagle/activity/main/view/OnClickListenerCacheDetails.java index 38902ac9..0bea84a9 100644 --- a/trunk/GeoBeagle/src/com/google/code/geobeagle/activity/main/view/OnClickListenerCacheDetails.java +++ b/trunk/GeoBeagle/src/com/google/code/geobeagle/activity/main/view/OnClickListenerCacheDetails.java @@ -1,53 +1,51 @@ /* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.details.DetailsActivity; import com.google.code.geobeagle.activity.main.GeoBeagle; import com.google.inject.Inject; import com.google.inject.Injector; import android.app.Activity; import android.content.Intent; import android.view.View; public class OnClickListenerCacheDetails implements View.OnClickListener { private final GeoBeagle geoBeagle; // For testing. public OnClickListenerCacheDetails(Activity geoBeagle) { this.geoBeagle = (GeoBeagle)geoBeagle; } @Inject public OnClickListenerCacheDetails(Injector injector) { geoBeagle = (GeoBeagle)injector.getInstance(Activity.class); } @Override public void onClick(View v) { Intent intent = new Intent(geoBeagle, DetailsActivity.class); Geocache geocache = geoBeagle.getGeocache(); - intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_SOURCE, geocache - .getSourceName()); - intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_ID, geocache.getId()); - intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_NAME, geocache - .getName()); + intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_SOURCE, geocache.getSourceName()); + intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_ID, geocache.getId().toString()); + intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_NAME, geocache.getName().toString()); geoBeagle.startActivity(intent); } }
true
true
public void onClick(View v) { Intent intent = new Intent(geoBeagle, DetailsActivity.class); Geocache geocache = geoBeagle.getGeocache(); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_SOURCE, geocache .getSourceName()); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_ID, geocache.getId()); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_NAME, geocache .getName()); geoBeagle.startActivity(intent); }
public void onClick(View v) { Intent intent = new Intent(geoBeagle, DetailsActivity.class); Geocache geocache = geoBeagle.getGeocache(); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_SOURCE, geocache.getSourceName()); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_ID, geocache.getId().toString()); intent.putExtra(DetailsActivity.INTENT_EXTRA_GEOCACHE_NAME, geocache.getName().toString()); geoBeagle.startActivity(intent); }
diff --git a/src/com/btmura/android/reddit/provider/SubredditProvider.java b/src/com/btmura/android/reddit/provider/SubredditProvider.java index 9c4b4b19..4a2a09e8 100644 --- a/src/com/btmura/android/reddit/provider/SubredditProvider.java +++ b/src/com/btmura/android/reddit/provider/SubredditProvider.java @@ -1,201 +1,205 @@ /* * Copyright (C) 2012 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.provider; import java.io.IOException; import java.util.ArrayList; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.backup.BackupManager; import android.content.ContentProviderOperation; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.DatabaseUtils.InsertHelper; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.AsyncTask; import android.os.RemoteException; import android.util.Log; import android.widget.Toast; import com.btmura.android.reddit.BuildConfig; import com.btmura.android.reddit.R; import com.btmura.android.reddit.accounts.AccountUtils; import com.btmura.android.reddit.database.SubredditSearches; import com.btmura.android.reddit.database.Subreddits; import com.btmura.android.reddit.util.Array; public class SubredditProvider extends SessionProvider { public static final String TAG = "SubredditProvider"; public static final String AUTHORITY = "com.btmura.android.reddit.provider.subreddits"; static final String BASE_AUTHORITY_URI = "content://" + AUTHORITY + "/"; static final String PATH_SUBREDDITS = "subreddits"; static final String PATH_SEARCHES = "searches"; public static final Uri SUBREDDITS_URI = Uri.parse(BASE_AUTHORITY_URI + PATH_SUBREDDITS); public static final Uri SEARCHES_URI = Uri.parse(BASE_AUTHORITY_URI + PATH_SEARCHES); public static final String PARAM_FETCH = "fetch"; public static final String PARAM_ACCOUNT = "account"; public static final String PARAM_SESSION_ID = "sessionId"; public static final String PARAM_QUERY = "query"; private static final UriMatcher MATCHER = new UriMatcher(0); private static final int MATCH_SUBREDDITS = 1; private static final int MATCH_SEARCHES = 2; static { MATCHER.addURI(AUTHORITY, PATH_SUBREDDITS, MATCH_SUBREDDITS); MATCHER.addURI(AUTHORITY, PATH_SEARCHES, MATCH_SEARCHES); } public SubredditProvider() { super(TAG); } protected String getTable(Uri uri, boolean isQuery) { int match = MATCHER.match(uri); switch (match) { case MATCH_SUBREDDITS: return Subreddits.TABLE_NAME; case MATCH_SEARCHES: return SubredditSearches.TABLE_NAME; default: throw new IllegalArgumentException("uri: " + uri); } } protected void processUri(Uri uri, SQLiteDatabase db, ContentValues values) { if (uri.getBooleanQueryParameter(PARAM_FETCH, false)) { handleFetch(uri, db); } } private void handleFetch(Uri uri, SQLiteDatabase db) { try { long sessionTimestamp = getSessionTimestamp(); String accountName = uri.getQueryParameter(PARAM_ACCOUNT); String sessionId = uri.getQueryParameter(PARAM_SESSION_ID); String query = uri.getQueryParameter(PARAM_QUERY); Context context = getContext(); String cookie = AccountUtils.getCookie(context, accountName); SubredditSearchListing listing = SubredditSearchListing.get(context, accountName, sessionId, sessionTimestamp, query, cookie); long cleaned; db.beginTransaction(); try { // Delete old results that can't be possibly viewed anymore. cleaned = db.delete(SubredditSearches.TABLE_NAME, SubredditSearches.SELECT_BEFORE_TIMESTAMP, Array.of(sessionTimestamp)); InsertHelper insertHelper = new InsertHelper(db, SubredditSearches.TABLE_NAME); int count = listing.values.size(); for (int i = 0; i < count; i++) { insertHelper.insert(listing.values.get(i)); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } if (BuildConfig.DEBUG) { Log.d(TAG, "cleaned: " + cleaned); } } catch (OperationCanceledException e) { Log.e(TAG, e.getMessage(), e); } catch (AuthenticatorException e) { Log.e(TAG, e.getMessage(), e); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); } } public static void insertInBackground(Context context, String accountName, String... subreddits) { modifyInBackground(context, accountName, subreddits, true); } public static void deleteInBackground(Context context, String accountName, String... subreddits) { modifyInBackground(context, accountName, subreddits, false); } private static void modifyInBackground(Context context, final String accountName, final String[] subreddits, final boolean add) { final Context appContext = context.getApplicationContext(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { - Uri syncUri = SUBREDDITS_URI.buildUpon() - .appendQueryParameter(PARAM_SYNC, Boolean.toString(true)) - .build(); + // Only trigger a sync on real accounts. + Uri syncUri = SUBREDDITS_URI; + if (AccountUtils.isAccount(accountName)) { + syncUri = syncUri.buildUpon() + .appendQueryParameter(PARAM_SYNC, Boolean.toString(true)) + .build(); + } int count = subreddits.length; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(count * 2); int state = add ? Subreddits.STATE_INSERTING : Subreddits.STATE_DELETING; for (int i = 0; i < count; i++) { ops.add(ContentProviderOperation.newDelete(syncUri) .withSelection(Subreddits.SELECT_BY_ACCOUNT_AND_NAME, Array.of(accountName, subreddits[i])) .build()); ops.add(ContentProviderOperation.newInsert(syncUri) .withValue(Subreddits.COLUMN_ACCOUNT, accountName) .withValue(Subreddits.COLUMN_NAME, subreddits[i]) .withValue(Subreddits.COLUMN_STATE, state) .build()); } try { appContext.getContentResolver().applyBatch(SubredditProvider.AUTHORITY, ops); } catch (RemoteException e) { Log.e(TAG, e.getMessage(), e); } catch (OperationApplicationException e) { Log.e(TAG, e.getMessage(), e); } return null; } @Override protected void onPostExecute(Void intoTheVoid) { showChangeToast(appContext, add, subreddits.length); scheduleBackup(appContext, accountName); } }.execute(); } private static void showChangeToast(Context context, boolean added, int count) { int resId = added ? R.plurals.subreddits_added : R.plurals.subreddits_deleted; CharSequence text = context.getResources().getQuantityString(resId, count, count); Toast.makeText(context, text, Toast.LENGTH_SHORT).show(); } private static void scheduleBackup(Context context, String accountName) { if (!AccountUtils.isAccount(accountName)) { new BackupManager(context).dataChanged(); } } }
true
true
private static void modifyInBackground(Context context, final String accountName, final String[] subreddits, final boolean add) { final Context appContext = context.getApplicationContext(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { Uri syncUri = SUBREDDITS_URI.buildUpon() .appendQueryParameter(PARAM_SYNC, Boolean.toString(true)) .build(); int count = subreddits.length; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(count * 2); int state = add ? Subreddits.STATE_INSERTING : Subreddits.STATE_DELETING; for (int i = 0; i < count; i++) { ops.add(ContentProviderOperation.newDelete(syncUri) .withSelection(Subreddits.SELECT_BY_ACCOUNT_AND_NAME, Array.of(accountName, subreddits[i])) .build()); ops.add(ContentProviderOperation.newInsert(syncUri) .withValue(Subreddits.COLUMN_ACCOUNT, accountName) .withValue(Subreddits.COLUMN_NAME, subreddits[i]) .withValue(Subreddits.COLUMN_STATE, state) .build()); } try { appContext.getContentResolver().applyBatch(SubredditProvider.AUTHORITY, ops); } catch (RemoteException e) { Log.e(TAG, e.getMessage(), e); } catch (OperationApplicationException e) { Log.e(TAG, e.getMessage(), e); } return null; } @Override protected void onPostExecute(Void intoTheVoid) { showChangeToast(appContext, add, subreddits.length); scheduleBackup(appContext, accountName); } }.execute(); }
private static void modifyInBackground(Context context, final String accountName, final String[] subreddits, final boolean add) { final Context appContext = context.getApplicationContext(); new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { // Only trigger a sync on real accounts. Uri syncUri = SUBREDDITS_URI; if (AccountUtils.isAccount(accountName)) { syncUri = syncUri.buildUpon() .appendQueryParameter(PARAM_SYNC, Boolean.toString(true)) .build(); } int count = subreddits.length; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(count * 2); int state = add ? Subreddits.STATE_INSERTING : Subreddits.STATE_DELETING; for (int i = 0; i < count; i++) { ops.add(ContentProviderOperation.newDelete(syncUri) .withSelection(Subreddits.SELECT_BY_ACCOUNT_AND_NAME, Array.of(accountName, subreddits[i])) .build()); ops.add(ContentProviderOperation.newInsert(syncUri) .withValue(Subreddits.COLUMN_ACCOUNT, accountName) .withValue(Subreddits.COLUMN_NAME, subreddits[i]) .withValue(Subreddits.COLUMN_STATE, state) .build()); } try { appContext.getContentResolver().applyBatch(SubredditProvider.AUTHORITY, ops); } catch (RemoteException e) { Log.e(TAG, e.getMessage(), e); } catch (OperationApplicationException e) { Log.e(TAG, e.getMessage(), e); } return null; } @Override protected void onPostExecute(Void intoTheVoid) { showChangeToast(appContext, add, subreddits.length); scheduleBackup(appContext, accountName); } }.execute(); }
diff --git a/scm-webapp/src/main/java/sonia/scm/web/cgi/DefaultCGIExecutor.java b/scm-webapp/src/main/java/sonia/scm/web/cgi/DefaultCGIExecutor.java index f343d4643..2a89ff2ab 100644 --- a/scm-webapp/src/main/java/sonia/scm/web/cgi/DefaultCGIExecutor.java +++ b/scm-webapp/src/main/java/sonia/scm/web/cgi/DefaultCGIExecutor.java @@ -1,532 +1,532 @@ /** * Copyright (c) 2010, Sebastian Sdorra * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of SCM-Manager; nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * http://bitbucket.org/sdorra/scm-manager * */ package sonia.scm.web.cgi; //~--- non-JDK imports -------------------------------------------------------- import java.util.logging.Level; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import sonia.scm.SCMContext; import sonia.scm.config.ScmConfiguration; import sonia.scm.util.HttpUtil; import sonia.scm.util.IOUtil; import sonia.scm.util.Util; //~--- JDK imports ------------------------------------------------------------ import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.util.Enumeration; import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Sebastian Sdorra */ public class DefaultCGIExecutor extends AbstractCGIExecutor { /** Field description */ public static final String CGI_VERSION = "CGI/1.1"; /** Field description */ public static final int DEFAULT_BUFFER_SIZE = 16264; /** Field description */ private static final String SERVER_SOFTWARE_PREFIX = "scm-manager/"; /** the logger for DefaultCGIExecutor */ private static final Logger logger = LoggerFactory.getLogger(DefaultCGIExecutor.class); //~--- constructors --------------------------------------------------------- /** * Constructs ... * * * @param configuration * @param context * @param request * @param response */ public DefaultCGIExecutor(ScmConfiguration configuration, ServletContext context, HttpServletRequest request, HttpServletResponse response) { this.configuration = configuration; this.context = context; this.request = request; this.response = response; // set default values this.bufferSize = DEFAULT_BUFFER_SIZE; this.environment = createEnvironment(); } //~--- methods -------------------------------------------------------------- /** * Method description * * * * * @param cmd * * @throws IOException */ @Override public void execute(String cmd) throws IOException { File command = new File(cmd); EnvList env = new EnvList(environment); if (workDirectory == null) { workDirectory = command.getParentFile(); } String path = command.getAbsolutePath(); String pathTranslated = request.getPathTranslated(); if (Util.isEmpty(pathTranslated)) { pathTranslated = path; } env.set(ENV_PATH_TRANSLATED, pathTranslated); String execCmd = path; if ((execCmd.charAt(0) != '"') && (execCmd.indexOf(" ") >= 0)) { execCmd = "\"".concat(execCmd).concat("\""); } if (interpreter != null) { execCmd = interpreter.concat(" ").concat(execCmd); } if (logger.isDebugEnabled()) { logger.debug("execute cgi: {}", execCmd); if (logger.isTraceEnabled()) { logger.trace(environment.toString()); } } Process p = null; try { p = Runtime.getRuntime().exec(execCmd, environment.getEnvArray(), workDirectory); execute(p); } finally { if (p != null) { p.destroy(); } } } /** * Method description * * * @return */ private EnvList createEnvironment() { String pathInfo = request.getPathInfo(); int serverPort = HttpUtil.getServerPort(configuration, request); String scriptName = request.getRequestURI().substring(0, request.getRequestURI().length() - pathInfo.length()); String scriptPath = context.getRealPath(scriptName); int len = request.getContentLength(); EnvList env = new EnvList(); env.set(ENV_AUTH_TYPE, request.getAuthType()); /** * Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined * if there is no content, so we cannot put 0 or -1 in as per the * Servlet API spec. * * see org.apache.catalina.servlets.CGIServlet **/ if ( len <= 0 ) { env.set(ENV_CONTENT_LENGTH, ""); } else { env.set(ENV_CONTENT_LENGTH, Integer.toString(len)); } - env.set(ENV_CONTENT_TYPE, request.getContentType()); + env.set(ENV_CONTENT_TYPE, Util.nonNull(request.getContentType())); env.set(ENV_GATEWAY_INTERFACE, CGI_VERSION); env.set(ENV_PATH_INFO, pathInfo); env.set(ENV_QUERY_STRING, request.getQueryString()); env.set(ENV_REMOTE_ADDR, request.getRemoteAddr()); env.set(ENV_REMOTE_HOST, request.getRemoteHost()); // The identity information reported about the connection by a // RFC 1413 [11] request to the remote agent, if // available. Servers MAY choose not to support this feature, or // not to request the data for efficiency reasons. // "REMOTE_IDENT" => "NYI" env.set(ENV_REMOTE_USER, request.getRemoteUser()); env.set(ENV_REQUEST_METHOD, request.getMethod()); env.set(ENV_SCRIPT_NAME, scriptName); env.set(ENV_SCRIPT_FILENAME, scriptPath); - env.set(ENV_SERVER_NAME, request.getServerName()); + env.set(ENV_SERVER_NAME, Util.nonNull(request.getServerName())); env.set(ENV_SERVER_PORT, Integer.toString(serverPort)); - env.set(ENV_SERVER_PROTOCOL, request.getProtocol()); + env.set(ENV_SERVER_PROTOCOL, Util.nonNull(request.getProtocol())); env.set( ENV_SERVER_SOFTWARE, SERVER_SOFTWARE_PREFIX.concat(SCMContext.getContext().getVersion())); Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { String name = (String) enm.nextElement(); String value = request.getHeader(name); env.set(ENV_HTTP_HEADER_PREFIX + name.toUpperCase().replace('-', '_'), value); } // these extra ones were from printenv on www.dev.nomura.co.uk env.set(ENV_HTTPS, (request.isSecure() ? ENV_HTTPS_VALUE_ON : ENV_HTTPS_VALUE_OFF)); return env; } /** * Method description * * * @param process * * @throws IOException */ private void execute(Process process) throws IOException { InputStream processIS = null; InputStream processES = null; try { processES = process.getErrorStream(); processErrorStreamAsync(processES); processServletInput(process); processIS = process.getInputStream(); processProcessInputStream(processIS); waitForFinish(process); } finally { IOUtil.close(processIS); IOUtil.close(processES); } } private void processErrorStreamAsync( final InputStream errorStream ) { new Thread(new Runnable() { @Override public void run() { try { processErrorStream(errorStream); } catch (IOException ex) { logger.error( "could not read errorstream", ex ); } } }).start(); } /** * Method description * * * @param is * * * @throws IOException */ private void parseHeaders(InputStream is) throws IOException { String line = null; response.setContentLength(-1); while ((line = getTextLineFromStream(is)).length() > 0) { if (logger.isTraceEnabled()) { logger.trace(" ".concat(line)); } if (!line.startsWith(RESPONSE_HEADER_HTTP_PREFIX)) { int k = line.indexOf(':'); if (k > 0) { String key = line.substring(0, k).trim(); String value = line.substring(k + 1).trim(); if (RESPONSE_HEADER_LOCATION.equalsIgnoreCase(key)) { response.sendRedirect(response.encodeRedirectURL(value)); } else if (RESPONSE_HEADER_STATUS.equalsIgnoreCase(key)) { String[] token = value.split(" "); int status = Integer.parseInt(token[0]); if (logger.isDebugEnabled()) { logger.debug("CGI returned with status {}", status); } if (status < 304) { response.setStatus(status); } else { response.sendError(status); } } else { // add remaining header items to our response header response.addHeader(key, value); } } } } } /** * Method description * * * @param in * * @throws IOException */ private void processErrorStream(InputStream in) throws IOException { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(in)); StringBuilder error = new StringBuilder(); String s = System.getProperty("line.separator"); String line = reader.readLine(); while (line != null) { error.append(line); line = reader.readLine(); if (line != null) { error.append(s); } } if (logger.isWarnEnabled()) { String msg = error.toString().trim(); if (Util.isNotEmpty(msg)) { logger.warn(msg); } } } finally { IOUtil.close(reader); } } /** * Method description * * * @param is * * @throws IOException */ private void processProcessInputStream(InputStream is) throws IOException { parseHeaders(is); ServletOutputStream servletOS = null; try { servletOS = response.getOutputStream(); IOUtil.copy(is, servletOS, bufferSize); } finally { IOUtil.close(servletOS); } } /** * Method description * * * @param process */ private void processServletInput(Process process) { OutputStream processOS = null; ServletInputStream servletIS = null; try { processOS = process.getOutputStream(); servletIS = request.getInputStream(); IOUtil.copy(servletIS, processOS, bufferSize); } catch (IOException ex) { logger.error( "could not read from ServletInputStream and write to ProcessOutputStream", ex); } finally { IOUtil.close(processOS); IOUtil.close(servletIS); } } /** * Method description * * * @param process * */ private void waitForFinish(Process process) { try { int exitCode = process.waitFor(); if (exitCode != 0) { logger.warn("process ends with exit code {}", exitCode); } } catch (InterruptedException ex) { logger.error("process interrupted", ex); } } //~--- get methods ---------------------------------------------------------- /** * Method description * * * @param is * * @return * * @throws IOException */ private String getTextLineFromStream(InputStream is) throws IOException { StringBuilder buffer = new StringBuilder(); int b; while ((b = is.read()) != -1 && (b != (int) '\n')) { buffer.append((char) b); } return buffer.toString().trim(); } //~--- fields --------------------------------------------------------------- /** Field description */ private ScmConfiguration configuration; /** Field description */ private ServletContext context; /** Field description */ private HttpServletRequest request; /** Field description */ private HttpServletResponse response; }
false
true
private EnvList createEnvironment() { String pathInfo = request.getPathInfo(); int serverPort = HttpUtil.getServerPort(configuration, request); String scriptName = request.getRequestURI().substring(0, request.getRequestURI().length() - pathInfo.length()); String scriptPath = context.getRealPath(scriptName); int len = request.getContentLength(); EnvList env = new EnvList(); env.set(ENV_AUTH_TYPE, request.getAuthType()); /** * Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined * if there is no content, so we cannot put 0 or -1 in as per the * Servlet API spec. * * see org.apache.catalina.servlets.CGIServlet **/ if ( len <= 0 ) { env.set(ENV_CONTENT_LENGTH, ""); } else { env.set(ENV_CONTENT_LENGTH, Integer.toString(len)); } env.set(ENV_CONTENT_TYPE, request.getContentType()); env.set(ENV_GATEWAY_INTERFACE, CGI_VERSION); env.set(ENV_PATH_INFO, pathInfo); env.set(ENV_QUERY_STRING, request.getQueryString()); env.set(ENV_REMOTE_ADDR, request.getRemoteAddr()); env.set(ENV_REMOTE_HOST, request.getRemoteHost()); // The identity information reported about the connection by a // RFC 1413 [11] request to the remote agent, if // available. Servers MAY choose not to support this feature, or // not to request the data for efficiency reasons. // "REMOTE_IDENT" => "NYI" env.set(ENV_REMOTE_USER, request.getRemoteUser()); env.set(ENV_REQUEST_METHOD, request.getMethod()); env.set(ENV_SCRIPT_NAME, scriptName); env.set(ENV_SCRIPT_FILENAME, scriptPath); env.set(ENV_SERVER_NAME, request.getServerName()); env.set(ENV_SERVER_PORT, Integer.toString(serverPort)); env.set(ENV_SERVER_PROTOCOL, request.getProtocol()); env.set( ENV_SERVER_SOFTWARE, SERVER_SOFTWARE_PREFIX.concat(SCMContext.getContext().getVersion())); Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { String name = (String) enm.nextElement(); String value = request.getHeader(name); env.set(ENV_HTTP_HEADER_PREFIX + name.toUpperCase().replace('-', '_'), value); } // these extra ones were from printenv on www.dev.nomura.co.uk env.set(ENV_HTTPS, (request.isSecure() ? ENV_HTTPS_VALUE_ON : ENV_HTTPS_VALUE_OFF)); return env; }
private EnvList createEnvironment() { String pathInfo = request.getPathInfo(); int serverPort = HttpUtil.getServerPort(configuration, request); String scriptName = request.getRequestURI().substring(0, request.getRequestURI().length() - pathInfo.length()); String scriptPath = context.getRealPath(scriptName); int len = request.getContentLength(); EnvList env = new EnvList(); env.set(ENV_AUTH_TYPE, request.getAuthType()); /** * Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined * if there is no content, so we cannot put 0 or -1 in as per the * Servlet API spec. * * see org.apache.catalina.servlets.CGIServlet **/ if ( len <= 0 ) { env.set(ENV_CONTENT_LENGTH, ""); } else { env.set(ENV_CONTENT_LENGTH, Integer.toString(len)); } env.set(ENV_CONTENT_TYPE, Util.nonNull(request.getContentType())); env.set(ENV_GATEWAY_INTERFACE, CGI_VERSION); env.set(ENV_PATH_INFO, pathInfo); env.set(ENV_QUERY_STRING, request.getQueryString()); env.set(ENV_REMOTE_ADDR, request.getRemoteAddr()); env.set(ENV_REMOTE_HOST, request.getRemoteHost()); // The identity information reported about the connection by a // RFC 1413 [11] request to the remote agent, if // available. Servers MAY choose not to support this feature, or // not to request the data for efficiency reasons. // "REMOTE_IDENT" => "NYI" env.set(ENV_REMOTE_USER, request.getRemoteUser()); env.set(ENV_REQUEST_METHOD, request.getMethod()); env.set(ENV_SCRIPT_NAME, scriptName); env.set(ENV_SCRIPT_FILENAME, scriptPath); env.set(ENV_SERVER_NAME, Util.nonNull(request.getServerName())); env.set(ENV_SERVER_PORT, Integer.toString(serverPort)); env.set(ENV_SERVER_PROTOCOL, Util.nonNull(request.getProtocol())); env.set( ENV_SERVER_SOFTWARE, SERVER_SOFTWARE_PREFIX.concat(SCMContext.getContext().getVersion())); Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { String name = (String) enm.nextElement(); String value = request.getHeader(name); env.set(ENV_HTTP_HEADER_PREFIX + name.toUpperCase().replace('-', '_'), value); } // these extra ones were from printenv on www.dev.nomura.co.uk env.set(ENV_HTTPS, (request.isSecure() ? ENV_HTTPS_VALUE_ON : ENV_HTTPS_VALUE_OFF)); return env; }
diff --git a/org.thingml.utils/src/main/java/org/thingml/comm/rxtx/Serial4ThingML.java b/org.thingml.utils/src/main/java/org/thingml/comm/rxtx/Serial4ThingML.java index 1839459e1..6e1b897d0 100644 --- a/org.thingml.utils/src/main/java/org/thingml/comm/rxtx/Serial4ThingML.java +++ b/org.thingml.utils/src/main/java/org/thingml/comm/rxtx/Serial4ThingML.java @@ -1,327 +1,327 @@ /** * Copyright (C) 2011 SINTEF <[email protected]> * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingml.comm.rxtx; import gnu.io.CommPort; import gnu.io.CommPortIdentifier; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import javax.swing.JOptionPane; public class Serial4ThingML { static { System.out.println("Load RxTx"); String osName = System.getProperty("os.name"); String osProc = System.getProperty("os.arch"); try { System.out.println("osName=" + osName + ", osProc=" + osProc); if (osName.equals("Mac OS X")) { NativeLibUtil.copyFile(Serial4ThingML.class.getClassLoader().getResourceAsStream("nativelib/Mac_OS_X/librxtxSerial.jnilib"), "librxtxSerial.jnilib"); } else if (osName.equals("Win32")) { NativeLibUtil.copyFile(Serial4ThingML.class.getClassLoader().getResourceAsStream("nativelib/Windows/win32/rxtxSerial.dll"), "rxtxSerial.dll"); } else if (osName.equals("Win64") || osName.equals("Windows 7")) { NativeLibUtil.copyFile(Serial4ThingML.class.getClassLoader().getResourceAsStream("nativelib/Windows/win64/rxtxSerial.dll"), "rxtxSerial.dll"); } else if (osName.equals("Linux") && (osProc.equals("x86-64") || osProc.equals("amd64"))) { NativeLibUtil.copyFile(Serial4ThingML.class.getClassLoader().getResourceAsStream("nativelib/Linux/x86_64-unknown-linux-gnu/librxtxSerial.so"), "librxtxSerial.so"); } else if (osName.equals("Linux") && osProc.equals("ia64")) { NativeLibUtil.copyFile(Serial4ThingML.class.getClassLoader().getResourceAsStream("nativelib/Linux/ia64-unknown-linux-gnu/librxtxSerial.so"), "librxtxSerial.so"); } else if (osName.equals("Linux") && (osProc.equals("x86") || osProc.equals("i386"))) { NativeLibUtil.copyFile(Serial4ThingML.class.getClassLoader().getResourceAsStream("nativelib/Linux/i686-unknown-linux-gnu/librxtxParallel.so"), "librxtxParallel.so"); NativeLibUtil.copyFile(Serial4ThingML.class.getClassLoader().getResourceAsStream("nativelib/Linux/i686-unknown-linux-gnu/librxtxSerial.so"), "librxtxSerial.so"); } } catch (Exception e) { System.err.println("Cannot Load RxTx on " + osName + "(" + osProc + ")"); e.printStackTrace(); System.exit(1); } } /*public static final byte START_BYTE = 0x12; public static final byte STOP_BYTE = 0x13; public static final byte ESCAPE_BYTE = 0x7D;*/ protected String port; protected SerialPort serialPort; protected InputStream in; protected OutputStream out; protected org.thingml.utils.comm.SerialThingML thing; public Serial4ThingML(String port, org.thingml.utils.comm.SerialThingML thing) { this.port = selectSerialPort(port); this.thing = thing; connect(); thing.setSerial4ThingML(this); } void connect() { registerPort(port); try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(port); if (portIdentifier.isCurrentlyOwned()) { System.err.println("Error: Port " + port + " is currently in use"); } else { CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000); if (commPort instanceof SerialPort) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); in = serialPort.getInputStream(); out = serialPort.getOutputStream(); serialPort.addEventListener(new SerialReader()); serialPort.notifyOnDataAvailable(true); } else { System.err.println("Error: Port " + port + " is not a valid serial port."); } } } catch (Exception e) { e.printStackTrace(); } } public void close() { try { if (in != null) { in.close(); } if (out != null) { out.close(); } if (serialPort != null) { serialPort.notifyOnDataAvailable(false); serialPort.removeEventListener(); serialPort.close(); } } catch (Exception e) { } } /* *********************************************************************** * Serial Port data send operation *************************************************************************/ public void sendData(byte[] payload) { try { // send the start byte //out.write((int) START_BYTE); // send data for (int i = 0; i < payload.length; i++) { // escape special bytes /*if (payload[i] == START_BYTE || payload[i] == STOP_BYTE || payload[i] == ESCAPE_BYTE) { out.write((int) ESCAPE_BYTE); }*/ //System.out.println("Serial.Write[" + i + "] = " + (int) payload[i]); out.write((int) payload[i]); } // send the stop byte //out.write((int) STOP_BYTE); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* *********************************************************************** * Serial Port Listener - reads packets from the serial line and * notifies listeners of incoming packets *************************************************************************/ public class SerialReader implements SerialPortEventListener { /*public static final int RCV_WAIT = 0; public static final int RCV_MSG = 1; public static final int RCV_ESC = 2;*/ //private byte[] buffer = new byte[256]; //protected int buffer_idx = 0; //protected int state = RCV_WAIT; @Override public void serialEvent(SerialPortEvent arg0) { int data; byte[] buffer = new byte[1024]; int buffer_idx = 0; try { while ((data = in.read()) > -1) { /* System.out.println("data: " + data); // we got a byte from the serial port if (state == RCV_WAIT) { // it should be a start byte or we just ignore it /*System.out.println("WAIT"); System.out.println("data: " + data + " ?= " + START_BYTE);*/ /* if (data == START_BYTE) { state = RCV_MSG; buffer_idx = 0; buffer[buffer_idx] = (byte) data; buffer_idx++; } } else if (state == RCV_MSG) { //System.out.println("RECEIVE"); if (data == ESCAPE_BYTE) { state = RCV_ESC; } else if (data == STOP_BYTE) { buffer[buffer_idx] = (byte) data; buffer_idx++; // We got a complete frame //byte[] packet = new byte[buffer_idx]; /*for (int i = 0; i < buffer_idx; i++) { packet[i] = buffer[i]; }*/ /* System.out.println("Well-formed packet forwarded to thing"); thing.receive(java.util.Arrays.copyOf(buffer, buffer_idx)/*packet*//*); state = RCV_WAIT; } else if (data == START_BYTE) { // Should not happen but we reset just in case state = RCV_MSG; buffer_idx = 0; buffer[buffer_idx] = (byte) data; buffer_idx++; } else { // it is just a byte to store buffer[buffer_idx] = (byte) data; buffer_idx++; } } else if (state == RCV_ESC) { //System.out.println("ESCAPE"); // Store the byte without looking at it buffer[buffer_idx] = (byte) data; buffer_idx++; state = RCV_MSG; } */ //buffer_idx = 0; //System.out.println("byte[" + buffer_idx + "]" + (byte) data); buffer[buffer_idx] = (byte) data; - if (buffer[buffer_idx] == 0x13) { + if (buffer[buffer_idx] == 0x13 && buffer[buffer_idx-1] != 0x7D) { //System.out.println(" forward"); thing.receive(java.util.Arrays.copyOfRange(buffer, 0, buffer_idx + 1)); buffer_idx = 0; } else { buffer_idx++; } } } catch (IOException e) { e.printStackTrace(); } } } /* *********************************************************************** * Serial port utilities: listing *************************************************************************/ /** * @return A HashSet containing the CommPortIdentifier for all serial ports that are not currently being used. */ public static HashSet<CommPortIdentifier> getAvailableSerialPorts() { HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>(); Enumeration thePorts = CommPortIdentifier.getPortIdentifiers(); while (thePorts.hasMoreElements()) { CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement(); switch (com.getPortType()) { case CommPortIdentifier.PORT_SERIAL: try { CommPort thePort = com.open("CommUtil", 50); thePort.close(); h.add(com); } catch (PortInUseException e) { System.out.println("Port, " + com.getName() + ", is in use."); } catch (Exception e) { System.err.println("Failed to open port " + com.getName()); e.printStackTrace(); } } } return h; } public static void registerPort(String port) { String prop = System.getProperty("gnu.io.rxtx.SerialPorts"); if (prop == null) { prop = ""; } if (!prop.contains(port)) { prop += port + File.pathSeparator; System.setProperty("gnu.io.rxtx.SerialPorts", prop); } //System.out.println("gnu.io.rxtx.SerialPorts = " + prop); prop = System.getProperty("javax.comm.rxtx.SerialPorts"); if (prop == null) { prop = ""; } if (!prop.contains(port)) { prop += port + File.pathSeparator; System.setProperty("javax.comm.rxtx.SerialPorts", prop); } //System.out.println("javax.comm.rxtx.SerialPorts = " + prop); } public static String selectSerialPort(String defaultPort) { ArrayList<String> possibilities = new ArrayList<String>(); for (CommPortIdentifier commportidentifier : getAvailableSerialPorts()) { possibilities.add(commportidentifier.getName()); } int startPosition = possibilities.indexOf(defaultPort); if (startPosition == -1 && possibilities.size() > 1) { startPosition = 1; } else { startPosition = 0; } String serialPort = (String) JOptionPane.showInputDialog( null, "ThingML Serial", "Select serial port", JOptionPane.PLAIN_MESSAGE, null, possibilities.toArray(), possibilities.toArray()[startPosition]); if (serialPort == null) { serialPort = (String) JOptionPane.showInputDialog( null, "ThingML Serial", "Enter serial port", JOptionPane.PLAIN_MESSAGE, null, null, null); } return serialPort; } }
true
true
public void serialEvent(SerialPortEvent arg0) { int data; byte[] buffer = new byte[1024]; int buffer_idx = 0; try { while ((data = in.read()) > -1) { /* System.out.println("data: " + data); // we got a byte from the serial port if (state == RCV_WAIT) { // it should be a start byte or we just ignore it /*System.out.println("WAIT"); System.out.println("data: " + data + " ?= " + START_BYTE);*/ /* if (data == START_BYTE) { state = RCV_MSG; buffer_idx = 0; buffer[buffer_idx] = (byte) data; buffer_idx++; } } else if (state == RCV_MSG) { //System.out.println("RECEIVE"); if (data == ESCAPE_BYTE) { state = RCV_ESC; } else if (data == STOP_BYTE) { buffer[buffer_idx] = (byte) data; buffer_idx++; // We got a complete frame //byte[] packet = new byte[buffer_idx]; /*for (int i = 0; i < buffer_idx; i++) { packet[i] = buffer[i]; }*/ /* System.out.println("Well-formed packet forwarded to thing"); thing.receive(java.util.Arrays.copyOf(buffer, buffer_idx)/*packet*//*); state = RCV_WAIT; } else if (data == START_BYTE) { // Should not happen but we reset just in case state = RCV_MSG; buffer_idx = 0; buffer[buffer_idx] = (byte) data; buffer_idx++; } else { // it is just a byte to store buffer[buffer_idx] = (byte) data; buffer_idx++; } } else if (state == RCV_ESC) { //System.out.println("ESCAPE"); // Store the byte without looking at it buffer[buffer_idx] = (byte) data; buffer_idx++; state = RCV_MSG; } */ //buffer_idx = 0; //System.out.println("byte[" + buffer_idx + "]" + (byte) data); buffer[buffer_idx] = (byte) data; if (buffer[buffer_idx] == 0x13) { //System.out.println(" forward"); thing.receive(java.util.Arrays.copyOfRange(buffer, 0, buffer_idx + 1)); buffer_idx = 0; } else { buffer_idx++; } }
public void serialEvent(SerialPortEvent arg0) { int data; byte[] buffer = new byte[1024]; int buffer_idx = 0; try { while ((data = in.read()) > -1) { /* System.out.println("data: " + data); // we got a byte from the serial port if (state == RCV_WAIT) { // it should be a start byte or we just ignore it /*System.out.println("WAIT"); System.out.println("data: " + data + " ?= " + START_BYTE);*/ /* if (data == START_BYTE) { state = RCV_MSG; buffer_idx = 0; buffer[buffer_idx] = (byte) data; buffer_idx++; } } else if (state == RCV_MSG) { //System.out.println("RECEIVE"); if (data == ESCAPE_BYTE) { state = RCV_ESC; } else if (data == STOP_BYTE) { buffer[buffer_idx] = (byte) data; buffer_idx++; // We got a complete frame //byte[] packet = new byte[buffer_idx]; /*for (int i = 0; i < buffer_idx; i++) { packet[i] = buffer[i]; }*/ /* System.out.println("Well-formed packet forwarded to thing"); thing.receive(java.util.Arrays.copyOf(buffer, buffer_idx)/*packet*//*); state = RCV_WAIT; } else if (data == START_BYTE) { // Should not happen but we reset just in case state = RCV_MSG; buffer_idx = 0; buffer[buffer_idx] = (byte) data; buffer_idx++; } else { // it is just a byte to store buffer[buffer_idx] = (byte) data; buffer_idx++; } } else if (state == RCV_ESC) { //System.out.println("ESCAPE"); // Store the byte without looking at it buffer[buffer_idx] = (byte) data; buffer_idx++; state = RCV_MSG; } */ //buffer_idx = 0; //System.out.println("byte[" + buffer_idx + "]" + (byte) data); buffer[buffer_idx] = (byte) data; if (buffer[buffer_idx] == 0x13 && buffer[buffer_idx-1] != 0x7D) { //System.out.println(" forward"); thing.receive(java.util.Arrays.copyOfRange(buffer, 0, buffer_idx + 1)); buffer_idx = 0; } else { buffer_idx++; } }
diff --git a/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java b/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java index 7124b4fde..58658dfd3 100644 --- a/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java +++ b/mifos/src/org/mifos/application/customer/util/helpers/CustomerHelper.java @@ -1,855 +1,856 @@ /** * CustomerHelper.java version: 1.0 * Copyright (c) 2005-2006 Grameen Foundation USA * 1029 Vermont Avenue, NW, Suite 400, Washington DC 20005 * All rights reserved. * Apache License * Copyright (c) 2005-2006 Grameen Foundation USA * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the * License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an explanation of the license * and how it is applied. * */ package org.mifos.application.customer.util.helpers; import java.sql.Date; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Set; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.mifos.application.NamedQueryConstants; import org.mifos.application.accounts.util.valueobjects.AccountActionDate; import org.mifos.application.accounts.util.valueobjects.AccountFees; import org.mifos.application.accounts.util.valueobjects.AccountFeesActionDetail; import org.mifos.application.accounts.util.valueobjects.CustomerAccount; import org.mifos.application.configuration.business.ConfigurationIntf; import org.mifos.application.configuration.business.MifosConfiguration; import org.mifos.application.configuration.util.helpers.ConfigurationConstants; import org.mifos.application.customer.center.util.helpers.CenterConstants; import org.mifos.application.customer.center.util.helpers.ValidateMethods; import org.mifos.application.customer.center.util.valueobjects.Center; import org.mifos.application.customer.client.util.valueobjects.Client; import org.mifos.application.customer.dao.CustomerNoteDAO; import org.mifos.application.customer.dao.CustomerUtilDAO; import org.mifos.application.customer.exceptions.CustomerException; import org.mifos.application.customer.group.util.helpers.GroupConstants; import org.mifos.application.customer.group.util.valueobjects.Group; import org.mifos.application.customer.util.valueobjects.Customer; import org.mifos.application.customer.util.valueobjects.CustomerAddressDetail; import org.mifos.application.customer.util.valueobjects.CustomerHierarchy; import org.mifos.application.customer.util.valueobjects.CustomerMeeting; import org.mifos.application.customer.util.valueobjects.CustomerMovement; import org.mifos.application.customer.util.valueobjects.CustomerNote; import org.mifos.application.customer.util.valueobjects.CustomerPosition; import org.mifos.application.customer.util.valueobjects.CustomerPositionDisplay; import org.mifos.application.fees.util.valueobjects.FeeFrequency; import org.mifos.application.fees.util.valueobjects.FeeMaster; import org.mifos.application.fees.util.valueobjects.Fees; import org.mifos.application.master.util.valueobjects.PositionMaster; import org.mifos.application.master.util.valueobjects.StatusMaster; import org.mifos.application.meeting.util.valueobjects.Meeting; import org.mifos.application.personnel.dao.PersonnelDAO; import org.mifos.application.personnel.util.valueobjects.Personnel; import org.mifos.application.personnel.util.valueobjects.PersonnelMaster; import org.mifos.framework.components.configuration.business.Configuration; import org.mifos.framework.components.repaymentschedule.RepaymentSchedule; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleConstansts; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleFactory; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleHelper; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleIfc; import org.mifos.framework.components.repaymentschedule.RepaymentScheduleInputsIfc; import org.mifos.framework.dao.helpers.MasterDataRetriever; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.HibernateProcessException; import org.mifos.framework.exceptions.SystemException; import org.mifos.framework.hibernate.helper.HibernateUtil; import org.mifos.framework.security.util.UserContext; import org.mifos.framework.struts.tags.DateHelper; import org.mifos.framework.util.valueobjects.Context; import org.mifos.framework.util.valueobjects.SearchResults; /** * This class is a helper class to customer (i.e. client/group/center). * This includes commom methods for customer that can be used by client,group or center. * @author navitas */ public class CustomerHelper { private ConfigurationIntf labelConfig=MifosConfiguration.getInstance(); public Date getCurrentDate(){ return new java.sql.Date(new java.util.Date().getTime()); } /** * This method creates a new customer movement object. * @return instance of CustomerMovement */ public CustomerMovement createCustomerMovement(Customer customer, Date startDate, short status, short userId)throws ApplicationException,SystemException{ CustomerMovement movement = new CustomerMovement(); movement.setCustomer(customer); if(startDate!=null) movement.setStartDate(startDate); else movement.setStartDate(new Date(new java.util.Date().getTime())); movement.setStatus(status); movement.setEndDate(null); movement.setOffice(customer.getOffice()); movement.setPersonnel(new PersonnelDAO().getUser(userId)); return movement; } /** * This method retrieves the list of programs that can be assigned to the group * @return The list of programs * @throws ApplicationException * @throws SystemException */ public SearchResults getProgramMaster(short localeId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_PROGRAM, GroupConstants.PROGRAMS_SET); masterDataRetriever.setParameter("localeId",localeId); return masterDataRetriever.retrieve(); } /** * This method return the count of customers in a office * @param officeId * @return customer count * @throws ApplicationException * @throws SystemException */ public int getCustomerCountInOffice(short officeId) throws ApplicationException,SystemException { Integer count ; Session session = null; try{ session = HibernateUtil.getSession(); Transaction trxn = session.beginTransaction(); Query query = session.createQuery("select count(*) from org.mifos.application.customer.util.valueobjects.Customer customer where customer.office.officeId =:OFFICEID"); query.setShort("OFFICEID", officeId); count = (Integer)query.uniqueResult(); trxn.commit(); return count; }catch(HibernateProcessException hpe){ throw hpe; }finally{ HibernateUtil.closeSession(session); } } /** * This method returns the count of customers based on given level * @param levelId * @return customer count * @throws ApplicationException * @throws SystemException */ public int getCustomerCount(short levelId,short officeId)throws ApplicationException,SystemException{ Integer count ; Session session = null; try{ session = HibernateUtil.getSession(); Query query = session.createQuery("select count(*) from org.mifos.application.customer.util.valueobjects.Customer customer where customer.customerLevel.levelId =:LEVELID and customer.office.officeId=:OFFICEID"); query.setShort("LEVELID", levelId); query.setShort("OFFICEID", officeId); count = (Integer)query.uniqueResult(); return count; }catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); }finally{ HibernateUtil.closeSession(session); } } /** * This method returns the name of status configured for a level in the given locale * @param localeId user locale * @param statusId status id * @param levelId customer level * @return string status name * @throws ApplicationException * @throws SystemException */ public String getStatusName(short localeId, short statusId,short levelId)throws ApplicationException,SystemException{ String statusName=null; List<StatusMaster> statusList =(List) new CustomerHelper().getStatusMaster(localeId,statusId,levelId).getValue(); if(statusList!=null){ StatusMaster sm = (StatusMaster)statusList.get(0); statusName= sm.getStatusName(); } return statusName; } /** * This method returns the name of flag * @param flagId customer flag * @param localeId user locale * @return string flag name * @throws ApplicationException * @throws SystemException */ public String getFlagName(short flagId,short localeId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_GET_FLAGNAME, GroupConstants.CURRENT_FLAG); masterDataRetriever.setParameter("flagId",flagId); masterDataRetriever.setParameter("localeId",localeId); SearchResults sr = masterDataRetriever.retrieve(); return (String)((List)sr.getValue()).get(0); } /** * This method tells whether a given flag for the given status is blacklisted or not * @param flagId customer flag * @return true if flag is blacklisted, otherwise false * @throws ApplicationException * @throws SystemException */ public boolean isBlacklisted(short flagId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_IS_BLACKLISTED, GroupConstants.IS_BLACKLISTED); masterDataRetriever.setParameter("flagId",flagId); SearchResults sr = masterDataRetriever.retrieve(); return ((Short)((List)sr.getValue()).get(0)).shortValue()==1?true:false; } /** * This method returns the list of next available status * to which a customer can move as per the customer state flow diagram * @param localeId user locale * @param statusId status id * @param levelId customer level * @return List next applicable status list * @throws ApplicationException * @throws SystemException */ public List getStatusList(short localeId, short status, short levelId, short branchId)throws ApplicationException,SystemException{ List<StatusMaster> statusList = new ArrayList<StatusMaster>(); switch (status){ case GroupConstants.PARTIAL_APPLICATION : if(Configuration.getInstance().getCustomerConfig(branchId).isPendingApprovalStateDefinedForGroup()) statusList.add(getStatusWithFlags(localeId,GroupConstants.PENDING_APPROVAL,levelId)); else statusList.add(getStatusWithFlags(localeId,GroupConstants.ACTIVE, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CANCELLED, levelId)); break; case GroupConstants.PENDING_APPROVAL: statusList.add(getStatusWithFlags(localeId,GroupConstants.PARTIAL_APPLICATION, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.ACTIVE, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CANCELLED, levelId)); break; case GroupConstants.ACTIVE: statusList.add(getStatusWithFlags(localeId,GroupConstants.HOLD, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CLOSED, levelId)); break; case GroupConstants.HOLD: statusList.add(getStatusWithFlags(localeId,GroupConstants.ACTIVE, levelId)); statusList.add(getStatusWithFlags(localeId,GroupConstants.CLOSED, levelId)); break; case GroupConstants.CANCELLED: statusList.add(getStatusWithFlags(localeId,GroupConstants.PARTIAL_APPLICATION, levelId)); default: } return statusList; } /** * This method returns flag list associated with passed in status Id * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults flag list * @throws ApplicationException * @throws SystemException */ public SearchResults getStatusFlags(short localeId , short statusId , short levelId)throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_SPECIFIC_STATUS_FLAG, GroupConstants.STATUS_FLAG); masterDataRetriever.setParameter("localeId" ,localeId ); masterDataRetriever.setParameter("levelId",levelId); masterDataRetriever.setParameter("specificStatusId",statusId); return masterDataRetriever.retrieve(); } /** * This method returns list of all available status for a level * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults status list * @throws ApplicationException * @throws SystemException */ public SearchResults getStatusMaster(short localeId , short statusId, short levelId )throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_SPECIFIC_STATUS, GroupConstants.STATUS); masterDataRetriever.setParameter("localeId" ,localeId ); masterDataRetriever.setParameter("levelId",levelId); masterDataRetriever.setParameter("specificStatusId",statusId); return masterDataRetriever.retrieve(); } /** * This method is the helper method that returns a status along with its assoicated flags * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults status list * @throws ApplicationException * @throws SystemException */ private StatusMaster getStatusWithFlags(short locale, short status, short levelId) throws ApplicationException,SystemException{ SearchResults sr = this.getStatusMaster(locale,status, levelId); StatusMaster statusMaster = null; Object obj = sr.getValue(); if(obj!=null){ statusMaster = (StatusMaster)((List)obj).get(0); sr = this.getStatusFlags(locale,status, levelId); obj=sr.getValue(); if(obj!=null){ statusMaster.setFlagList((List)obj); } else{ statusMaster.setFlagList(null); } } return statusMaster; } /** * This method returns List given number of notes for a given customer * @param count number of notes to be returned * @return customerId for which notes has to be retrieved * @throws ApplicationException * @throws SystemException */ public List<CustomerNote> getLatestNotes(int count, Integer customerId)throws ApplicationException,SystemException{ CustomerNoteDAO notesDAO = new CustomerNoteDAO(); return notesDAO.getLatestNotesByCount(count, customerId); } /** * This method is used to retrieve MasterDataRetriver instance * @return instance of MasterDataRetriever * @throws HibernateProcessException */ public MasterDataRetriever getMasterDataRetriever()throws HibernateProcessException{ return new MasterDataRetriever(); } /** * This method returns list of all available status for a level * @param localeId user locale * @param statusId status id * @param levelId customer level * @return SearchResults status list * @throws ApplicationException * @throws SystemException */ public SearchResults getStatusForLevel(short localeId , short levelId )throws ApplicationException,SystemException{ MasterDataRetriever masterDataRetriever = null; try{ masterDataRetriever = getMasterDataRetriever(); } catch(HibernateProcessException hpe){ throw new ApplicationException(hpe); } masterDataRetriever.prepare(NamedQueryConstants.MASTERDATA_STATUS, GroupConstants.STATUS_LIST); masterDataRetriever.setParameter("localeId" ,localeId ); masterDataRetriever.setParameter("levelId",levelId); return masterDataRetriever.retrieve(); } /*** * This method converts the valueobject to reflect the changes being done on a edit of MFI information. * @param oldClient The details retrieved from the database * @param newClient The MFI details which would ahve been edited * @return */ public Client convertOldClientMFIDetails(Client oldClient , Client newClient){ oldClient.setExternalId(newClient.getExternalId()); oldClient.setTrained(newClient.getTrained()); oldClient.setTrainedDate(newClient.getTrainedDate()); oldClient.setClientConfidential(newClient.getClientConfidential()); oldClient.setCustomerFormedByPersonnel(newClient.getCustomerFormedByPersonnel()); //oldClient.setPersonnel(newClient.getPersonnel()); return oldClient; } /** * This method creates a new customer hierarchy object. It is called whenever a new group is created with * center as its parent or group parent is changed. * @return instance of CustomerHierarchy */ public CustomerHierarchy createCustomerHierarchy(Customer parent, Customer child, Context context){ CustomerHierarchy customerHierarchy = new CustomerHierarchy(); customerHierarchy.setCustomer(child); customerHierarchy.setParentCustomer(parent); customerHierarchy.setStatus(CustomerConstants.ACTIVE_HIERARCHY); customerHierarchy.setEndDate(new java.sql.Date(new java.util.Date().getTime())); customerHierarchy.setStartDate(new java.sql.Date(new java.util.Date().getTime())); customerHierarchy.setUpdatedBy(context.getUserContext().getId()); customerHierarchy.setUpdatedDate(new java.sql.Date(new java.util.Date().getTime())); return customerHierarchy; } /** * This method creates a new customer hierarchy object. It is called whenever a new group is created with * center as its parent or group parent is changed. * @return instance of CustomerHierarchy */ public CustomerMovement createCustomerMovement(Customer customer , Date startDate){ CustomerMovement customerMovement = new CustomerMovement(); customerMovement.setCustomer(customer); customerMovement.setStatus(CustomerConstants.ACTIVE_HIERARCHY); customerMovement.setStartDate(startDate); customerMovement.setOffice(customer.getOffice()); customerMovement.setPersonnel(customer.getPersonnel()); return customerMovement; } /** * This method creates a new SearchResults object with values as passed in parameters * @param resultName the name with which framework will put resultvalue in request * @param resultValue that need to be put in request * @return SearchResults instance */ public SearchResults getResultObject(String resultName, Object resultValue){ SearchResults result = new SearchResults(); result.setResultName(resultName); result.setValue(resultValue); return result; } /*** * Concatenates all the names together * @param firstName * @param middleName * @param secondLastName * @param lastName * @return */ public String setDisplayNames(String firstName, String middleName, String secondLastName, String lastName) { StringBuilder displayName = new StringBuilder(); displayName.append(firstName); if(!ValidateMethods.isNullOrBlank(middleName)){ displayName.append(CustomerConstants.BLANK); displayName.append(middleName ); } if(!ValidateMethods.isNullOrBlank(secondLastName)){ displayName.append(CustomerConstants.BLANK); displayName.append(secondLastName); } if(!ValidateMethods.isNullOrBlank(lastName)){ displayName.append(CustomerConstants.BLANK); displayName.append(lastName); } return displayName.toString().trim(); } /** * This method is helper method that sets the personnel age in request * @param request Contains the request parameters */ public int calculateAge(Date date){ int age = DateHelper.DateDiffInYears(date); return age; } /** * Generates the ID for the client using ID Generator. * @return * @throws SystemException * @throws ApplicationException */ public String generateSystemId(Short officeId , String officeGlobalNum)throws SystemException,ApplicationException{ int maxCustomerId = 0; maxCustomerId = new CustomerUtilDAO().getMaxCustomerId(officeId); String systemId = IdGenerator.generateSystemId(officeGlobalNum , maxCustomerId); return systemId; } /** * This is the helper method to check for extra date validations needed at the time of create preview * @param personnelStatus */ public boolean isValidDOB(String dob ,Locale mfiLocale){ java.sql.Date sqlDOB=null; boolean isValidDate = true; if(!ValidateMethods.isNullOrBlank(dob)) { sqlDOB=DateHelper.getLocaleDate(mfiLocale,dob); Calendar currentCalendar = new GregorianCalendar(); int year=currentCalendar.get(Calendar.YEAR); int month=currentCalendar.get(Calendar.MONTH); int day=currentCalendar.get(Calendar.DAY_OF_MONTH); currentCalendar = new GregorianCalendar(year,month,day); java.sql.Date currentDate=new java.sql.Date(currentCalendar.getTimeInMillis()); if(currentDate.compareTo(sqlDOB) < 0 ) { isValidDate= false; } } return isValidDate; } /** * This method concatenates differnt address lines and forms one line of address * @param addressDetails CustomerAddressDetail * @return string single line address */ public String getDisplayAddress(CustomerAddressDetail addressDetails){ String displayAddress=""; if(!isNullOrBlank(addressDetails.getLine1())){ displayAddress+=addressDetails.getLine1(); } if(!isNullOrBlank(addressDetails.getLine2())&&!isNullOrBlank(addressDetails.getLine1())){ displayAddress+=", "+ addressDetails.getLine2(); } else if(!isNullOrBlank(addressDetails.getLine2())){ displayAddress+=addressDetails.getLine2(); } if(!isNullOrBlank(addressDetails.getLine3())&&!isNullOrBlank(addressDetails.getLine2())||(!isNullOrBlank(addressDetails.getLine3())&&!isNullOrBlank(addressDetails.getLine1()))){ displayAddress+=", "+ addressDetails.getLine3(); } else if(!isNullOrBlank(addressDetails.getLine3())){ displayAddress+=addressDetails.getLine3(); } return displayAddress; } /*** * This method checks if a particuar value is either null or blank * @param value the value that has to be checked as to whether it is null or blank * @return true or false as to whether the value passed was null or blank */ public static boolean isNullOrBlank(String value){ boolean isValueNull = false; if(value == null || value.trim().equals(CenterConstants.BLANK)){ isValueNull = true; } return isValueNull; } public void saveMeetingDetails(Customer customer,Session session, UserContext userContext) throws ApplicationException,SystemException { Meeting meeting =null ; Set<AccountFees> accountFeesSet=new HashSet(); CustomerMeeting customerMeeting =null; customerMeeting = customer.getCustomerMeeting(); // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting && customer.getPersonnel()!=null){ meeting = customerMeeting.getMeeting(); try { CustomerAccount customerAccount=customer.getCustomerAccount(); if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); if(accountFeesSet !=null&& accountFeesSet.size()>0){ for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount().getAmountDoubleValue()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } } } //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); - if(accountFeesSet!=null) + if(accountFeesSet!=null && !accountFeesSet.isEmpty()) repaymntScheduleInputs.setAccountFee(accountFeesSet); else repaymntScheduleInputs.setAccountFee(new HashSet()); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. Short state=customer.getStatusId(); if(state.equals(CustomerConstants.CENTER_ACTIVE_STATE) || state.equals(CustomerConstants.GROUP_ACTIVE_STATE) || state.equals(GroupConstants.HOLD) || state.equals(CustomerConstants.CLIENT_APPROVED) || state.equals(CustomerConstants.CLIENT_ONHOLD)){ for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); } }else{ - for(AccountFees accountFees : accountFeesSet){ - accountFees.setLastAppliedDate(null); - } + if(accountFeesSet!=null && !accountFeesSet.isEmpty()) + for(AccountFees accountFees : accountFeesSet){ + accountFees.setLastAppliedDate(null); + } Iterator<AccountActionDate> accActionDateItr=accntActionDateSet.iterator(); while(accActionDateItr.hasNext()){ AccountActionDate accountActionDate=accActionDateItr.next(); accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); accountActionDate.setAccountFeesActionDetail(null); } } customer.getCustomerAccount().setAccountActionDateSet(accntActionDateSet); } }catch (Exception hpe) { String messageArgumentKey =null; if(customer instanceof Client)messageArgumentKey=ConfigurationConstants.CLIENT; else if (customer instanceof Group )messageArgumentKey=ConfigurationConstants.GROUP; else if (customer instanceof Center )messageArgumentKey=ConfigurationConstants.CENTER; throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe,new Object[]{labelConfig.getLabel(messageArgumentKey,userContext.getPereferedLocale())}); } } } public void attachMeetingDetails(Customer customer,Session session,CustomerMeeting customerMeeting) throws ApplicationException,SystemException { //Customer customer = (Customer)context.getValueObject(); Meeting meeting =null ; // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting){ meeting = customerMeeting.getMeeting(); // Session session = null; //Transaction trxn = null; try { //session = HibernateUtil.getSession(); //trxn = session.beginTransaction(); /* Customer vo = (Customer)session.get(Customer.class,customer.getCustomerId()); if(vo.getCustomerAccounts()!=null){ Iterator accountsIterator = vo.getCustomerAccounts().iterator(); while(accountsIterator.hasNext()){ Account account = (Account)accountsIterator.next(); if(account.getAccountTypeId().shortValue()== new Short(AccountTypes.CUSTOMERACCOUNT).shortValue()){ vo.setCustomerAccount((CustomerAccount)account); break; } } } CustomerAccount customerAccount=vo.getCustomerAccount(); Set<AccountFees> accountFeesSet=null; if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); // System.out.println("In Account Fees-----@@@@^^^^^^^^^&&&&&&&&&&**************" + "**********#################!!!!!!!!!!------"+accountFeesSet.size()); for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } }*/ //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); //repaymntScheduleInputs.setAccountFee(accountFeesSet); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //context.addAttribute(new SearchResults("AccountActionDate",accntActionDateSet)); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); session.save(accountActionDate); } } //trxn.commit(); }catch (Exception hpe) { throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe); } } } /** * This method returns true if there is any accountFee with null or zero amnt. * it checks if the fees id is not null , then amount should not be null. * @return true or false */ public boolean isAnyAccountFeesWithoutAmnt(List<FeeMaster> adminFeeList , List<FeeMaster> selectedFeeList ) { //check if any administrative fee amount is null if(null!=adminFeeList && adminFeeList.size()>0){ for(int index=0;index<adminFeeList.size();index++ ){ if(adminFeeList.get(index).getCheckedFee()==null ||(adminFeeList.get(index).getCheckedFee()!=null &&adminFeeList.get(index).getCheckedFee().shortValue()!=1)){ if (adminFeeList.get(index).getRateOrAmount()==null ||adminFeeList.get(index).getRateOrAmount()==0.0){ return true; } } } } //check if any additional fee amount is null if(null!=selectedFeeList && selectedFeeList.size()>0){ for(int index=0;index<selectedFeeList.size();index++ ){ if(selectedFeeList.get(index).getFeeId()!=null && selectedFeeList.get(index).getFeeId().shortValue()!=0 ){ if (selectedFeeList.get(index).getRateOrAmount()==null ||selectedFeeList.get(index).getRateOrAmount()==0.0){ return true; } } } } return false; } /** * This method prepares a list of CustomerPositionDisplay that tells which position is assigned to which customer. * @param group * @return List of CustomerPositionDisplay * @throws ApplicationExcpetion * @throws SystemExcpetion */ public List loadCustomerPositions(Customer customer, short localeId,List positionMaster)throws ApplicationException,SystemException{ List<CustomerPositionDisplay> customerPositions = new ArrayList<CustomerPositionDisplay>(); //SearchResults sr = new GroupHelper().getPositionsMaster(localeId); //List positionMaster =(List) sr.getValue(); Set positionsSet = customer.getCustomerPositions(); if(positionMaster!=null && positionsSet!=null){ PositionMaster pm=null; CustomerPosition cp=null; CustomerPositionDisplay cpdisplay=null; Iterator posMaster=positionMaster.iterator(); Iterator custPos=null; while(posMaster.hasNext()){ pm=(PositionMaster)posMaster.next(); cpdisplay = new CustomerPositionDisplay(); cpdisplay.setPositionId(pm.getPositionId()); cpdisplay.setPositionName(pm.getPositionName()); custPos=positionsSet.iterator(); while(custPos.hasNext()){ cp=(CustomerPosition)custPos.next(); if(cp.getPositionId().intValue()==pm.getPositionId().intValue()){ cpdisplay.setCustomerName(cp.getCustomerName()); cpdisplay.setCustomerId(cp.getCustomerId()); } } customerPositions.add(cpdisplay); } } return customerPositions; } public Personnel getFormedByLO(Context context, short personnelId) { Personnel loanOfficer = new Personnel(); Iterator iteratorLO=((List)context.getSearchResultBasedOnName(CustomerConstants.FORMEDBY_LOAN_OFFICER_LIST).getValue()).iterator(); //Obtaining the name of the selected loan officer from the master list of loan officers while (iteratorLO.hasNext()){ PersonnelMaster lo=(PersonnelMaster)iteratorLO.next(); if(lo.getPersonnelId().shortValue()==personnelId){ loanOfficer.setPersonnelId(lo.getPersonnelId()); loanOfficer.setDisplayName(lo.getDisplayName()); loanOfficer.setVersionNo(lo.getVersionNo()); } } return loanOfficer; } }
false
true
public void saveMeetingDetails(Customer customer,Session session, UserContext userContext) throws ApplicationException,SystemException { Meeting meeting =null ; Set<AccountFees> accountFeesSet=new HashSet(); CustomerMeeting customerMeeting =null; customerMeeting = customer.getCustomerMeeting(); // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting && customer.getPersonnel()!=null){ meeting = customerMeeting.getMeeting(); try { CustomerAccount customerAccount=customer.getCustomerAccount(); if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); if(accountFeesSet !=null&& accountFeesSet.size()>0){ for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount().getAmountDoubleValue()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } } } //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); if(accountFeesSet!=null) repaymntScheduleInputs.setAccountFee(accountFeesSet); else repaymntScheduleInputs.setAccountFee(new HashSet()); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. Short state=customer.getStatusId(); if(state.equals(CustomerConstants.CENTER_ACTIVE_STATE) || state.equals(CustomerConstants.GROUP_ACTIVE_STATE) || state.equals(GroupConstants.HOLD) || state.equals(CustomerConstants.CLIENT_APPROVED) || state.equals(CustomerConstants.CLIENT_ONHOLD)){ for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); } }else{ for(AccountFees accountFees : accountFeesSet){ accountFees.setLastAppliedDate(null); } Iterator<AccountActionDate> accActionDateItr=accntActionDateSet.iterator(); while(accActionDateItr.hasNext()){ AccountActionDate accountActionDate=accActionDateItr.next(); accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); accountActionDate.setAccountFeesActionDetail(null); } } customer.getCustomerAccount().setAccountActionDateSet(accntActionDateSet); } }catch (Exception hpe) { String messageArgumentKey =null; if(customer instanceof Client)messageArgumentKey=ConfigurationConstants.CLIENT; else if (customer instanceof Group )messageArgumentKey=ConfigurationConstants.GROUP; else if (customer instanceof Center )messageArgumentKey=ConfigurationConstants.CENTER; throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe,new Object[]{labelConfig.getLabel(messageArgumentKey,userContext.getPereferedLocale())}); } } }
public void saveMeetingDetails(Customer customer,Session session, UserContext userContext) throws ApplicationException,SystemException { Meeting meeting =null ; Set<AccountFees> accountFeesSet=new HashSet(); CustomerMeeting customerMeeting =null; customerMeeting = customer.getCustomerMeeting(); // only if customer meeting is not null get the meeting from customer meeting // this could be null if customer does not have a customer meeting. if(null != customerMeeting && customer.getPersonnel()!=null){ meeting = customerMeeting.getMeeting(); try { CustomerAccount customerAccount=customer.getCustomerAccount(); if(null != customerAccount) { accountFeesSet=customerAccount.getAccountFeesSet(); if(accountFeesSet !=null&& accountFeesSet.size()>0){ for(AccountFees accountFees:accountFeesSet) { Fees fees=(Fees)session.get(Fees.class,accountFees.getFees().getFeeId()); FeeFrequency feeFrequency=fees.getFeeFrequency(); if(null !=feeFrequency) { feeFrequency.getFeeFrequencyId(); feeFrequency.getFeeFrequencyTypeId(); } accountFees.setFeeAmount(accountFees.getAccountFeeAmount().getAmountDoubleValue()); accountFees.getFees().setRateFlatFalg(fees.getRateFlatFalg()); accountFees.getFees().setFeeFrequency(feeFrequency); } } } //get the repayment schedule input object which would be passed to repayment schedule generator RepaymentScheduleInputsIfc repaymntScheduleInputs = RepaymentScheduleFactory.getRepaymentScheduleInputs(); RepaymentScheduleIfc repaymentScheduler = RepaymentScheduleFactory.getRepaymentScheduler(); //set the customer'sMeeting , this is required to check if the disbursement date is valid // this would be null if customer does not have a meeting. repaymntScheduleInputs.setMeeting(meeting); repaymntScheduleInputs.setMeetingToConsider(RepaymentScheduleConstansts.MEETING_CUSTOMER); // set the loan disburesment date onto the repayment frequency repaymntScheduleInputs.setRepaymentFrequency(meeting); if(accountFeesSet!=null && !accountFeesSet.isEmpty()) repaymntScheduleInputs.setAccountFee(accountFeesSet); else repaymntScheduleInputs.setAccountFee(new HashSet()); // this method invokes the repayment schedule generator. repaymentScheduler.setRepaymentScheduleInputs(repaymntScheduleInputs); RepaymentSchedule repaymentSchedule = repaymentScheduler.getRepaymentSchedule(); Set<AccountActionDate> accntActionDateSet = RepaymentScheduleHelper.getActionDateValueObject(repaymentSchedule); //this will insert records in account action date which is noting but installments. if(null != accntActionDateSet && ! accntActionDateSet.isEmpty()){ // iterate over account action date set and set the relation ship. Short state=customer.getStatusId(); if(state.equals(CustomerConstants.CENTER_ACTIVE_STATE) || state.equals(CustomerConstants.GROUP_ACTIVE_STATE) || state.equals(GroupConstants.HOLD) || state.equals(CustomerConstants.CLIENT_APPROVED) || state.equals(CustomerConstants.CLIENT_ONHOLD)){ for(AccountActionDate accountActionDate : accntActionDateSet){ accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); } }else{ if(accountFeesSet!=null && !accountFeesSet.isEmpty()) for(AccountFees accountFees : accountFeesSet){ accountFees.setLastAppliedDate(null); } Iterator<AccountActionDate> accActionDateItr=accntActionDateSet.iterator(); while(accActionDateItr.hasNext()){ AccountActionDate accountActionDate=accActionDateItr.next(); accountActionDate.setAccount(customer.getCustomerAccount()); accountActionDate.setCustomerId(customer.getCustomerId()); accountActionDate.setCurrencyId(Short.valueOf("1")); accountActionDate.setAccountFeesActionDetail(null); } } customer.getCustomerAccount().setAccountActionDateSet(accntActionDateSet); } }catch (Exception hpe) { String messageArgumentKey =null; if(customer instanceof Client)messageArgumentKey=ConfigurationConstants.CLIENT; else if (customer instanceof Group )messageArgumentKey=ConfigurationConstants.GROUP; else if (customer instanceof Center )messageArgumentKey=ConfigurationConstants.CENTER; throw new CustomerException(CustomerConstants.CREATE_FAILED_EXCEPTION ,hpe,new Object[]{labelConfig.getLabel(messageArgumentKey,userContext.getPereferedLocale())}); } } }
diff --git a/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/HeaderPanel.java b/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/HeaderPanel.java index b5a2daeb4..9317500f3 100755 --- a/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/HeaderPanel.java +++ b/modules/foundation/appbase/src/classes/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/HeaderPanel.java @@ -1,323 +1,323 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.appbase.client.cell.view.viewdefault; import java.awt.Color; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.ImageIcon; import javax.swing.SwingUtilities; /** * * @author dj */ public class HeaderPanel extends javax.swing.JPanel { public interface Container { // TODO: add call backs to FrameHeaderSwing public void close(); public void toggleHUD(); } private Container container; private static ImageIcon onHUDImage; private static ImageIcon offHUDImage; public void setContainer(Container container) { this.container = container; } /** Creates new form HeaderPanel */ public HeaderPanel() { initComponents(); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); hudButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { hudButtonActionPerformed(evt); } }); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jToolBar1 = new javax.swing.JToolBar(); appLabel = new javax.swing.JLabel(); controllerLabel = new javax.swing.JLabel(); closeButton = new javax.swing.JButton(); hudButton = new javax.swing.JButton(); jToolBar1.setRollover(true); setMaximumSize(new java.awt.Dimension(32767, 24)); setMinimumSize(new java.awt.Dimension(50, 24)); setPreferredSize(new java.awt.Dimension(422, 24)); appLabel.setFont(appLabel.getFont().deriveFont(appLabel.getFont().getStyle() | java.awt.Font.BOLD, appLabel.getFont().getSize()+2)); appLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/appbase/client/Bundle"); // NOI18N appLabel.setText(bundle.getString("HeaderPanel.appLabel.text")); // NOI18N controllerLabel.setFont(controllerLabel.getFont().deriveFont(controllerLabel.getFont().getStyle() | java.awt.Font.BOLD, controllerLabel.getFont().getSize()+2)); controllerLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); controllerLabel.setText(bundle.getString("HeaderPanel.controllerLabel.text")); // NOI18N - closeButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N + closeButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/window-close24x24.png"))); // NOI18N closeButton.setMaximumSize(new java.awt.Dimension(24, 24)); closeButton.setMinimumSize(new java.awt.Dimension(24, 24)); closeButton.setPreferredSize(new java.awt.Dimension(24, 24)); closeButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/window-close24x24.png"))); // NOI18N - hudButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N + hudButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); hudButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/dock24x24.png"))); // NOI18N hudButton.setMaximumSize(new java.awt.Dimension(24, 24)); hudButton.setMinimumSize(new java.awt.Dimension(24, 24)); hudButton.setPreferredSize(new java.awt.Dimension(24, 24)); hudButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/dock24x24.png"))); // NOI18N org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() - .add(appLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 226, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) + .add(appLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) - .add(controllerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 124, Short.MAX_VALUE) + .add(controllerLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(hudButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(3, 3, 3) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(appLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(controllerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(hudButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel appLabel; private javax.swing.JButton closeButton; private javax.swing.JLabel controllerLabel; private javax.swing.JButton hudButton; private javax.swing.JToolBar jToolBar1; // End of variables declaration//GEN-END:variables @Override public void setBackground(final Color color) { SwingUtilities.invokeLater(new Runnable() { public void run() { HeaderPanel.super.setBackground(color); if (appLabel != null) { appLabel.setBackground(color); } if (controllerLabel != null) { controllerLabel.setBackground(color); } if (closeButton != null) { closeButton.setBackground(color); } if (hudButton != null) { hudButton.setBackground(color); } } }); } @Override public void setForeground(final Color color) { SwingUtilities.invokeLater(new Runnable() { public void run() { HeaderPanel.super.setForeground(color); if (appLabel != null) { appLabel.setForeground(color); } if (controllerLabel != null) { controllerLabel.setForeground(color); } if (closeButton != null) { closeButton.setForeground(color); } if (hudButton != null) { hudButton.setForeground(color); } } }); } public void showHUDButton(boolean showButton) { hudButton.setVisible(showButton); } @Override public void addMouseListener(final MouseListener listener) { SwingUtilities.invokeLater(new Runnable() { public void run() { HeaderPanel.super.addMouseListener(listener); if (appLabel != null) { appLabel.addMouseListener(listener); } if (controllerLabel != null) { controllerLabel.addMouseListener(listener); } if (closeButton != null) { closeButton.addMouseListener(listener); } if (hudButton != null) { hudButton.addMouseListener(listener); } } }); } @Override public void removeMouseListener(final MouseListener listener) { SwingUtilities.invokeLater(new Runnable() { public void run() { HeaderPanel.super.removeMouseListener(listener); if (appLabel != null) { appLabel.removeMouseListener(listener); } if (controllerLabel != null) { controllerLabel.removeMouseListener(listener); } if (closeButton != null) { closeButton.removeMouseListener(listener); } if (hudButton != null) { hudButton.removeMouseListener(listener); } } }); } @Override public void addMouseMotionListener(final MouseMotionListener listener) { SwingUtilities.invokeLater(new Runnable() { public void run() { HeaderPanel.super.addMouseMotionListener(listener); if (appLabel != null) { appLabel.addMouseMotionListener(listener); } if (controllerLabel != null) { controllerLabel.addMouseMotionListener(listener); } if (closeButton != null) { closeButton.addMouseMotionListener(listener); } if (hudButton != null) { hudButton.addMouseMotionListener(listener); } } }); } @Override public void removeMouseMotionListener(final MouseMotionListener listener) { SwingUtilities.invokeLater(new Runnable() { public void run() { HeaderPanel.super.removeMouseMotionListener(listener); if (appLabel != null) { appLabel.removeMouseMotionListener(listener); } if (controllerLabel != null) { controllerLabel.removeMouseMotionListener(listener); } if (closeButton != null) { closeButton.removeMouseMotionListener(listener); } if (hudButton != null) { hudButton.removeMouseMotionListener(listener); } } }); } public void setTitle(String title) { if (title == null) { title = " "; } final String theTitle = title; if (appLabel != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { appLabel.setText(theTitle); } }); } } public void setController(String controller) { if (controller == null) { controller = " "; } final String theController = controller; if (appLabel != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { controllerLabel.setText(theController); } }); } } private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) { if (container != null) { container.close(); } } private void hudButtonActionPerformed(java.awt.event.ActionEvent evt) { if (container != null) { container.toggleHUD(); } } }
false
true
private void initComponents() { jToolBar1 = new javax.swing.JToolBar(); appLabel = new javax.swing.JLabel(); controllerLabel = new javax.swing.JLabel(); closeButton = new javax.swing.JButton(); hudButton = new javax.swing.JButton(); jToolBar1.setRollover(true); setMaximumSize(new java.awt.Dimension(32767, 24)); setMinimumSize(new java.awt.Dimension(50, 24)); setPreferredSize(new java.awt.Dimension(422, 24)); appLabel.setFont(appLabel.getFont().deriveFont(appLabel.getFont().getStyle() | java.awt.Font.BOLD, appLabel.getFont().getSize()+2)); appLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/appbase/client/Bundle"); // NOI18N appLabel.setText(bundle.getString("HeaderPanel.appLabel.text")); // NOI18N controllerLabel.setFont(controllerLabel.getFont().deriveFont(controllerLabel.getFont().getStyle() | java.awt.Font.BOLD, controllerLabel.getFont().getSize()+2)); controllerLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); controllerLabel.setText(bundle.getString("HeaderPanel.controllerLabel.text")); // NOI18N closeButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/window-close24x24.png"))); // NOI18N closeButton.setMaximumSize(new java.awt.Dimension(24, 24)); closeButton.setMinimumSize(new java.awt.Dimension(24, 24)); closeButton.setPreferredSize(new java.awt.Dimension(24, 24)); closeButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/window-close24x24.png"))); // NOI18N hudButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); // NOI18N hudButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/dock24x24.png"))); // NOI18N hudButton.setMaximumSize(new java.awt.Dimension(24, 24)); hudButton.setMinimumSize(new java.awt.Dimension(24, 24)); hudButton.setPreferredSize(new java.awt.Dimension(24, 24)); hudButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/dock24x24.png"))); // NOI18N org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() .add(appLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 226, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(controllerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 124, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(hudButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(3, 3, 3) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(appLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(controllerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(hudButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { jToolBar1 = new javax.swing.JToolBar(); appLabel = new javax.swing.JLabel(); controllerLabel = new javax.swing.JLabel(); closeButton = new javax.swing.JButton(); hudButton = new javax.swing.JButton(); jToolBar1.setRollover(true); setMaximumSize(new java.awt.Dimension(32767, 24)); setMinimumSize(new java.awt.Dimension(50, 24)); setPreferredSize(new java.awt.Dimension(422, 24)); appLabel.setFont(appLabel.getFont().deriveFont(appLabel.getFont().getStyle() | java.awt.Font.BOLD, appLabel.getFont().getSize()+2)); appLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jdesktop/wonderland/modules/appbase/client/Bundle"); // NOI18N appLabel.setText(bundle.getString("HeaderPanel.appLabel.text")); // NOI18N controllerLabel.setFont(controllerLabel.getFont().deriveFont(controllerLabel.getFont().getStyle() | java.awt.Font.BOLD, controllerLabel.getFont().getSize()+2)); controllerLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); controllerLabel.setText(bundle.getString("HeaderPanel.controllerLabel.text")); // NOI18N closeButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/window-close24x24.png"))); // NOI18N closeButton.setMaximumSize(new java.awt.Dimension(24, 24)); closeButton.setMinimumSize(new java.awt.Dimension(24, 24)); closeButton.setPreferredSize(new java.awt.Dimension(24, 24)); closeButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/window-close24x24.png"))); // NOI18N hudButton.setFont(new java.awt.Font("DejaVu Sans", 0, 10)); hudButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/dock24x24.png"))); // NOI18N hudButton.setMaximumSize(new java.awt.Dimension(24, 24)); hudButton.setMinimumSize(new java.awt.Dimension(24, 24)); hudButton.setPreferredSize(new java.awt.Dimension(24, 24)); hudButton.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/org/jdesktop/wonderland/modules/appbase/client/cell/view/viewdefault/resources/dock24x24.png"))); // NOI18N org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() .add(appLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(controllerLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(hudButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(3, 3, 3) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(appLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(controllerLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .add(hudButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents
diff --git a/core/src/processing/core/PApplet.java b/core/src/processing/core/PApplet.java index e7c6be8ef..9f3762fe1 100644 --- a/core/src/processing/core/PApplet.java +++ b/core/src/processing/core/PApplet.java @@ -1,14200 +1,14202 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-11 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 2.1. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.core; import java.applet.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import java.text.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; /** * Base class for all sketches that use processing.core. * <p/> * Note that you should not use AWT or Swing components inside a Processing * applet. The surface is made to automatically update itself, and will cause * problems with redraw of components drawn above it. If you'd like to * integrate other Java components, see below. * <p/> * As of release 0145, Processing uses active mode rendering in all cases. * All animation tasks happen on the "Processing Animation Thread". The * setup() and draw() methods are handled by that thread, and events (like * mouse movement and key presses, which are fired by the event dispatch * thread or EDT) are queued to be (safely) handled at the end of draw(). * For code that needs to run on the EDT, use SwingUtilities.invokeLater(). * When doing so, be careful to synchronize between that code (since * invokeLater() will make your code run from the EDT) and the Processing * animation thread. Use of a callback function or the registerXxx() methods * in PApplet can help ensure that your code doesn't do something naughty. * <p/> * As of release 0136 of Processing, we have discontinued support for versions * of Java prior to 1.5. We don't have enough people to support it, and for a * project of our size, we should be focusing on the future, rather than * working around legacy Java code. In addition, Java 1.5 gives us access to * better timing facilities which will improve the steadiness of animation. * <p/> * This class extends Applet instead of JApplet because 1) historically, * we supported Java 1.1, which does not include Swing (without an * additional, sizable, download), and 2) Swing is a bloated piece of crap. * A Processing applet is a heavyweight AWT component, and can be used the * same as any other AWT component, with or without Swing. * <p/> * Similarly, Processing runs in a Frame and not a JFrame. However, there's * nothing to prevent you from embedding a PApplet into a JFrame, it's just * that the base version uses a regular AWT frame because there's simply * no need for swing in that context. If people want to use Swing, they can * embed themselves as they wish. * <p/> * It is possible to use PApplet, along with core.jar in other projects. * In addition to enabling you to use Java 1.5+ features with your sketch, * this also allows you to embed a Processing drawing area into another Java * application. This means you can use standard GUI controls with a Processing * sketch. Because AWT and Swing GUI components cannot be used on top of a * PApplet, you can instead embed the PApplet inside another GUI the way you * would any other Component. * <p/> * It is also possible to resize the Processing window by including * <tt>frame.setResizable(true)</tt> inside your <tt>setup()</tt> method. * Note that the Java method <tt>frame.setSize()</tt> will not work unless * you first set the frame to be resizable. * <p/> * Because the default animation thread will run at 60 frames per second, * an embedded PApplet can make the parent sluggish. You can use frameRate() * to make it update less often, or you can use noLoop() and loop() to disable * and then re-enable looping. If you want to only update the sketch * intermittently, use noLoop() inside setup(), and redraw() whenever * the screen needs to be updated once (or loop() to re-enable the animation * thread). The following example embeds a sketch and also uses the noLoop() * and redraw() methods. You need not use noLoop() and redraw() when embedding * if you want your application to animate continuously. * <PRE> * public class ExampleFrame extends Frame { * * public ExampleFrame() { * super("Embedded PApplet"); * * setLayout(new BorderLayout()); * PApplet embed = new Embedded(); * add(embed, BorderLayout.CENTER); * * // important to call this whenever embedding a PApplet. * // It ensures that the animation thread is started and * // that other internal variables are properly set. * embed.init(); * } * } * * public class Embedded extends PApplet { * * public void setup() { * // original setup code here ... * size(400, 400); * * // prevent thread from starving everything else * noLoop(); * } * * public void draw() { * // drawing code goes here * } * * public void mousePressed() { * // do something based on mouse movement * * // update the screen (run draw once) * redraw(); * } * } * </PRE> * * <H2>Processing on multiple displays</H2> * <p>I was asked about Processing with multiple displays, and for lack of a * better place to document it, things will go here.</P> * <p>You can address both screens by making a window the width of both, * and the height of the maximum of both screens. In this case, do not use * present mode, because that's exclusive to one screen. Basically it'll * give you a PApplet that spans both screens. If using one half to control * and the other half for graphics, you'd just have to put the 'live' stuff * on one half of the canvas, the control stuff on the other. This works * better in windows because on the mac we can't get rid of the menu bar * unless it's running in present mode.</P> * <p>For more control, you need to write straight java code that uses p5. * You can create two windows, that are shown on two separate screens, * that have their own PApplet. this is just one of the tradeoffs of one of * the things that we don't support in p5 from within the environment * itself (we must draw the line somewhere), because of how messy it would * get to start talking about multiple screens. It's also not that tough to * do by hand w/ some Java code.</P> * @usage Web &amp; Application */ public class PApplet extends Applet implements PConstants, Runnable, MouseListener, MouseMotionListener, KeyListener, FocusListener { /** * Full name of the Java version (i.e. 1.5.0_11). * Prior to 0125, this was only the first three digits. */ public static final String javaVersionName = System.getProperty("java.version"); /** * Version of Java that's in use, whether 1.1 or 1.3 or whatever, * stored as a float. * <p> * Note that because this is stored as a float, the values may * not be <EM>exactly</EM> 1.3 or 1.4. Instead, make sure you're * comparing against 1.3f or 1.4f, which will have the same amount * of error (i.e. 1.40000001). This could just be a double, but * since Processing only uses floats, it's safer for this to be a float * because there's no good way to specify a double with the preproc. */ public static final float javaVersion = new Float(javaVersionName.substring(0, 3)).floatValue(); /** * Current platform in use. * <p> * Equivalent to System.getProperty("os.name"), just used internally. */ /** * Current platform in use, one of the * PConstants WINDOWS, MACOSX, MACOS9, LINUX or OTHER. */ static public int platform; /** * Name associated with the current 'platform' (see PConstants.platformNames) */ //static public String platformName; static { String osname = System.getProperty("os.name"); if (osname.indexOf("Mac") != -1) { platform = MACOSX; } else if (osname.indexOf("Windows") != -1) { platform = WINDOWS; } else if (osname.equals("Linux")) { // true for the ibm vm platform = LINUX; } else { platform = OTHER; } } /** * Setting for whether to use the Quartz renderer on OS X. The Quartz * renderer is on its way out for OS X, but Processing uses it by default * because it's much faster than the Sun renderer. In some cases, however, * the Quartz renderer is preferred. For instance, fonts are less thick * when using the Sun renderer, so to improve how fonts look, * change this setting before you call PApplet.main(). * <pre> * static public void main(String[] args) { * PApplet.useQuartz = "false"; * PApplet.main(new String[] { "YourSketch" }); * } * </pre> * This setting must be called before any AWT work happens, so that's why * it's such a terrible hack in how it's employed here. Calling setProperty() * inside setup() is a joke, since it's long since the AWT has been invoked. */ static public boolean useQuartz = true; /** * Modifier flags for the shortcut key used to trigger menus. * (Cmd on Mac OS X, Ctrl on Linux and Windows) */ static public final int MENU_SHORTCUT = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); /** The PGraphics renderer associated with this PApplet */ public PGraphics g; //protected Object glock = new Object(); // for sync /** The frame containing this applet (if any) */ public Frame frame; /** * ( begin auto-generated from screenWidth.xml ) * * System variable which stores the width of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>screenWidth</b> is 1024 and <b>screenHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int screenWidth; /** * ( begin auto-generated from screenHeight.xml ) * * System variable that stores the height of the computer screen. For * example, if the current screen resolution is 1024x768, * <b>screenWidth</b> is 1024 and <b>screenHeight</b> is 768. These * dimensions are useful when exporting full-screen applications. * <br /><br /> * To ensure that the sketch takes over the entire screen, use "Present" * instead of "Run". Otherwise the window will still have a frame border * around it and not be placed in the upper corner of the screen. On Mac OS * X, the menu bar will remain present unless "Present" mode is used. * * ( end auto-generated ) * @webref environment */ public int screenHeight; /** * A leech graphics object that is echoing all events. */ public PGraphics recorder; /** * Command line options passed in from main(). * <p> * This does not include the arguments passed in to PApplet itself. */ public String args[]; /** Path to sketch folder */ public String sketchPath; //folder; /** When debugging headaches */ static final boolean THREAD_DEBUG = false; /** Default width and height for applet when not specified */ static public final int DEFAULT_WIDTH = 100; static public final int DEFAULT_HEIGHT = 100; /** * Minimum dimensions for the window holding an applet. * This varies between platforms, Mac OS X 10.3 can do any height * but requires at least 128 pixels width. Windows XP has another * set of limitations. And for all I know, Linux probably lets you * make windows with negative sizes. */ static public final int MIN_WINDOW_WIDTH = 128; static public final int MIN_WINDOW_HEIGHT = 128; /** * Exception thrown when size() is called the first time. * <p> * This is used internally so that setup() is forced to run twice * when the renderer is changed. This is the only way for us to handle * invoking the new renderer while also in the midst of rendering. */ static public class RendererChangeException extends RuntimeException { } /** * true if no size() command has been executed. This is used to wait until * a size has been set before placing in the window and showing it. */ public boolean defaultSize; volatile boolean resizeRequest; volatile int resizeWidth; volatile int resizeHeight; /** * ( begin auto-generated from pixels.xml ) * * Array containing the values for all the pixels in the display window. * These values are of the color datatype. This array is the size of the * display window. For example, if the image is 100x100 pixels, there will * be 10000 values and if the window is 200x300 pixels, there will be 60000 * values. The <b>index</b> value defines the position of a value within * the array. For example, the statement <b>color b = pixels[230]</b> will * set the variable <b>b</b> to be equal to the value at that location in * the array.<br /> * <br /> * Before accessing this array, the data must loaded with the * <b>loadPixels()</b> function. After the array data has been modified, * the <b>updatePixels()</b> function must be run to update the changes. * Without <b>loadPixels()</b>, running the code may (or will in future * releases) result in a NullPointerException. * * ( end auto-generated ) * * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#updatePixels() * @see PApplet#get(int, int, int, int) * @see PApplet#set(int, int, int) * @see PImage */ public int pixels[]; /** * ( begin auto-generated from width.xml ) * * System variable which stores the width of the display window. This value * is set by the first parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>width</b> * variable to the value 320. The value of <b>width</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment */ public int width; /** * ( begin auto-generated from height.xml ) * * System variable which stores the height of the display window. This * value is set by the second parameter of the <b>size()</b> function. For * example, the function call <b>size(320, 240)</b> sets the <b>height</b> * variable to the value 240. The value of <b>height</b> is zero until * <b>size()</b> is called. * * ( end auto-generated ) * @webref environment * */ public int height; /** * ( begin auto-generated from mouseX.xml ) * * The system variable <b>mouseX</b> always contains the current horizontal * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * * */ public int mouseX; /** * ( begin auto-generated from mouseY.xml ) * * The system variable <b>mouseY</b> always contains the current vertical * coordinate of the mouse. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() * */ public int mouseY; /** * ( begin auto-generated from pmouseX.xml ) * * The system variable <b>pmouseX</b> always contains the horizontal * position of the mouse in the frame previous to the current frame.<br /> * <br /> * You may find that <b>pmouseX</b> and <b>pmouseY</b> have different * values inside <b>draw()</b> and inside events like <b>mousePressed()</b> * and <b>mouseMoved()</b>. This is because they're used for different * roles, so don't mix them. Inside <b>draw()</b>, <b>pmouseX</b> and * <b>pmouseY</b> update only once per frame (once per trip through your * <b>draw()</b>). But, inside mouse events, they update each time the * event is called. If they weren't separated, then the mouse would be read * only once per frame, making response choppy. If the mouse variables were * always updated multiple times per frame, using <NOBR><b>line(pmouseX, * pmouseY, mouseX, mouseY)</b></NOBR> inside <b>draw()</b> would have lots * of gaps, because <b>pmouseX</b> may have changed several times in * between the calls to <b>line()</b>. Use <b>pmouseX</b> and * <b>pmouseY</b> inside <b>draw()</b> if you want values relative to the * previous frame. Use <b>pmouseX</b> and <b>pmouseY</b> inside the mouse * functions if you want continuous response. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseY * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseX; /** * ( begin auto-generated from pmouseY.xml ) * * The system variable <b>pmouseY</b> always contains the vertical position * of the mouse in the frame previous to the current frame. More detailed * information about how <b>pmouseY</b> is updated inside of <b>draw()</b> * and mouse events is explained in the reference for <b>pmouseX</b>. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#pmouseX * @see PApplet#mouseX * @see PApplet#mouseY */ public int pmouseY; /** * previous mouseX/Y for the draw loop, separated out because this is * separate from the pmouseX/Y when inside the mouse event handlers. */ protected int dmouseX, dmouseY; /** * pmouseX/Y for the event handlers (mousePressed(), mouseDragged() etc) * these are different because mouse events are queued to the end of * draw, so the previous position has to be updated on each event, * as opposed to the pmouseX/Y that's used inside draw, which is expected * to be updated once per trip through draw(). */ protected int emouseX, emouseY; /** * Used to set pmouseX/Y to mouseX/Y the first time mouseX/Y are used, * otherwise pmouseX/Y are always zero, causing a nasty jump. * <p> * Just using (frameCount == 0) won't work since mouseXxxxx() * may not be called until a couple frames into things. */ public boolean firstMouse; /** * ( begin auto-generated from mouseButton.xml ) * * Processing automatically tracks if the mouse button is pressed and which * button is pressed. The value of the system variable <b>mouseButton</b> * is either <b>LEFT</b>, <b>RIGHT</b>, or <b>CENTER</b> depending on which * button is pressed. * * ( end auto-generated ) * * <h3>Advanced:</h3> * * If running on Mac OS, a ctrl-click will be interpreted as * the righthand mouse button (unlike Java, which reports it as * the left mouse). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public int mouseButton; /** * ( begin auto-generated from mousePressed_var.xml ) * * Variable storing if a mouse button is pressed. The value of the system * variable <b>mousePressed</b> is true if a mouse button is pressed and * false if a button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public boolean mousePressed; public MouseEvent mouseEvent; /** * ( begin auto-generated from key.xml ) * * The system variable <b>key</b> always contains the value of the most * recent key on the keyboard that was used (either pressed or released). * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Last key pressed. * <p> * If it's a coded key, i.e. UP/DOWN/CTRL/SHIFT/ALT, * this will be set to CODED (0xffff or 65535). * * @webref input:keyboard * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public char key; /** * ( begin auto-generated from keyCode.xml ) * * The variable <b>keyCode</b> is used to detect special keys such as the * UP, DOWN, LEFT, RIGHT arrow keys and ALT, CONTROL, SHIFT. When checking * for these keys, it's first necessary to check and see if the key is * coded. This is done with the conditional "if (key == CODED)" as shown in * the example. * <br/> <br/> * The keys included in the ASCII specification (BACKSPACE, TAB, ENTER, * RETURN, ESC, and DELETE) do not require checking to see if they key is * coded, and you should simply use the <b>key</b> variable instead of * <b>keyCode</b> If you're making cross-platform projects, note that the * ENTER key is commonly used on PCs and Unix and the RETURN key is used * instead on Macintosh. Check for both ENTER and RETURN to make sure your * program will work for all platforms. * <br/> <br/> * For users familiar with Java, the values for UP and DOWN are simply * shorter versions of Java's KeyEvent.VK_UP and KeyEvent.VK_DOWN. Other * keyCode values can be found in the Java <a * href="http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html">KeyEvent</a> reference. * * ( end auto-generated ) * * <h3>Advanced</h3> * When "key" is set to CODED, this will contain a Java key code. * <p> * For the arrow keys, keyCode will be one of UP, DOWN, LEFT and RIGHT. * Also available are ALT, CONTROL and SHIFT. A full set of constants * can be obtained from java.awt.event.KeyEvent, from the VK_XXXX variables. * * @webref input:keyboard * @see PApplet#key * @see PApplet#keyPressed * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public int keyCode; /** * ( begin auto-generated from keyPressed_var.xml ) * * The boolean system variable <b>keyPressed</b> is <b>true</b> if any key * is pressed and <b>false</b> if no keys are pressed. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed() * @see PApplet#keyReleased() */ public boolean keyPressed; /** * the last KeyEvent object passed into a mouse function. */ public KeyEvent keyEvent; /** * ( begin auto-generated from focused.xml ) * * Confirms if a Processing program is "focused", meaning that it is active * and will accept input from mouse or keyboard. This variable is "true" if * it is focused and "false" if not. This variable is often used when you * want to warn people they need to click on or roll over an applet before * it will work. * * ( end auto-generated ) * @webref environment */ public boolean focused = false; /** * ( begin auto-generated from online.xml ) * * Confirms if a Processing program is running inside a web browser. This * variable is "true" if the program is online and "false" if not. * * ( end auto-generated ) * @webref environment */ public boolean online = false; /** * Time in milliseconds when the applet was started. * <p> * Used by the millis() function. */ long millisOffset = System.currentTimeMillis(); /** * ( begin auto-generated from frameRate_var.xml ) * * The system variable <b>frameRate</b> contains the approximate frame rate * of the software as it executes. The initial value is 10 fps and is * updated with each frame. The value is averaged (integrated) over several * frames. As such, this value won't be valid until after 5-10 frames. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public float frameRate = 10; /** Last time in nanoseconds that frameRate was checked */ protected long frameRateLastNanos = 0; /** As of release 0116, frameRate(60) is called as a default */ protected float frameRateTarget = 60; protected long frameRatePeriod = 1000000000L / 60L; protected boolean looping; /** flag set to true when a redraw is asked for by the user */ protected boolean redraw; /** * ( begin auto-generated from frameCount.xml ) * * The system variable <b>frameCount</b> contains the number of frames * displayed since the program started. Inside <b>setup()</b> the value is * 0 and and after the first iteration of draw it is 1, etc. * * ( end auto-generated ) * @webref environment * @see PApplet#frameRate(float) */ public int frameCount; /** * true if this applet has had it. */ public volatile boolean finished; /** * true if the animation thread is paused. */ public volatile boolean paused; /** * true if exit() has been called so that things shut down * once the main thread kicks off. */ protected boolean exitCalled; Thread thread; protected RegisteredMethods sizeMethods; protected RegisteredMethods preMethods, drawMethods, postMethods; protected RegisteredMethods mouseEventMethods, keyEventMethods; protected RegisteredMethods disposeMethods; // messages to send if attached as an external vm /** * Position of the upper-lefthand corner of the editor window * that launched this applet. */ static public final String ARGS_EDITOR_LOCATION = "--editor-location"; /** * Location for where to position the applet window on screen. * <p> * This is used by the editor to when saving the previous applet * location, or could be used by other classes to launch at a * specific position on-screen. */ static public final String ARGS_EXTERNAL = "--external"; static public final String ARGS_LOCATION = "--location"; static public final String ARGS_DISPLAY = "--display"; static public final String ARGS_BGCOLOR = "--bgcolor"; static public final String ARGS_PRESENT = "--present"; static public final String ARGS_EXCLUSIVE = "--exclusive"; static public final String ARGS_STOP_COLOR = "--stop-color"; static public final String ARGS_HIDE_STOP = "--hide-stop"; /** * Allows the user or PdeEditor to set a specific sketch folder path. * <p> * Used by PdeEditor to pass in the location where saveFrame() * and all that stuff should write things. */ static public final String ARGS_SKETCH_FOLDER = "--sketch-path"; /** * When run externally to a PdeEditor, * this is sent by the applet when it quits. */ //static public final String EXTERNAL_QUIT = "__QUIT__"; static public final String EXTERNAL_STOP = "__STOP__"; /** * When run externally to a PDE Editor, this is sent by the applet * whenever the window is moved. * <p> * This is used so that the editor can re-open the sketch window * in the same position as the user last left it. */ static public final String EXTERNAL_MOVE = "__MOVE__"; /** true if this sketch is being run by the PDE */ boolean external = false; static final String ERROR_MIN_MAX = "Cannot use min() or max() on an empty array."; // during rev 0100 dev cycle, working on new threading model, // but need to disable and go conservative with changes in order // to get pdf and audio working properly first. // for 0116, the CRUSTY_THREADS are being disabled to fix lots of bugs. //static final boolean CRUSTY_THREADS = false; //true; public void init() { // println("init() called " + Integer.toHexString(hashCode())); // using a local version here since the class variable is deprecated Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); screenWidth = screen.width; screenHeight = screen.height; // send tab keys through to the PApplet setFocusTraversalKeysEnabled(false); //millisOffset = System.currentTimeMillis(); // moved to the variable declaration finished = false; // just for clarity // this will be cleared by draw() if it is not overridden looping = true; redraw = true; // draw this guy once firstMouse = true; // these need to be inited before setup sizeMethods = new RegisteredMethods(); preMethods = new RegisteredMethods(); drawMethods = new RegisteredMethods(); postMethods = new RegisteredMethods(); mouseEventMethods = new RegisteredMethods(); keyEventMethods = new RegisteredMethods(); disposeMethods = new RegisteredMethods(); try { getAppletContext(); online = true; } catch (NullPointerException e) { online = false; } try { if (sketchPath == null) { sketchPath = System.getProperty("user.dir"); } } catch (Exception e) { } // may be a security problem Dimension size = getSize(); if ((size.width != 0) && (size.height != 0)) { // When this PApplet is embedded inside a Java application with other // Component objects, its size() may already be set externally (perhaps // by a LayoutManager). In this case, honor that size as the default. // Size of the component is set, just create a renderer. g = makeGraphics(size.width, size.height, sketchRenderer(), null, true); // This doesn't call setSize() or setPreferredSize() because the fact // that a size was already set means that someone is already doing it. } else { // Set the default size, until the user specifies otherwise this.defaultSize = true; int w = sketchWidth(); int h = sketchHeight(); g = makeGraphics(w, h, sketchRenderer(), null, true); // Fire component resize event setSize(w, h); setPreferredSize(new Dimension(w, h)); } width = g.width; height = g.height; addListeners(); // this is automatically called in applets // though it's here for applications anyway start(); } public int sketchAntiAlias() { return 2; } public int sketchWidth() { return DEFAULT_WIDTH; } public int sketchHeight() { return DEFAULT_HEIGHT; } public String sketchRenderer() { return JAVA2D; } public void orientation(int which) { // ignore calls to the orientation command } /** * Called by the browser or applet viewer to inform this applet that it * should start its execution. It is called after the init method and * each time the applet is revisited in a Web page. * <p/> * Called explicitly via the first call to PApplet.paint(), because * PAppletGL needs to have a usable screen before getting things rolling. */ public void start() { // println("start() called"); // new Exception().printStackTrace(System.out); finished = false; paused = false; // unpause the thread // if this is the first run, setup and run the thread if (thread == null) { thread = new Thread(this, "Animation Thread"); thread.start(); } } /** * Called by the browser or applet viewer to inform * this applet that it should stop its execution. * <p/> * Unfortunately, there are no guarantees from the Java spec * when or if stop() will be called (i.e. on browser quit, * or when moving between web pages), and it's not always called. */ public void stop() { // this used to shut down the sketch, but that code has // been moved to dispose() paused = true; // causes animation thread to sleep //TODO listeners } /** * Called by the browser or applet viewer to inform this applet * that it is being reclaimed and that it should destroy * any resources that it has allocated. * <p/> * destroy() supposedly gets called as the applet viewer * is shutting down the applet. stop() is called * first, and then destroy() to really get rid of things. * no guarantees on when they're run (on browser quit, or * when moving between pages), though. */ public void destroy() { this.dispose(); } /** * This returns the last width and height specified by the user * via the size() command. */ // public Dimension getPreferredSize() { // return new Dimension(width, height); // } // public void addNotify() { // super.addNotify(); // println("addNotify()"); // } ////////////////////////////////////////////////////////////// public class RegisteredMethods { int count; Object objects[]; Method methods[]; Object[] convArgs = new Object[] { }; // convenience version for no args public void handle() { handle(convArgs); } public void handle(Object oargs[]) { for (int i = 0; i < count; i++) { try { //System.out.println(objects[i] + " " + args); methods[i].invoke(objects[i], oargs); } catch (Exception e) { //// check for wrapped exception, get root exception Throwable t; if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; //ite.getTargetException().printStackTrace(); t = ite.getCause(); } else { //e.printStackTrace(); t = e; } //// check for RuntimeException, and allow to bubble up if (t instanceof RuntimeException) { //// re-throw exception throw (RuntimeException) t; } else { //// trap and print as usual t.printStackTrace(); } } } } public void add(Object object, Method method) { if (objects == null) { objects = new Object[5]; methods = new Method[5]; } if (count == objects.length) { objects = (Object[]) PApplet.expand(objects); methods = (Method[]) PApplet.expand(methods); // Object otemp[] = new Object[count << 1]; // System.arraycopy(objects, 0, otemp, 0, count); // objects = otemp; // Method mtemp[] = new Method[count << 1]; // System.arraycopy(methods, 0, mtemp, 0, count); // methods = mtemp; } objects[count] = object; methods[count] = method; count++; } /** * Removes first object/method pair matched (and only the first, * must be called multiple times if object is registered multiple times). * Does not shrink array afterwards, silently returns if method not found. */ public void remove(Object object, Method method) { int index = findIndex(object, method); if (index != -1) { // shift remaining methods by one to preserve ordering count--; for (int i = index; i < count; i++) { objects[i] = objects[i+1]; methods[i] = methods[i+1]; } // clean things out for the gc's sake objects[count] = null; methods[count] = null; } } protected int findIndex(Object object, Method method) { for (int i = 0; i < count; i++) { if (objects[i] == object && methods[i].equals(method)) { //objects[i].equals() might be overridden, so use == for safety // since here we do care about actual object identity //methods[i]==method is never true even for same method, so must use // equals(), this should be safe because of object identity return i; } } return -1; } } public void registerSize(Object o) { Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; registerWithArgs(sizeMethods, "size", o, methodArgs); } public void registerPre(Object o) { registerNoArgs(preMethods, "pre", o); } public void registerDraw(Object o) { registerNoArgs(drawMethods, "draw", o); } public void registerPost(Object o) { registerNoArgs(postMethods, "post", o); } public void registerMouseEvent(Object o) { Class<?> methodArgs[] = new Class[] { MouseEvent.class }; registerWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs); } public void registerKeyEvent(Object o) { Class<?> methodArgs[] = new Class[] { KeyEvent.class }; registerWithArgs(keyEventMethods, "keyEvent", o, methodArgs); } public void registerDispose(Object o) { registerNoArgs(disposeMethods, "dispose", o); } protected void registerNoArgs(RegisteredMethods meth, String name, Object o) { Class<?> c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } protected void registerWithArgs(RegisteredMethods meth, String name, Object o, Class<?> cargs[]) { Class<?> c = o.getClass(); try { Method method = c.getMethod(name, cargs); meth.add(o, method); } catch (NoSuchMethodException nsme) { die("There is no public " + name + "() method in the class " + o.getClass().getName()); } catch (Exception e) { die("Could not register " + name + " + () for " + o, e); } } public void unregisterSize(Object o) { Class<?> methodArgs[] = new Class[] { Integer.TYPE, Integer.TYPE }; unregisterWithArgs(sizeMethods, "size", o, methodArgs); } public void unregisterPre(Object o) { unregisterNoArgs(preMethods, "pre", o); } public void unregisterDraw(Object o) { unregisterNoArgs(drawMethods, "draw", o); } public void unregisterPost(Object o) { unregisterNoArgs(postMethods, "post", o); } public void unregisterMouseEvent(Object o) { Class<?> methodArgs[] = new Class[] { MouseEvent.class }; unregisterWithArgs(mouseEventMethods, "mouseEvent", o, methodArgs); } public void unregisterKeyEvent(Object o) { Class<?> methodArgs[] = new Class[] { KeyEvent.class }; unregisterWithArgs(keyEventMethods, "keyEvent", o, methodArgs); } public void unregisterDispose(Object o) { unregisterNoArgs(disposeMethods, "dispose", o); } protected void unregisterNoArgs(RegisteredMethods meth, String name, Object o) { Class<?> c = o.getClass(); try { Method method = c.getMethod(name, new Class[] {}); meth.remove(o, method); } catch (Exception e) { die("Could not unregister " + name + "() for " + o, e); } } protected void unregisterWithArgs(RegisteredMethods meth, String name, Object o, Class<?> cargs[]) { Class<?> c = o.getClass(); try { Method method = c.getMethod(name, cargs); meth.remove(o, method); } catch (Exception e) { die("Could not unregister " + name + "() for " + o, e); } } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from setup.xml ) * * The <b>setup()</b> function is called once when the program starts. It's * used to define initial * enviroment properties such as screen size and background color and to * load media such as images * and fonts as the program starts. There can only be one <b>setup()</b> * function for each program and * it shouldn't be called again after its initial execution. Note: * Variables declared within * <b>setup()</b> are not accessible within other functions, including * <b>draw()</b>. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#size(int, int) * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#draw() */ public void setup() { } /** * ( begin auto-generated from draw.xml ) * * Called directly after <b>setup()</b> and continuously executes the lines * of code contained inside its block until the program is stopped or * <b>noLoop()</b> is called. The <b>draw()</b> function is called * automatically and should never be called explicitly. It should always be * controlled with <b>noLoop()</b>, <b>redraw()</b> and <b>loop()</b>. * After <b>noLoop()</b> stops the code in <b>draw()</b> from executing, * <b>redraw()</b> causes the code inside <b>draw()</b> to execute once and * <b>loop()</b> will causes the code inside <b>draw()</b> to execute * continuously again. The number of times <b>draw()</b> executes in each * second may be controlled with the <b>delay()</b> and <b>frameRate()</b> * functions. There can only be one <b>draw()</b> function for each sketch * and <b>draw()</b> must exist if you want the code to run continuously or * to process events such as <b>mousePressed()</b>. Sometimes, you might * have an empty call to <b>draw()</b> in your program as shown in the * above example. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#setup() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#frameRate() */ public void draw() { // if no draw method, then shut things down //System.out.println("no draw method, goodbye"); finished = true; } ////////////////////////////////////////////////////////////// protected void resizeRenderer(int iwidth, int iheight) { // println("resizeRenderer request for " + iwidth + " " + iheight); if (width != iwidth || height != iheight) { // println(" former size was " + width + " " + height); g.setSize(iwidth, iheight); width = iwidth; height = iheight; } } /** * ( begin auto-generated from size.xml ) * * Defines the dimension of the display window in units of pixels. The * <b>size()</b> function must be the first line in <b>setup()</b>. If * <b>size()</b> is not used, the default size of the window is 100x100 * pixels. The system variables <b>width</b> and <b>height</b> are set by * the parameters passed to this function.<br /> * <br /> * Do not use variables as the parameters to <b>size()</b> function, * because it will cause problems when exporting your sketch. When * variables are used, the dimensions of your sketch cannot be determined * during export. Instead, employ numeric values in the <b>size()</b> * statement, and then use the built-in <b>width</b> and <b>height</b> * variables inside your program when the dimensions of the display window * are needed.<br /> * <br /> * The <b>size()</b> function can only be used once inside a sketch, and * cannot be used for resizing.<br/> * <br/> <b>renderer</b> parameter selects which rendering engine to use. * For example, if you will be drawing 3D shapes, use <b>P3D</b>, if you * want to export images from a program as a PDF file use <b>PDF</b>. A * brief description of the three primary renderers follows:<br /> * <br /> * <b>P2D</b> (Processing 2D) - The default renderer that supports two * dimensional drawing.<br /> * <br /> * <b>P3D</b> (Processing 3D) - 3D graphics renderer that makes use of * OpenGL-compatible graphics hardware.<br /> * <br /> * <b>PDF</b> - The PDF renderer draws 2D graphics directly to an Acrobat * PDF file. This produces excellent results when you need vector shapes * for high resolution output or printing. You must first use Import * Library &rarr; PDF to make use of the library. More information can be * found in the PDF library reference.<br /> * <br /> * The P3D renderer doesn't support <b>strokeCap()</b> or * <b>strokeJoin()</b>, which can lead to ugly results when using * <b>strokeWeight()</b>. (<a * href="http://code.google.com/p/processing/issues/detail?id=123">Issue * 123</a>) <br /> * <br /> * The maximum width and height is limited by your operating system, and is * usually the width and height of your actual screen. On some machines it * may simply be the number of pixels on your current screen, meaning that * a screen of 800x600 could support <b>size(1600, 300)</b>, since it's the * same number of pixels. This varies widely so you'll have to try * different rendering modes and sizes until you get what you're looking * for. If you need something larger, use <b>createGraphics</b> to create a * non-visible drawing surface.<br /> * <br /> * Again, the <b>size()</b> function must be the first line of the code (or * first item inside setup). Any code that appears before the <b>size()</b> * command may run more than once, which can lead to confusing results. * * ( end auto-generated ) * * <h3>Advanced</h3> * If using Java 1.3 or later, this will default to using * PGraphics2, the Java2D-based renderer. If using Java 1.1, * or if PGraphics2 is not available, then PGraphics will be used. * To set your own renderer, use the other version of the size() * method that takes a renderer as its last parameter. * <p> * If called once a renderer has already been set, this will * use the previous renderer and simply resize it. * * @webref environment * @param iwidth width of the display window in units of pixels * @param iheight height of the display window in units of pixels */ public void size(int iwidth, int iheight) { size(iwidth, iheight, JAVA2D, null); } /** * @param irenderer Either P2D, P3D */ public void size(int iwidth, int iheight, String irenderer) { size(iwidth, iheight, irenderer, null); } /** * @nowebref */ public void size(final int iwidth, final int iheight, String irenderer, String ipath) { // Run this from the EDT, just cuz it's AWT stuff (or maybe later Swing) SwingUtilities.invokeLater(new Runnable() { public void run() { // Set the preferred size so that the layout managers can handle it setPreferredSize(new Dimension(iwidth, iheight)); setSize(iwidth, iheight); } }); // ensure that this is an absolute path if (ipath != null) ipath = savePath(ipath); String currentRenderer = g.getClass().getName(); if (currentRenderer.equals(irenderer)) { // Avoid infinite loop of throwing exception to reset renderer resizeRenderer(iwidth, iheight); //redraw(); // will only be called insize draw() } else { // renderer is being changed // otherwise ok to fall through and create renderer below // the renderer is changing, so need to create a new object g = makeGraphics(iwidth, iheight, irenderer, ipath, true); width = iwidth; height = iheight; // fire resize event to make sure the applet is the proper size // setSize(iwidth, iheight); // this is the function that will run if the user does their own // size() command inside setup, so set defaultSize to false. defaultSize = false; // throw an exception so that setup() is called again // but with a properly sized render // this is for opengl, which needs a valid, properly sized // display before calling anything inside setup(). throw new RendererChangeException(); } } /** * ( begin auto-generated from createGraphics.xml ) * * Creates and returns a new <b>PGraphics</b> object of the types P2D or * P3D. Use this class if you need to draw into an off-screen graphics * buffer. The PDF renderer requires the filename parameter. The DXF * renderer should not be used with <b>createGraphics()</b>, it's only * built for use with <b>beginRaw()</b> and <b>endRaw()</b>.<br /> * <br /> * It's important to call any drawing functions between <b>beginDraw()</b> * and <b>endDraw()</b> statements. This is also true for any functions * that affect drawing, such as <b>smooth()</b> or <b>colorMode()</b>.<br/> * <br/> the main drawing surface which is completely opaque, surfaces * created with <b>createGraphics()</b> can have transparency. This makes * it possible to draw into a graphics and maintain the alpha channel. By * using <b>save()</b> to write a PNG or TGA file, the transparency of the * graphics object will be honored. Note that transparency levels are * binary: pixels are either complete opaque or transparent. For the time * being, this means that text characters will be opaque blocks. This will * be fixed in a future release (<a * href="http://code.google.com/p/processing/issues/detail?id=80">Issue 80</a>). * * ( end auto-generated ) * <h3>Advanced</h3> * Create an offscreen PGraphics object for drawing. This can be used * for bitmap or vector images drawing or rendering. * <UL> * <LI>Do not use "new PGraphicsXxxx()", use this method. This method * ensures that internal variables are set up properly that tie the * new graphics context back to its parent PApplet. * <LI>The basic way to create bitmap images is to use the <A * HREF="http://processing.org/reference/saveFrame_.html">saveFrame()</A> * function. * <LI>If you want to create a really large scene and write that, * first make sure that you've allocated a lot of memory in the Preferences. * <LI>If you want to create images that are larger than the screen, * you should create your own PGraphics object, draw to that, and use * <A HREF="http://processing.org/reference/save_.html">save()</A>. * For now, it's best to use <A HREF="http://dev.processing.org/reference/everything/javadoc/processing/core/PGraphics3D.html">P3D</A> in this scenario. * P2D is currently disabled, and the JAVA2D default will give mixed * results. An example of using P3D: * <PRE> * * PGraphics big; * * void setup() { * big = createGraphics(3000, 3000, P3D); * * big.beginDraw(); * big.background(128); * big.line(20, 1800, 1800, 900); * // etc.. * big.endDraw(); * * // make sure the file is written to the sketch folder * big.save("big.tif"); * } * * </PRE> * <LI>It's important to always wrap drawing to createGraphics() with * beginDraw() and endDraw() (beginFrame() and endFrame() prior to * revision 0115). The reason is that the renderer needs to know when * drawing has stopped, so that it can update itself internally. * This also handles calling the defaults() method, for people familiar * with that. * <LI>It's not possible to use createGraphics() with the OPENGL renderer, * because it doesn't allow offscreen use. * <LI>With Processing 0115 and later, it's possible to write images in * formats other than the default .tga and .tiff. The exact formats and * background information can be found in the developer's reference for * <A HREF="http://dev.processing.org/reference/core/javadoc/processing/core/PImage.html#save(java.lang.String)">PImage.save()</A>. * </UL> * * @webref rendering * @param iwidth width in pixels * @param iheight height in pixels * @param irenderer Either P2D, P3D, PDF, DXF * * @see PGraphics#PGraphics * */ public PGraphics createGraphics(int iwidth, int iheight, String irenderer) { PGraphics pg = makeGraphics(iwidth, iheight, irenderer, null, false); //pg.parent = this; // make save() work return pg; } /** * Create an offscreen graphics surface for drawing, in this case * for a renderer that writes to a file (such as PDF or DXF). * @param ipath the name of the file (can be an absolute or relative path) */ public PGraphics createGraphics(int iwidth, int iheight, String irenderer, String ipath) { if (ipath != null) { ipath = savePath(ipath); } PGraphics pg = makeGraphics(iwidth, iheight, irenderer, ipath, false); pg.parent = this; // make save() work return pg; } /** * Version of createGraphics() used internally. */ protected PGraphics makeGraphics(int iwidth, int iheight, String irenderer, String ipath, boolean iprimary) { if (irenderer.equals(OPENGL)) { if (PApplet.platform == WINDOWS) { String s = System.getProperty("java.version"); if (s != null) { if (s.equals("1.5.0_10")) { System.err.println("OpenGL support is broken with Java 1.5.0_10"); System.err.println("See http://dev.processing.org" + "/bugs/show_bug.cgi?id=513 for more info."); throw new RuntimeException("Please update your Java " + "installation (see bug #513)"); } } } } // if (irenderer.equals(P2D)) { // throw new RuntimeException("The P2D renderer is currently disabled, " + // "please use P3D or JAVA2D."); // } String openglError = "Before using OpenGL, first select " + "Import Library > opengl from the Sketch menu."; try { /* Class<?> rendererClass = Class.forName(irenderer); Class<?> constructorParams[] = null; Object constructorValues[] = null; if (ipath == null) { constructorParams = new Class[] { Integer.TYPE, Integer.TYPE, PApplet.class }; constructorValues = new Object[] { new Integer(iwidth), new Integer(iheight), this }; } else { constructorParams = new Class[] { Integer.TYPE, Integer.TYPE, PApplet.class, String.class }; constructorValues = new Object[] { new Integer(iwidth), new Integer(iheight), this, ipath }; } Constructor<?> constructor = rendererClass.getConstructor(constructorParams); PGraphics pg = (PGraphics) constructor.newInstance(constructorValues); */ Class<?> rendererClass = Thread.currentThread().getContextClassLoader().loadClass(irenderer); //Class<?> params[] = null; //PApplet.println(rendererClass.getConstructors()); Constructor<?> constructor = rendererClass.getConstructor(new Class[] { }); PGraphics pg = (PGraphics) constructor.newInstance(); pg.setParent(this); pg.setPrimary(iprimary); if (ipath != null) pg.setPath(ipath); pg.setAntiAlias(sketchAntiAlias()); pg.setSize(iwidth, iheight); // everything worked, return it return pg; } catch (InvocationTargetException ite) { String msg = ite.getTargetException().getMessage(); if ((msg != null) && (msg.indexOf("no jogl in java.library.path") != -1)) { throw new RuntimeException(openglError + " (The native library is missing.)"); } else { ite.getTargetException().printStackTrace(); Throwable target = ite.getTargetException(); if (platform == MACOSX) target.printStackTrace(System.out); // bug // neither of these help, or work //target.printStackTrace(System.err); //System.err.flush(); //System.out.println(System.err); // and the object isn't null throw new RuntimeException(target.getMessage()); } } catch (ClassNotFoundException cnfe) { if (cnfe.getMessage().indexOf("processing.opengl.PGraphicsGL") != -1) { throw new RuntimeException(openglError + " (The library .jar file is missing.)"); } else { throw new RuntimeException("You need to use \"Import Library\" " + "to add " + irenderer + " to your sketch."); } } catch (Exception e) { //System.out.println("ex3"); if ((e instanceof IllegalArgumentException) || (e instanceof NoSuchMethodException) || (e instanceof IllegalAccessException)) { e.printStackTrace(); /* String msg = "public " + irenderer.substring(irenderer.lastIndexOf('.') + 1) + "(int width, int height, PApplet parent" + ((ipath == null) ? "" : ", String filename") + ") does not exist."; */ String msg = irenderer + " needs to be updated " + "for the current release of Processing."; throw new RuntimeException(msg); } else { if (platform == MACOSX) e.printStackTrace(System.out); throw new RuntimeException(e.getMessage()); } } } /** * ( begin auto-generated from createImage.xml ) * * Creates a new PImage (the datatype for storing images). This provides a * fresh buffer of pixels to play with. Set the size of the buffer with the * <b>width</b> and <b>height</b> parameters. The <b>format</b> parameter * defines how the pixels are stored. See the PImage reference for more information. * <br/> <br/> * Be sure to include all three parameters, specifying only the width and * height (but no format) will produce a strange error. * <br/> <br/> * Advanced users please note that createImage() should be used instead of * the syntax <tt>new PImage()</tt>. * * ( end auto-generated ) * <h3>Advanced</h3> * Preferred method of creating new PImage objects, ensures that a * reference to the parent PApplet is included, which makes save() work * without needing an absolute path. * * @webref image * @param wide width in pixels * @param high height in pixels * @param format Either RGB, ARGB, ALPHA (grayscale alpha channel) * @see PImage#PImage * @see PGraphics#PGraphics */ public PImage createImage(int wide, int high, int format) { return createImage(wide, high, format, null); } /** * @nowebref */ public PImage createImage(int wide, int high, int format, Object params) { PImage image = new PImage(wide, high, format); if (params != null) { image.setParams(g, params); } image.parent = this; // make save() work return image; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . public void update(Graphics screen) { paint(screen); } public void paint(Graphics screen) { // int r = (int) random(10000); // System.out.println("into paint " + r); //super.paint(screen); // ignore the very first call to paint, since it's coming // from the o.s., and the applet will soon update itself anyway. if (frameCount == 0) { // println("Skipping frame"); // paint() may be called more than once before things // are finally painted to the screen and the thread gets going return; } // without ignoring the first call, the first several frames // are confused because paint() gets called in the midst of // the initial nextFrame() call, so there are multiple // updates fighting with one another. // make sure the screen is visible and usable // (also prevents over-drawing when using PGraphicsOpenGL) /* the 1.5.x version if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 // g.image is synchronized so that draw/loop and paint don't // try to fight over it. this was causing a randomized slowdown // that would cut the frameRate into a third on macosx, // and is probably related to the windows sluggishness bug too if (g.image != null) { System.out.println("ui paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } } } */ // the 1.2.1 version if ((g != null) && (g.image != null)) { // println("inside paint(), screen.drawImage()"); screen.drawImage(g.image, 0, 0, null); } } // active paint method protected void paint() { try { Graphics screen = this.getGraphics(); if (screen != null) { if ((g != null) && (g.image != null)) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); // } finally { // if (g != null) { // g.dispose(); // } } } protected void paint_1_5_1() { try { Graphics screen = getGraphics(); if (screen != null) { if (g != null) { // added synchronization for 0194 because of flicker issues with JAVA2D // http://code.google.com/p/processing/issues/detail?id=558 if (g.image != null) { System.out.println("active paint"); synchronized (g.image) { screen.drawImage(g.image, 0, 0, null); } Toolkit.getDefaultToolkit().sync(); } } } } catch (Exception e) { // Seen on applet destroy, maybe can ignore? e.printStackTrace(); } } ////////////////////////////////////////////////////////////// /** * Main method for the primary animation thread. * * <A HREF="http://java.sun.com/products/jfc/tsc/articles/painting/">Painting in AWT and Swing</A> */ public void run() { // not good to make this synchronized, locks things up long beforeTime = System.nanoTime(); long overSleepTime = 0L; int noDelays = 0; // Number of frames with a delay of 0 ms before the // animation thread yields to other running threads. final int NO_DELAYS_PER_YIELD = 15; /* // this has to be called after the exception is thrown, // otherwise the supporting libs won't have a valid context to draw to Object methodArgs[] = new Object[] { new Integer(width), new Integer(height) }; sizeMethods.handle(methodArgs); */ while ((Thread.currentThread() == thread) && !finished) { while (paused) { // println("paused..."); try { Thread.sleep(100L); } catch (InterruptedException e) { //ignore? } } // Don't resize the renderer from the EDT (i.e. from a ComponentEvent), // otherwise it may attempt a resize mid-render. if (resizeRequest) { resizeRenderer(resizeWidth, resizeHeight); resizeRequest = false; } // render a single frame handleDraw(); if (frameCount == 1) { // Call the request focus event once the image is sure to be on // screen and the component is valid. The OpenGL renderer will // request focus for its canvas inside beginDraw(). // http://java.sun.com/j2se/1.4.2/docs/api/java/awt/doc-files/FocusSpec.html // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // requestFocus(); // Changing to this version for 0187 // http://code.google.com/p/processing/issues/detail?id=279 requestFocusInWindow(); } // wait for update & paint to happen before drawing next frame // this is necessary since the drawing is sometimes in a // separate thread, meaning that the next frame will start // before the update/paint is completed long afterTime = System.nanoTime(); long timeDiff = afterTime - beforeTime; //System.out.println("time diff is " + timeDiff); long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime; if (sleepTime > 0) { // some time left in this cycle try { // Thread.sleep(sleepTime / 1000000L); // nanoseconds -> milliseconds Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L)); noDelays = 0; // Got some sleep, not delaying anymore } catch (InterruptedException ex) { } overSleepTime = (System.nanoTime() - afterTime) - sleepTime; //System.out.println(" oversleep is " + overSleepTime); } else { // sleepTime <= 0; the frame took longer than the period // excess -= sleepTime; // store excess time value overSleepTime = 0L; if (noDelays > NO_DELAYS_PER_YIELD) { Thread.yield(); // give another thread a chance to run noDelays = 0; } } beforeTime = System.nanoTime(); } dispose(); // call to shutdown libs? // If the user called the exit() function, the window should close, // rather than the sketch just halting. if (exitCalled) { exitActual(); } } //synchronized public void handleDisplay() { public void handleDraw() { if (g != null && (looping || redraw)) { if (!g.canDraw()) { // Don't draw if the renderer is not yet ready. // (e.g. OpenGL has to wait for a peer to be on screen) return; } g.beginDraw(); if (recorder != null) { recorder.beginDraw(); } long now = System.nanoTime(); if (frameCount == 0) { try { //println("Calling setup()"); setup(); //println("Done with setup()"); } catch (RendererChangeException e) { // Give up, instead set the new renderer and re-attempt setup() return; } this.defaultSize = false; } else { // frameCount > 0, meaning an actual draw() // update the current frameRate double rate = 1000000.0 / ((now - frameRateLastNanos) / 1000000.0); float instantaneousRate = (float) rate / 1000.0f; frameRate = (frameRate * 0.9f) + (instantaneousRate * 0.1f); if (frameCount != 0) { preMethods.handle(); } // use dmouseX/Y as previous mouse pos, since this is the // last position the mouse was in during the previous draw. pmouseX = dmouseX; pmouseY = dmouseY; //println("Calling draw()"); draw(); //println("Done calling draw()"); // dmouseX/Y is updated only once per frame (unlike emouseX/Y) dmouseX = mouseX; dmouseY = mouseY; // these are called *after* loop so that valid // drawing commands can be run inside them. it can't // be before, since a call to background() would wipe // out anything that had been drawn so far. dequeueMouseEvents(); dequeueKeyEvents(); drawMethods.handle(); redraw = false; // unset 'redraw' flag in case it was set // (only do this once draw() has run, not just setup()) } g.endDraw(); if (recorder != null) { recorder.endDraw(); } frameRateLastNanos = now; frameCount++; paint(); // back to active paint // repaint(); // getToolkit().sync(); // force repaint now (proper method) if (frameCount != 0) { postMethods.handle(); } } } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from redraw.xml ) * * Executes the code within <b>draw()</b> one time. This functions allows * the program to update the display window only when necessary, for * example when an event registered by <b>mousePressed()</b> or * <b>keyPressed()</b> occurs. * <br/><br/> structuring a program, it only makes sense to call redraw() * within events such as <b>mousePressed()</b>. This is because * <b>redraw()</b> does not run <b>draw()</b> immediately (it only sets a * flag that indicates an update is needed). * <br/><br/> <b>redraw()</b> within <b>draw()</b> has no effect because * <b>draw()</b> is continuously called anyway. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#frameRate() */ synchronized public void redraw() { if (!looping) { redraw = true; // if (thread != null) { // // wake from sleep (necessary otherwise it'll be // // up to 10 seconds before update) // if (CRUSTY_THREADS) { // thread.interrupt(); // } else { // synchronized (blocker) { // blocker.notifyAll(); // } // } // } } } /** * ( begin auto-generated from loop.xml ) * * Causes Processing to continuously execute the code within <b>draw()</b>. * If <b>noLoop()</b> is called, the code in <b>draw()</b> stops executing. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#noLoop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void loop() { if (!looping) { looping = true; } } /** * ( begin auto-generated from noLoop.xml ) * * Stops Processing from continuously executing the code within * <b>draw()</b>. If <b>loop()</b> is called, the code in <b>draw()</b> * begin to run continuously again. If using <b>noLoop()</b> in * <b>setup()</b>, it should be the last line inside the block. * <br/> <br/> * When <b>noLoop()</b> is used, it's not possible to manipulate or access * the screen inside event handling functions such as <b>mousePressed()</b> * or <b>keyPressed()</b>. Instead, use those functions to call * <b>redraw()</b> or <b>loop()</b>, which will run <b>draw()</b>, which * can update the screen properly. This means that when noLoop() has been * called, no drawing can happen, and functions like saveFrame() or * loadPixels() may not be used. * <br/> <br/> * Note that if the sketch is resized, <b>redraw()</b> will be called to * update the sketch, even after <b>noLoop()</b> has been specified. * Otherwise, the sketch would enter an odd state until <b>loop()</b> was called. * * ( end auto-generated ) * @webref structure * @usage web_application * @see PApplet#loop() * @see PApplet#redraw() * @see PApplet#draw() */ synchronized public void noLoop() { if (looping) { looping = false; } } ////////////////////////////////////////////////////////////// public void addListeners() { addMouseListener(this); addMouseMotionListener(this); addKeyListener(this); addFocusListener(this); addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { Component c = e.getComponent(); //System.out.println("componentResized() " + c); Rectangle bounds = c.getBounds(); resizeRequest = true; resizeWidth = bounds.width; resizeHeight = bounds.height; if (!looping) { redraw(); } } }); } ////////////////////////////////////////////////////////////// MouseEvent mouseEventQueue[] = new MouseEvent[10]; int mouseEventCount; protected void enqueueMouseEvent(MouseEvent e) { synchronized (mouseEventQueue) { if (mouseEventCount == mouseEventQueue.length) { MouseEvent temp[] = new MouseEvent[mouseEventCount << 1]; System.arraycopy(mouseEventQueue, 0, temp, 0, mouseEventCount); mouseEventQueue = temp; } mouseEventQueue[mouseEventCount++] = e; } } protected void dequeueMouseEvents() { synchronized (mouseEventQueue) { for (int i = 0; i < mouseEventCount; i++) { mouseEvent = mouseEventQueue[i]; handleMouseEvent(mouseEvent); } mouseEventCount = 0; } } /** * Actually take action based on a mouse event. * Internally updates mouseX, mouseY, mousePressed, and mouseEvent. * Then it calls the event type with no params, * i.e. mousePressed() or mouseReleased() that the user may have * overloaded to do something more useful. */ protected void handleMouseEvent(MouseEvent event) { int id = event.getID(); // http://dev.processing.org/bugs/show_bug.cgi?id=170 // also prevents mouseExited() on the mac from hosing the mouse // position, because x/y are bizarre values on the exit event. // see also the id check below.. both of these go together if ((id == MouseEvent.MOUSE_DRAGGED) || (id == MouseEvent.MOUSE_MOVED)) { pmouseX = emouseX; pmouseY = emouseY; mouseX = event.getX(); mouseY = event.getY(); } mouseEvent = event; int modifiers = event.getModifiers(); if ((modifiers & InputEvent.BUTTON1_MASK) != 0) { mouseButton = LEFT; } else if ((modifiers & InputEvent.BUTTON2_MASK) != 0) { mouseButton = CENTER; } else if ((modifiers & InputEvent.BUTTON3_MASK) != 0) { mouseButton = RIGHT; } // if running on macos, allow ctrl-click as right mouse if (platform == MACOSX) { if (mouseEvent.isPopupTrigger()) { mouseButton = RIGHT; } } mouseEventMethods.handle(new Object[] { event }); // this used to only be called on mouseMoved and mouseDragged // change it back if people run into trouble if (firstMouse) { pmouseX = mouseX; pmouseY = mouseY; dmouseX = mouseX; dmouseY = mouseY; firstMouse = false; } //println(event); switch (id) { case MouseEvent.MOUSE_PRESSED: mousePressed = true; mousePressed(); break; case MouseEvent.MOUSE_RELEASED: mousePressed = false; mouseReleased(); break; case MouseEvent.MOUSE_CLICKED: mouseClicked(); break; case MouseEvent.MOUSE_DRAGGED: mouseDragged(); break; case MouseEvent.MOUSE_MOVED: mouseMoved(); break; } if ((id == MouseEvent.MOUSE_DRAGGED) || (id == MouseEvent.MOUSE_MOVED)) { emouseX = mouseX; emouseY = mouseY; } } /** * Figure out how to process a mouse event. When loop() has been * called, the events will be queued up until drawing is complete. * If noLoop() has been called, then events will happen immediately. */ protected void checkMouseEvent(MouseEvent event) { if (looping) { enqueueMouseEvent(event); } else { handleMouseEvent(event); } } /** * If you override this or any function that takes a "MouseEvent e" * without calling its super.mouseXxxx() then mouseX, mouseY, * mousePressed, and mouseEvent will no longer be set. * * @nowebref */ public void mousePressed(MouseEvent e) { checkMouseEvent(e); } /** * @nowebref */ public void mouseReleased(MouseEvent e) { checkMouseEvent(e); } /** * @nowebref */ public void mouseClicked(MouseEvent e) { checkMouseEvent(e); } public void mouseEntered(MouseEvent e) { checkMouseEvent(e); } public void mouseExited(MouseEvent e) { checkMouseEvent(e); } /** * @nowebref */ public void mouseDragged(MouseEvent e) { checkMouseEvent(e); } /** * @nowebref */ public void mouseMoved(MouseEvent e) { checkMouseEvent(e); } /** * ( begin auto-generated from mousePressed.xml ) * * The <b>mousePressed()</b> function is called once after every time a * mouse button is pressed. The <b>mouseButton</b> variable (see the * related reference entry) can be used to determine which button has been pressed. * * ( end auto-generated ) * <h3>Advanced</h3> * * If you must, use * int button = mouseEvent.getButton(); * to figure out which button was clicked. It will be one of: * MouseEvent.BUTTON1, MouseEvent.BUTTON2, MouseEvent.BUTTON3 * Note, however, that this is completely inconsistent across * platforms. * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mousePressed() { } /** * ( begin auto-generated from mouseReleased.xml ) * * The <b>mouseReleased()</b> function is called every time a mouse button * is released. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseReleased() { } /** * ( begin auto-generated from mouseClicked.xml ) * * The <b>mouseClicked()</b> function is called once after a mouse button * has been pressed and then released. * * ( end auto-generated ) * <h3>Advanced</h3> * When the mouse is clicked, mousePressed() will be called, * then mouseReleased(), then mouseClicked(). Note that * mousePressed is already false inside of mouseClicked(). * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mouseButton * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() * @see PApplet#mouseDragged() */ public void mouseClicked() { } /** * ( begin auto-generated from mouseDragged.xml ) * * The <b>mouseDragged()</b> function is called once every time the mouse * moves and a mouse button is pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseMoved() */ public void mouseDragged() { } /** * ( begin auto-generated from mouseMoved.xml ) * * The <b>mouseMoved()</b> function is called every time the mouse moves * and a mouse button is not pressed. * * ( end auto-generated ) * @webref input:mouse * @see PApplet#mouseX * @see PApplet#mouseY * @see PApplet#mousePressed * @see PApplet#mousePressed() * @see PApplet#mouseReleased() * @see PApplet#mouseDragged() */ public void mouseMoved() { } ////////////////////////////////////////////////////////////// KeyEvent keyEventQueue[] = new KeyEvent[10]; int keyEventCount; protected void enqueueKeyEvent(KeyEvent e) { synchronized (keyEventQueue) { if (keyEventCount == keyEventQueue.length) { KeyEvent temp[] = new KeyEvent[keyEventCount << 1]; System.arraycopy(keyEventQueue, 0, temp, 0, keyEventCount); keyEventQueue = temp; } keyEventQueue[keyEventCount++] = e; } } protected void dequeueKeyEvents() { synchronized (keyEventQueue) { for (int i = 0; i < keyEventCount; i++) { keyEvent = keyEventQueue[i]; handleKeyEvent(keyEvent); } keyEventCount = 0; } } protected void handleKeyEvent(KeyEvent event) { keyEvent = event; key = event.getKeyChar(); keyCode = event.getKeyCode(); keyEventMethods.handle(new Object[] { event }); switch (event.getID()) { case KeyEvent.KEY_PRESSED: keyPressed = true; keyPressed(); break; case KeyEvent.KEY_RELEASED: keyPressed = false; keyReleased(); break; case KeyEvent.KEY_TYPED: keyTyped(); break; } // if someone else wants to intercept the key, they should // set key to zero (or something besides the ESC). if (event.getID() == KeyEvent.KEY_PRESSED) { if (key == KeyEvent.VK_ESCAPE) { exit(); } // When running tethered to the Processing application, respond to // Ctrl-W (or Cmd-W) events by closing the sketch. Disable this behavior // when running independently, because this sketch may be one component // embedded inside an application that has its own close behavior. if (external && event.getModifiers() == MENU_SHORTCUT && event.getKeyCode() == 'W') { exit(); } } } protected void checkKeyEvent(KeyEvent event) { if (looping) { enqueueKeyEvent(event); } else { handleKeyEvent(event); } } /** * Overriding keyXxxxx(KeyEvent e) functions will cause the 'key', * 'keyCode', and 'keyEvent' variables to no longer work; * key events will no longer be queued until the end of draw(); * and the keyPressed(), keyReleased() and keyTyped() methods * will no longer be called. * * @nowebref */ public void keyPressed(KeyEvent e) { checkKeyEvent(e); } /** * @nowebref */ public void keyReleased(KeyEvent e) { checkKeyEvent(e); } /** * @nowebref */ public void keyTyped(KeyEvent e) { checkKeyEvent(e); } /** * * ( begin auto-generated from keyPressed.xml ) * * The <b>keyPressed()</b> function is called once every time a key is * pressed. The key that was pressed is stored in the <b>key</b> variable. * <br/> <br/> * For non-ASCII keys, use the <b>keyCode</b> variable. The keys included * in the ASCII specification (BACKSPACE, TAB, ENTER, RETURN, ESC, and * DELETE) do not require checking to see if they key is coded, and you * should simply use the <b>key</b> variable instead of <b>keyCode</b> If * you're making cross-platform projects, note that the ENTER key is * commonly used on PCs and Unix and the RETURN key is used instead on * Macintosh. Check for both ENTER and RETURN to make sure your program * will work for all platforms. * <br/> <br/> * Because of how operating systems handle key repeats, holding down a key * may cause multiple calls to keyPressed() (and keyReleased() as well). * The rate of repeat is set by the operating system and how each computer * is configured. * * ( end auto-generated ) * <h3>Advanced</h3> * * Called each time a single key on the keyboard is pressed. * Because of how operating systems handle key repeats, holding * down a key will cause multiple calls to keyPressed(), because * the OS repeat takes over. * <p> * Examples for key handling: * (Tested on Windows XP, please notify if different on other * platforms, I have a feeling Mac OS and Linux may do otherwise) * <PRE> * 1. Pressing 'a' on the keyboard: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * keyReleased with key == 'a' and keyCode == 'A' * * 2. Pressing 'A' on the keyboard: * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * * 3. Pressing 'shift', then 'a' on the keyboard (caps lock is off): * keyPressed with key == CODED and keyCode == SHIFT * keyPressed with key == 'A' and keyCode == 'A' * keyTyped with key == 'A' and keyCode == 0 * keyReleased with key == 'A' and keyCode == 'A' * keyReleased with key == CODED and keyCode == SHIFT * * 4. Holding down the 'a' key. * The following will happen several times, * depending on your machine's "key repeat rate" settings: * keyPressed with key == 'a' and keyCode == 'A' * keyTyped with key == 'a' and keyCode == 0 * When you finally let go, you'll get: * keyReleased with key == 'a' and keyCode == 'A' * * 5. Pressing and releasing the 'shift' key * keyPressed with key == CODED and keyCode == SHIFT * keyReleased with key == CODED and keyCode == SHIFT * (note there is no keyTyped) * * 6. Pressing the tab key in an applet with Java 1.4 will * normally do nothing, but PApplet dynamically shuts * this behavior off if Java 1.4 is in use (tested 1.4.2_05 Windows). * Java 1.1 (Microsoft VM) passes the TAB key through normally. * Not tested on other platforms or for 1.3. * </PRE> * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyReleased() */ public void keyPressed() { } /** * ( begin auto-generated from keyReleased.xml ) * * The <b>keyReleased()</b> function is called once every time a key is * released. The key that was released will be stored in the <b>key</b> * variable. See <b>key</b> and <b>keyReleased</b> for more information. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyPressed * @see PApplet#keyPressed() */ public void keyReleased() { } /** * ( begin auto-generated from keyTyped.xml ) * * The <b>keyTyped()</b> function is called once every time a key is * pressed, but action keys such as Ctrl, Shift, and Alt are ignored. * Because of how operating systems handle key repeats, holding down a key * will cause multiple calls to <b>keyTyped()</b>, the rate is set by the * operating system and how each computer is configured. * * ( end auto-generated ) * @webref input:keyboard * @see PApplet#keyPressed * @see PApplet#key * @see PApplet#keyCode * @see PApplet#keyReleased() */ public void keyTyped() { } ////////////////////////////////////////////////////////////// // i am focused man, and i'm not afraid of death. // and i'm going all out. i circle the vultures in a van // and i run the block. public void focusGained() { } public void focusGained(FocusEvent e) { focused = true; focusGained(); } public void focusLost() { } public void focusLost(FocusEvent e) { focused = false; focusLost(); } ////////////////////////////////////////////////////////////// // getting the time /** * ( begin auto-generated from millis.xml ) * * Returns the number of milliseconds (thousandths of a second) since * starting an applet. This information is often used for timing animation * sequences. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p> * This is a function, rather than a variable, because it may * change multiple times per frame. * * @webref input:time_date * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ public int millis() { return (int) (System.currentTimeMillis() - millisOffset); } /** * ( begin auto-generated from second.xml ) * * Processing communicates with the clock on your computer. The * <b>second()</b> function returns the current second as a value from 0 - 59. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int second() { return Calendar.getInstance().get(Calendar.SECOND); } /** * ( begin auto-generated from minute.xml ) * * Processing communicates with the clock on your computer. The * <b>minute()</b> function returns the current minute as a value from 0 - 59. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * * */ static public int minute() { return Calendar.getInstance().get(Calendar.MINUTE); } /** * ( begin auto-generated from hour.xml ) * * Processing communicates with the clock on your computer. The * <b>hour()</b> function returns the current hour as a value from 0 - 23. * * ( end auto-generated ) * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#day() * @see PApplet#month() * @see PApplet#year() * */ static public int hour() { return Calendar.getInstance().get(Calendar.HOUR_OF_DAY); } /** * ( begin auto-generated from day.xml ) * * Processing communicates with the clock on your computer. The * <b>day()</b> function returns the current day as a value from 1 - 31. * * ( end auto-generated ) * <h3>Advanced</h3> * Get the current day of the month (1 through 31). * <p> * If you're looking for the day of the week (M-F or whatever) * or day of the year (1..365) then use java's Calendar.get() * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#month() * @see PApplet#year() */ static public int day() { return Calendar.getInstance().get(Calendar.DAY_OF_MONTH); } /** * ( begin auto-generated from month.xml ) * * Processing communicates with the clock on your computer. The * <b>month()</b> function returns the current month as a value from 1 - 12. * * ( end auto-generated ) * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#year() */ static public int month() { // months are number 0..11 so change to colloquial 1..12 return Calendar.getInstance().get(Calendar.MONTH) + 1; } /** * ( begin auto-generated from year.xml ) * * Processing communicates with the clock on your computer. The * <b>year()</b> function returns the current year as an integer (2003, * 2004, 2005, etc). * * ( end auto-generated ) * The <b>year()</b> function returns the current year as an integer (2003, 2004, 2005, etc). * * @webref input:time_date * @see PApplet#millis() * @see PApplet#second() * @see PApplet#minute() * @see PApplet#hour() * @see PApplet#day() * @see PApplet#month() */ static public int year() { return Calendar.getInstance().get(Calendar.YEAR); } ////////////////////////////////////////////////////////////// // controlling time (playing god) /** * ( begin auto-generated from frameRate.xml ) * * Specifies the number of frames to be displayed every second. If the * processor is not fast enough to maintain the specified rate, it will not * be achieved. For example, the function call <b>frameRate(30)</b> will * attempt to refresh 30 times a second. It is recommended to set the frame * rate within <b>setup()</b>. The default rate is 60 frames per second. * * ( end auto-generated ) * <h3>Advanced</h3> * Set a target frameRate. This will cause delay() to be called * after each frame so that the sketch synchronizes to a particular speed. * Note that this only sets the maximum frame rate, it cannot be used to * make a slow sketch go faster. Sketches have no default frame rate * setting, and will attempt to use maximum processor power to achieve * maximum speed. * @webref environment * @param newRateTarget number of frames per second * @see PApplet#setup() * @see PApplet#draw() * @see PApplet#loop() * @see PApplet#noLoop() * @see PApplet#redraw() */ public void frameRate(float newRateTarget) { frameRateTarget = newRateTarget; frameRatePeriod = (long) (1000000000.0 / frameRateTarget); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from param.xml ) * * Reads the value of a param. Values are always read as a String so if you * want them to be an integer or other datatype they must be converted. The * <b>param()</b> function will only work in a web browser. The function * should be called inside <b>setup()</b>, otherwise the applet may not yet * be initialized and connected to its parent web browser. * * ( end auto-generated ) * * @webref input:web * @usage Web * * @param what name of the param to read */ public String param(String what) { if (online) { return getParameter(what); } else { System.err.println("param() only works inside a web browser"); } return null; } /** * ( begin auto-generated from status.xml ) * * Displays message in the browser's status area. This is the text area in * the lower left corner of the browser. The <b>status()</b> function will * only work when the Processing program is running in a web browser. * * ( end auto-generated ) * <h3>Advanced</h3> * Show status in the status bar of a web browser, or in the * System.out console. Eventually this might show status in the * p5 environment itself, rather than relying on the console. * * @webref input:web * @usage Web * @param what any valid String */ public void status(String what) { if (online) { showStatus(what); } else { System.out.println(what); // something more interesting? } } public void link(String here) { link(here, null); } /** * ( begin auto-generated from link.xml ) * * Links to a webpage either in the same window or in a new window. The * complete URL must be specified. * * ( end auto-generated ) * <h3>Advanced</h3> * Link to an external page without all the muss. * <p> * When run with an applet, uses the browser to open the url, * for applications, attempts to launch a browser with the url. * <p> * Works on Mac OS X and Windows. For Linux, use: * <PRE>open(new String[] { "firefox", url });</PRE> * or whatever you want as your browser, since Linux doesn't * yet have a standard method for launching URLs. * * @webref input:web * @param url complete url as a String in quotes * @param frameTitle name of the window to load the URL as a string in quotes * */ public void link(String url, String frameTitle) { if (online) { try { if (frameTitle == null) { getAppletContext().showDocument(new URL(url)); } else { getAppletContext().showDocument(new URL(url), frameTitle); } } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not open " + url); } } else { try { if (platform == WINDOWS) { // the following uses a shell execute to launch the .html file // note that under cygwin, the .html files have to be chmodded +x // after they're unpacked from the zip file. i don't know why, // and don't understand what this does in terms of windows // permissions. without the chmod, the command prompt says // "Access is denied" in both cygwin and the "dos" prompt. //Runtime.getRuntime().exec("cmd /c " + currentDir + "\\reference\\" + // referenceFile + ".html"); // replace ampersands with control sequence for DOS. // solution contributed by toxi on the bugs board. url = url.replaceAll("&","^&"); // open dos prompt, give it 'start' command, which will // open the url properly. start by itself won't work since // it appears to need cmd Runtime.getRuntime().exec("cmd /c start " + url); } else if (platform == MACOSX) { //com.apple.mrj.MRJFileUtils.openURL(url); try { // Class<?> mrjFileUtils = Class.forName("com.apple.mrj.MRJFileUtils"); // Method openMethod = // mrjFileUtils.getMethod("openURL", new Class[] { String.class }); Class<?> eieio = Class.forName("com.apple.eio.FileManager"); Method openMethod = eieio.getMethod("openURL", new Class[] { String.class }); openMethod.invoke(null, new Object[] { url }); } catch (Exception e) { e.printStackTrace(); } } else { //throw new RuntimeException("Can't open URLs for this platform"); // Just pass it off to open() and hope for the best open(url); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not open " + url); } } } /** * ( begin auto-generated from open.xml ) * * Attempts to open an application or file using your platform's launcher. * The <b>file</b> parameter is a String specifying the file name and * location. The location parameter must be a full path name, or the name * of an executable in the system's PATH. In most cases, using a full path * is the best option, rather than relying on the system PATH. Be sure to * make the file executable before attempting to open it (chmod +x). * <br/> <br/> * The <b>args</b> parameter is a String or String array which is passed to * the command line. If you have multiple parameters, e.g. an application * and a document, or a command with multiple switches, use the version * that takes a String array, and place each individual item in a separate * element. * <br/> <br/> * If args is a String (not an array), then it can only be a single file or * application with no parameters. It's not the same as executing that * String using a shell. For instance, open("jikes -help") will not work properly. * <br/> <br/> * This function behaves differently on each platform. On Windows, the * parameters are sent to the Windows shell via "cmd /c". On Mac OS X, the * "open" command is used (type "man open" in Terminal.app for * documentation). On Linux, it first tries gnome-open, then kde-open, but * if neither are available, it sends the command to the shell without any * alterations. * <br/> <br/> * For users familiar with Java, this is not quite the same as * Runtime.exec(), because the launcher command is prepended. Instead, the * <b>exec(String[])</b> function is a shortcut for * Runtime.getRuntime.exec(String[]). * * ( end auto-generated ) * @webref input:files * @param filename name of the file * @usage Application */ static public void open(String filename) { open(new String[] { filename }); } static String openLauncher; /** * Launch a process using a platforms shell. This version uses an array * to make it easier to deal with spaces in the individual elements. * (This avoids the situation of trying to put single or double quotes * around different bits). * * @param argv list of commands passed to the command line */ static public Process open(String argv[]) { String[] params = null; if (platform == WINDOWS) { // just launching the .html file via the shell works // but make sure to chmod +x the .html files first // also place quotes around it in case there's a space // in the user.dir part of the url params = new String[] { "cmd", "/c" }; } else if (platform == MACOSX) { params = new String[] { "open" }; } else if (platform == LINUX) { if (openLauncher == null) { // Attempt to use gnome-open try { Process p = Runtime.getRuntime().exec(new String[] { "gnome-open" }); /*int result =*/ p.waitFor(); // Not installed will throw an IOException (JDK 1.4.2, Ubuntu 7.04) openLauncher = "gnome-open"; } catch (Exception e) { } } if (openLauncher == null) { // Attempt with kde-open try { Process p = Runtime.getRuntime().exec(new String[] { "kde-open" }); /*int result =*/ p.waitFor(); openLauncher = "kde-open"; } catch (Exception e) { } } if (openLauncher == null) { System.err.println("Could not find gnome-open or kde-open, " + "the open() command may not work."); } if (openLauncher != null) { params = new String[] { openLauncher }; } //} else { // give up and just pass it to Runtime.exec() //open(new String[] { filename }); //params = new String[] { filename }; } if (params != null) { // If the 'open', 'gnome-open' or 'cmd' are already included if (params[0].equals(argv[0])) { // then don't prepend those params again return exec(argv); } else { params = concat(params, argv); return exec(params); } } else { return exec(argv); } } static public Process exec(String[] argv) { try { return Runtime.getRuntime().exec(argv); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("Could not open " + join(argv, ' ')); } } ////////////////////////////////////////////////////////////// /** * Function for an applet/application to kill itself and * display an error. Mostly this is here to be improved later. */ public void die(String what) { dispose(); throw new RuntimeException(what); } /** * Same as above but with an exception. Also needs work. */ public void die(String what, Exception e) { if (e != null) e.printStackTrace(); die(what); } /** * ( begin auto-generated from exit.xml ) * * Quits/stops/exits the program. Programs without a <b>draw()</b> function * exit automatically after the last line has run, but programs with * <b>draw()</b> run continuously until the program is manually stopped or * <b>exit()</b> is run.<br /> * <br /> * Rather than terminating immediately, <b>exit()</b> will cause the sketch * to exit after <b>draw()</b> has completed (or after <b>setup()</b> * completes if called during the <b>setup()</b> function).<br /> * <br /> * For Java programmers, this is <em>not</em> the same as System.exit(). * Further, System.exit() should not be used because closing out an * application while <b>draw()</b> is running may cause a crash * (particularly with P3D). * * ( end auto-generated ) * @webref structure */ public void exit() { if (thread == null) { // exit immediately, dispose() has already been called, // meaning that the main thread has long since exited exitActual(); } else if (looping) { // dispose() will be called as the thread exits finished = true; // tell the code to call exit2() to do a System.exit() // once the next draw() has completed exitCalled = true; } else if (!looping) { // if not looping, shut down things explicitly, // because the main thread will be sleeping dispose(); // now get out exitActual(); } } void exitActual() { try { System.exit(0); } catch (SecurityException e) { // don't care about applet security exceptions } } /** * Called to dispose of resources and shut down the sketch. * Destroys the thread, dispose the renderer,and notify listeners. * <p> * Not to be called or overriden by users. If called multiple times, * will only notify listeners once. Register a dispose listener instead. */ public void dispose() { // moved here from stop() finished = true; // let the sketch know it is shut down time // don't run the disposers twice if (thread == null) return; thread = null; // shut down renderer if (g != null) g.dispose(); disposeMethods.handle(); } ////////////////////////////////////////////////////////////// /** * Call a method in the current class based on its name. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void method(String name) { try { Method method = getClass().getMethod(name, new Class[] {}); method.invoke(this, new Object[] { }); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.getTargetException().printStackTrace(); } catch (NoSuchMethodException nsme) { System.err.println("There is no public " + name + "() method " + "in the class " + getClass().getName()); } catch (Exception e) { e.printStackTrace(); } } /** * Launch a new thread and call the specified function from that new thread. * This is a very simple way to do a thread without needing to get into * classes, runnables, etc. * <p/> * Note that the function being called must be public. Inside the PDE, * 'public' is automatically added, but when used without the preprocessor, * (like from Eclipse) you'll have to do it yourself. */ public void thread(final String name) { Thread later = new Thread() { public void run() { method(name); } }; later.start(); } ////////////////////////////////////////////////////////////// // SCREEN GRABASS /** * ( begin auto-generated from save.xml ) * * Saves an image from the display window. Images are saved in TIFF, TARGA, * JPEG, and PNG format depending on the extension within the * <b>filename</b> parameter. For example, "image.tif" will have a TIFF * image and "image.png" will save a PNG image. If no extension is included * in the filename, the image will save in TIFF format and <b>.tif</b> will * be added to the name. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu. It is not possible to use <b>save()</b> while running the program * in a web browser. * <br/> images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @param filename any sequence of letters and numbers * @see PApplet#saveFrame() * @see PApplet#createGraphics(int, int, String) */ public void save(String filename) { g.save(savePath(filename)); } /** */ public void saveFrame() { try { g.save(savePath("screen-" + nf(frameCount, 4) + ".tif")); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * ( begin auto-generated from saveFrame.xml ) * * Saves a numbered sequence of images, one image each time the function is * run. To save an image that is identical to the display window, run the * function at the end of <b>draw()</b> or within mouse and key events such * as <b>mousePressed()</b> and <b>keyPressed()</b>. If <b>saveFrame()</b> * is called without parameters, it will save the files as screen-0000.tif, * screen-0001.tif, etc. It is possible to specify the name of the sequence * with the <b>filename</b> parameter and make the choice of saving TIFF, * TARGA, PNG, or JPEG files with the <b>ext</b> parameter. These image * sequences can be loaded into programs such as Apple's QuickTime software * and made into movies. These files are saved to the sketch's folder, * which may be opened by selecting "Show sketch folder" from the "Sketch" * menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * All images saved from the main drawing window will be opaque. To save * images without a background, use <b>createGraphics()</b>. * * ( end auto-generated ) * @webref output:image * @see PApplet#save(String) * @see PApplet#createGraphics(int, int, String, String) * @param what any sequence of letters or numbers that ends with either ".tif", ".tga", ".jpg", or ".png" */ public void saveFrame(String what) { try { g.save(savePath(insertFrame(what))); } catch (SecurityException se) { System.err.println("Can't use saveFrame() when running in a browser, " + "unless using a signed applet."); } } /** * Check a string for #### signs to see if the frame number should be * inserted. Used for functions like saveFrame() and beginRecord() to * replace the # marks with the frame number. If only one # is used, * it will be ignored, under the assumption that it's probably not * intended to be the frame number. */ protected String insertFrame(String what) { int first = what.indexOf('#'); int last = what.lastIndexOf('#'); if ((first != -1) && (last - first > 0)) { String prefix = what.substring(0, first); int count = last - first + 1; String suffix = what.substring(last + 1); return prefix + nf(frameCount, count) + suffix; } return what; // no change } ////////////////////////////////////////////////////////////// // CURSOR // int cursorType = ARROW; // cursor type boolean cursorVisible = true; // cursor visibility flag PImage invisibleCursor; /** * Set the cursor type * @param cursorType either ARROW, CROSS, HAND, MOVE, TEXT, WAIT */ public void cursor(int cursorType) { setCursor(Cursor.getPredefinedCursor(cursorType)); cursorVisible = true; this.cursorType = cursorType; } /** * Replace the cursor with the specified PImage. The x- and y- * coordinate of the center will be the center of the image. */ public void cursor(PImage image) { cursor(image, image.width/2, image.height/2); } /** * ( begin auto-generated from cursor.xml ) * * Sets the cursor to a predefined symbol, an image, or makes it visible if * already hidden. If you are trying to set an image as the cursor, it is * recommended to make the size 16x16 or 32x32 pixels. It is not possible * to load an image as the cursor if you are exporting your program for the * Web and not all MODES work with all Web browsers. The values for * parameters <b>x</b> and <b>y</b> must be less than the dimensions of the image. * <br /> <br /> * Setting or hiding the cursor generally does not work with "Present" mode * (when running full-screen). * * ( end auto-generated ) * <h3>Advanced</h3> * Set a custom cursor to an image with a specific hotspot. * Only works with JDK 1.2 and later. * Currently seems to be broken on Java 1.4 for Mac OS X * <p> * Based on code contributed by Amit Pitaru, plus additional * code to handle Java versions via reflection by Jonathan Feinberg. * Reflection removed for release 0128 and later. * @webref environment * @see PApplet#noCursor() * @param image any variable of type PImage * @param hotspotX the horizonal active spot of the cursor * @param hotspotY the vertical active spot of the cursor */ public void cursor(PImage image, int hotspotX, int hotspotY) { // don't set this as cursor type, instead use cursor_type // to save the last cursor used in case cursor() is called //cursor_type = Cursor.CUSTOM_CURSOR; Image jimage = createImage(new MemoryImageSource(image.width, image.height, image.pixels, 0, image.width)); Point hotspot = new Point(hotspotX, hotspotY); Toolkit tk = Toolkit.getDefaultToolkit(); Cursor cursor = tk.createCustomCursor(jimage, hotspot, "Custom Cursor"); setCursor(cursor); cursorVisible = true; } /** * Show the cursor after noCursor() was called. * Notice that the program remembers the last set cursor type */ public void cursor() { // maybe should always set here? seems dangerous, since // it's likely that java will set the cursor to something // else on its own, and the applet will be stuck b/c bagel // thinks that the cursor is set to one particular thing if (!cursorVisible) { cursorVisible = true; setCursor(Cursor.getPredefinedCursor(cursorType)); } } /** * ( begin auto-generated from noCursor.xml ) * * Hides the cursor from view. Will not work when running the program in a * web browser or when running in full screen (Present) mode. * * ( end auto-generated ) * <h3>Advanced</h3> * Hide the cursor by creating a transparent image * and using it as a custom cursor. * @webref environment * @see PApplet#cursor() * @usage Application */ public void noCursor() { if (!cursorVisible) return; // don't hide if already hidden. if (invisibleCursor == null) { invisibleCursor = new PImage(16, 16, ARGB); } // was formerly 16x16, but the 0x0 was added by jdf as a fix // for macosx, which wasn't honoring the invisible cursor cursor(invisibleCursor, 8, 8); cursorVisible = false; } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from print.xml ) * * Writes to the console area of the Processing environment. This is often * helpful for looking at the data a program is producing. The companion * function <b>println()</b> works like <b>print()</b>, but creates a new * line of text for each call to the function. Individual elements can be * separated with quotes ("") and joined with the addition operator (+).<br /> * <br /> * Beginning with release 0125, to print the contents of an array, use * println(). There's no sensible way to do a <b>print()</b> of an array, * because there are too many possibilities for how to separate the data * (spaces, commas, etc). If you want to print an array as a single line, * use <b>join()</b>. With <b>join()</b>, you can choose any delimiter you * like and <b>print()</b> the result.<br /> * <br /> * Using <b>print()</b> on an object will output <b>null</b>, a memory * location that may look like "@10be08," or the result of the * <b>toString()</b> method from the object that's being printed. Advanced * users who want more useful output when calling <b>print()</b> on their * own classes can add a <b>toString()</b> method to the class that returns * a String. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @param what boolean, byte, char, color, int, float, String, Object * @see PApplet#println(byte) * @see PApplet#join(String[], char) */ static public void print(byte what) { System.out.print(what); System.out.flush(); } static public void print(boolean what) { System.out.print(what); System.out.flush(); } static public void print(char what) { System.out.print(what); System.out.flush(); } static public void print(int what) { System.out.print(what); System.out.flush(); } static public void print(float what) { System.out.print(what); System.out.flush(); } static public void print(String what) { System.out.print(what); System.out.flush(); } static public void print(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.print("null"); } else { System.out.println(what.toString()); } } // /** * ( begin auto-generated from println.xml ) * * Writes to the text area of the Processing environment's console. This is * often helpful for looking at the data a program is producing. Each call * to this function creates a new line of output. Individual elements can * be separated with quotes ("") and joined with the string concatenation * operator (+). See <b>print()</b> for more about what to expect in the output. * <br/><br/> <b>println()</b> on an array (by itself) will write the * contents of the array to the console. This is often helpful for looking * at the data a program is producing. A new line is put between each * element of the array. This function can only print one dimensional * arrays. For arrays with higher dimensions, the result will be closer to * that of <b>print()</b>. * * ( end auto-generated ) * @webref output:text_area * @usage IDE * @see PApplet#print(byte) */ static public void println() { System.out.println(); } // /** * @param what boolean, byte, char, color, int, float, String, Object */ static public void println(byte what) { print(what); System.out.println(); } static public void println(boolean what) { print(what); System.out.println(); } static public void println(char what) { print(what); System.out.println(); } static public void println(int what) { print(what); System.out.println(); } static public void println(float what) { print(what); System.out.println(); } static public void println(String what) { print(what); System.out.println(); } static public void println(Object what) { if (what == null) { // special case since this does fuggly things on > 1.1 System.out.println("null"); } else { String name = what.getClass().getName(); if (name.charAt(0) == '[') { switch (name.charAt(1)) { case '[': // don't even mess with multi-dimensional arrays (case '[') // or anything else that's not int, float, boolean, char System.out.println(what); break; case 'L': // print a 1D array of objects as individual elements Object poo[] = (Object[]) what; for (int i = 0; i < poo.length; i++) { if (poo[i] instanceof String) { System.out.println("[" + i + "] \"" + poo[i] + "\""); } else { System.out.println("[" + i + "] " + poo[i]); } } break; case 'Z': // boolean boolean zz[] = (boolean[]) what; for (int i = 0; i < zz.length; i++) { System.out.println("[" + i + "] " + zz[i]); } break; case 'B': // byte byte bb[] = (byte[]) what; for (int i = 0; i < bb.length; i++) { System.out.println("[" + i + "] " + bb[i]); } break; case 'C': // char char cc[] = (char[]) what; for (int i = 0; i < cc.length; i++) { System.out.println("[" + i + "] '" + cc[i] + "'"); } break; case 'I': // int int ii[] = (int[]) what; for (int i = 0; i < ii.length; i++) { System.out.println("[" + i + "] " + ii[i]); } break; case 'F': // float float ff[] = (float[]) what; for (int i = 0; i < ff.length; i++) { System.out.println("[" + i + "] " + ff[i]); } break; case 'D': // double double dd[] = (double[]) what; for (int i = 0; i < dd.length; i++) { System.out.println("[" + i + "] " + dd[i]); } break; default: System.out.println(what); } } else { // not an array System.out.println(what); } } } // /* // not very useful, because it only works for public (and protected?) // fields of a class, not local variables to methods public void printvar(String name) { try { Field field = getClass().getDeclaredField(name); println(name + " = " + field.get(this)); } catch (Exception e) { e.printStackTrace(); } } */ ////////////////////////////////////////////////////////////// // MATH // lots of convenience methods for math with floats. // doubles are overkill for processing applets, and casting // things all the time is annoying, thus the functions below. /** * ( begin auto-generated from abs.xml ) * * Calculates the absolute value (magnitude) of a number. The absolute * value of a number is always positive. * * ( end auto-generated ) * @webref math:calculation * @param n number to compute */ static public final float abs(float n) { return (n < 0) ? -n : n; } static public final int abs(int n) { return (n < 0) ? -n : n; } /** * ( begin auto-generated from sq.xml ) * * Squares a number (multiplies a number by itself). The result is always a * positive number, as multiplying two negative numbers always yields a * positive result. For example, -1 * -1 = 1. * * ( end auto-generated ) * @webref math:calculation * @param a number to square * @see PApplet#sqrt(float) */ static public final float sq(float a) { return a*a; } /** * ( begin auto-generated from sqrt.xml ) * * Calculates the square root of a number. The square root of a number is * always positive, even though there may be a valid negative root. The * square root <b>s</b> of number <b>a</b> is such that <b>s*s = a</b>. It * is the opposite of squaring. * * ( end auto-generated ) * @webref math:calculation * @param a non-negative number * @see PApplet#pow(float, float) * @see PApplet#sq(float) */ static public final float sqrt(float a) { return (float)Math.sqrt(a); } /** * ( begin auto-generated from log.xml ) * * Calculates the natural logarithm (the base-<i>e</i> logarithm) of a * number. This function expects the values greater than 0.0. * * ( end auto-generated ) * @webref math:calculation * @param a number greater than 0.0 */ static public final float log(float a) { return (float)Math.log(a); } /** * ( begin auto-generated from exp.xml ) * * Returns Euler's number <i>e</i> (2.71828...) raised to the power of the * <b>value</b> parameter. * * ( end auto-generated ) * @webref math:calculation * @param a exponent to raise */ static public final float exp(float a) { return (float)Math.exp(a); } /** * ( begin auto-generated from pow.xml ) * * Facilitates exponential expressions. The <b>pow()</b> function is an * efficient way of multiplying numbers by themselves (or their reciprocal) * in large quantities. For example, <b>pow(3, 5)</b> is equivalent to the * expression 3*3*3*3*3 and <b>pow(3, -5)</b> is equivalent to 1 / 3*3*3*3*3. * * ( end auto-generated ) * @webref math:calculation * @param a base of the exponential expression * @param b power of which to raise the base * @see PApplet#sqrt(float) */ static public final float pow(float a, float b) { return (float)Math.pow(a, b); } /** * ( begin auto-generated from max.xml ) * * Determines the largest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number to compare * @param b second number to compare * @see PApplet#min(float, float, float) */ static public final int max(int a, int b) { return (a > b) ? a : b; } static public final float max(float a, float b) { return (a > b) ? a : b; } /* static public final double max(double a, double b) { return (a > b) ? a : b; } */ /** * @param c third number to compare */ static public final int max(int a, int b, int c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } static public final float max(float a, float b, float c) { return (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); } /** * @param list list to compare */ static public final int max(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } static public final float max(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } /** * Find the maximum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The maximum value */ /* static public final double max(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double max = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] > max) max = list[i]; } return max; } */ static public final int min(int a, int b) { return (a < b) ? a : b; } static public final float min(float a, float b) { return (a < b) ? a : b; } /* static public final double min(double a, double b) { return (a < b) ? a : b; } */ static public final int min(int a, int b, int c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /** * ( begin auto-generated from min.xml ) * * Determines the smallest value in a sequence of numbers. * * ( end auto-generated ) * @webref math:calculation * @param a first number * @param b second number * @param c third number * @see PApplet#max(float, float, float) */ static public final float min(float a, float b, float c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } /* static public final double min(double a, double b, double c) { return (a < b) ? ((a < c) ? a : c) : ((b < c) ? b : c); } */ /** * @param list int or float array */ static public final int min(int[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } int min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } static public final float min(float[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } float min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } /** * Find the minimum value in an array. * Throws an ArrayIndexOutOfBoundsException if the array is length 0. * @param list the source array * @return The minimum value */ /* static public final double min(double[] list) { if (list.length == 0) { throw new ArrayIndexOutOfBoundsException(ERROR_MIN_MAX); } double min = list[0]; for (int i = 1; i < list.length; i++) { if (list[i] < min) min = list[i]; } return min; } */ static public final int constrain(int amt, int low, int high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from constrain.xml ) * * Constrains a value to not exceed a maximum and minimum value. * * ( end auto-generated ) * @webref math:calculation * @param amt the value to constrain * @param low minimum limit * @param high maximum limit * @see PApplet#max(float, float, float) * @see PApplet#min(float, float, float) */ static public final float constrain(float amt, float low, float high) { return (amt < low) ? low : ((amt > high) ? high : amt); } /** * ( begin auto-generated from sin.xml ) * * Calculates the sine of an angle. This function expects the values of the * <b>angle</b> parameter to be provided in radians (values from 0 to * 6.28). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float sin(float angle) { return (float)Math.sin(angle); } /** * ( begin auto-generated from cos.xml ) * * Calculates the cosine of an angle. This function expects the values of * the <b>angle</b> parameter to be provided in radians (values from 0 to * PI*2). Values are returned in the range -1 to 1. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#sin(float) * @see PApplet#tan(float) * @see PApplet#radians(float) */ static public final float cos(float angle) { return (float)Math.cos(angle); } /** * ( begin auto-generated from tan.xml ) * * Calculates the ratio of the sine and cosine of an angle. This function * expects the values of the <b>angle</b> parameter to be provided in * radians (values from 0 to PI*2). Values are returned in the range * <b>infinity</b> to <b>-infinity</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param angle an angle in radians * @see PApplet#cos(float) * @see PApplet#sin(float) * @see PApplet#radians(float) */ static public final float tan(float angle) { return (float)Math.tan(angle); } /** * ( begin auto-generated from asin.xml ) * * The inverse of <b>sin()</b>, returns the arc sine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>-PI/2</b> to <b>PI/2</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc sine is to be returned * @see PApplet#sin(float) * @see PApplet#acos(float) * @see PApplet#atan(float) */ static public final float asin(float value) { return (float)Math.asin(value); } /** * ( begin auto-generated from acos.xml ) * * The inverse of <b>cos()</b>, returns the arc cosine of a value. This * function expects the values in the range of -1 to 1 and values are * returned in the range <b>0</b> to <b>PI (3.1415927)</b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value the value whose arc cosine is to be returned * @see PApplet#cos(float) * @see PApplet#asin(float) * @see PApplet#atan(float) */ static public final float acos(float value) { return (float)Math.acos(value); } /** * ( begin auto-generated from atan.xml ) * * The inverse of <b>tan()</b>, returns the arc tangent of a value. This * function expects the values in the range of -Infinity to Infinity * (exclusive) and values are returned in the range <b>-PI/2</b> to <b>PI/2 </b>. * * ( end auto-generated ) * @webref math:trigonometry * @param value -Infinity to Infinity (exclusive) * @see PApplet#tan(float) * @see PApplet#asin(float) * @see PApplet#acos(float) */ static public final float atan(float value) { return (float)Math.atan(value); } /** * ( begin auto-generated from atan2.xml ) * * Calculates the angle (in radians) from a specified point to the * coordinate origin as measured from the positive x-axis. Values are * returned as a <b>float</b> in the range from <b>PI</b> to <b>-PI</b>. * The <b>atan2()</b> function is most often used for orienting geometry to * the position of the cursor. Note: The y-coordinate of the point is the * first parameter and the x-coordinate is the second due the the structure * of calculating the tangent. * * ( end auto-generated ) * @webref math:trigonometry * @param a y-coordinate of the point * @param b x-coordinate of the point * @see PApplet#tan(float) */ static public final float atan2(float a, float b) { return (float)Math.atan2(a, b); } /** * ( begin auto-generated from degrees.xml ) * * Converts a radian measurement to its corresponding value in degrees. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param radians radian value to convert to degrees * @see PApplet#radians(float) */ static public final float degrees(float radians) { return radians * RAD_TO_DEG; } /** * ( begin auto-generated from radians.xml ) * * Converts a degree measurement to its corresponding value in radians. * Radians and degrees are two ways of measuring the same thing. There are * 360 degrees in a circle and 2*PI radians in a circle. For example, * 90&deg; = PI/2 = 1.5707964. All trigonometric functions in Processing * require their parameters to be specified in radians. * * ( end auto-generated ) * @webref math:trigonometry * @param degrees degree value to convert to radians * @see PApplet#degrees(float) */ static public final float radians(float degrees) { return degrees * DEG_TO_RAD; } /** * ( begin auto-generated from ceil.xml ) * * Calculates the closest int value that is greater than or equal to the * value of the parameter. For example, <b>ceil(9.03)</b> returns the value 10. * * ( end auto-generated ) * @webref math:calculation * @param what number to round up * @see PApplet#floor(float) * @see PApplet#round(float) */ static public final int ceil(float what) { return (int) Math.ceil(what); } /** * ( begin auto-generated from floor.xml ) * * Calculates the closest int value that is less than or equal to the value * of the parameter. * * ( end auto-generated ) * @webref math:calculation * @param what number to round down * @see PApplet#ceil(float) * @see PApplet#round(float) */ static public final int floor(float what) { return (int) Math.floor(what); } /** * ( begin auto-generated from round.xml ) * * Calculates the integer closest to the <b>value</b> parameter. For * example, <b>round(9.2)</b> returns the value 9. * * ( end auto-generated ) * @webref math:calculation * @param what number to round * @see PApplet#floor(float) * @see PApplet#ceil(float) */ static public final int round(float what) { return Math.round(what); } static public final float mag(float a, float b) { return (float)Math.sqrt(a*a + b*b); } /** * ( begin auto-generated from mag.xml ) * * Calculates the magnitude (or length) of a vector. A vector is a * direction in space commonly used in computer graphics and linear * algebra. Because it has no "start" position, the magnitude of a vector * can be thought of as the distance from coordinate (0,0) to its (x,y) * value. Therefore, mag() is a shortcut for writing "dist(0, 0, x, y)". * * ( end auto-generated ) * @webref math:calculation * @param a first value * @param b second value * @param c third value * @see PApplet#dist(float, float, float, float) */ static public final float mag(float a, float b, float c) { return (float)Math.sqrt(a*a + b*b + c*c); } static public final float dist(float x1, float y1, float x2, float y2) { return sqrt(sq(x2-x1) + sq(y2-y1)); } /** * ( begin auto-generated from dist.xml ) * * Calculates the distance between two points. * * ( end auto-generated ) * @webref math:calculation * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param z1 z-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param z2 z-coordinate of the second point */ static public final float dist(float x1, float y1, float z1, float x2, float y2, float z2) { return sqrt(sq(x2-x1) + sq(y2-y1) + sq(z2-z1)); } /** * ( begin auto-generated from lerp.xml ) * * Calculates a number between two numbers at a specific increment. The * <b>amt</b> parameter is the amount to interpolate between the two values * where 0.0 equal to the first point, 0.1 is very near the first point, * 0.5 is half-way in between, etc. The lerp function is convenient for * creating motion along a straight path and for drawing dotted lines. * * ( end auto-generated ) * @webref math:calculation * @param start first value * @param stop second value * @param amt float between 0.0 and 1.0 * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ static public final float lerp(float start, float stop, float amt) { return start + (stop-start) * amt; } /** * ( begin auto-generated from norm.xml ) * * Normalizes a number from another range into a value between 0 and 1. * <br/> <br/> * Identical to map(value, low, high, 0, 1); * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param start lower bound of the value's current range * @param stop upper bound of the value's current range * @see PApplet#map(float, float, float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float norm(float value, float start, float stop) { return (value - start) / (stop - start); } /** * ( begin auto-generated from map.xml ) * * Re-maps a number from one range to another. In the example above, * the number '25' is converted from a value in the range 0..100 into * a value that ranges from the left edge (0) to the right edge (width) * of the screen. * <br/> <br/> * Numbers outside the range are not clamped to 0 and 1, because * out-of-range values are often intentional and useful. * * ( end auto-generated ) * @webref math:calculation * @param value the incoming value to be converted * @param istart lower bound of the value's current range * @param istop upper bound of the value's current range * @param ostart lower bound of the value's target range * @param ostop upper bound of the value's target range * @see PApplet#norm(float, float, float) * @see PApplet#lerp(float, float, float) */ static public final float map(float value, float istart, float istop, float ostart, float ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } /* static public final double map(double value, double istart, double istop, double ostart, double ostop) { return ostart + (ostop - ostart) * ((value - istart) / (istop - istart)); } */ ////////////////////////////////////////////////////////////// // RANDOM NUMBERS Random internalRandom; /** * */ public final float random(float howbig) { // for some reason (rounding error?) Math.random() * 3 // can sometimes return '3' (once in ~30 million tries) // so a check was added to avoid the inclusion of 'howbig' // avoid an infinite loop if (howbig == 0) return 0; // internal random number object if (internalRandom == null) internalRandom = new Random(); float value = 0; do { //value = (float)Math.random() * howbig; value = internalRandom.nextFloat() * howbig; } while (value == howbig); return value; } /** * ( begin auto-generated from random.xml ) * * Generates random numbers. Each time the <b>random()</b> function is * called, it returns an unexpected value within the specified range. If * one parameter is passed to the function it will return a <b>float</b> * between zero and the value of the <b>high</b> parameter. The function * call <b>random(5)</b> returns values between 0 and 5 (starting at zero, * up to but not including 5). If two parameters are passed, it will return * a <b>float</b> with a value between the the parameters. The function * call <b>random(-5, 10.2)</b> returns values starting at -5 up to (but * not including) 10.2. To convert a floating-point random number to an * integer, use the <b>int()</b> function. * * ( end auto-generated ) * @webref math:random * @param howsmall lower limit * @param howbig upper limit * @see PApplet#randomSeed(long) * @see PApplet#noise(float, float, float) */ public final float random(float howsmall, float howbig) { if (howsmall >= howbig) return howsmall; float diff = howbig - howsmall; return random(diff) + howsmall; } /** * ( begin auto-generated from randomSeed.xml ) * * Sets the seed value for <b>random()</b>. By default, <b>random()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param what seed value * @see PApplet#random(float,float) * @see PApplet#noise(float, float, float) * @see PApplet#noiseSeed(long) */ public final void randomSeed(long what) { // internal random number object if (internalRandom == null) internalRandom = new Random(); internalRandom.setSeed(what); } ////////////////////////////////////////////////////////////// // PERLIN NOISE // [toxi 040903] // octaves and amplitude amount per octave are now user controlled // via the noiseDetail() function. // [toxi 030902] // cleaned up code and now using bagel's cosine table to speed up // [toxi 030901] // implementation by the german demo group farbrausch // as used in their demo "art": http://www.farb-rausch.de/fr010src.zip static final int PERLIN_YWRAPB = 4; static final int PERLIN_YWRAP = 1<<PERLIN_YWRAPB; static final int PERLIN_ZWRAPB = 8; static final int PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB; static final int PERLIN_SIZE = 4095; int perlin_octaves = 4; // default to medium smooth float perlin_amp_falloff = 0.5f; // 50% reduction/octave // [toxi 031112] // new vars needed due to recent change of cos table in PGraphics int perlin_TWOPI, perlin_PI; float[] perlin_cosTable; float[] perlin; Random perlinRandom; /** */ public float noise(float x) { // is this legit? it's a dumb way to do it (but repair it later) return noise(x, 0f, 0f); } /** */ public float noise(float x, float y) { return noise(x, y, 0f); } /** * ( begin auto-generated from noise.xml ) * * Returns the Perlin noise value at specified coordinates. Perlin noise is * a random sequence generator producing a more natural ordered, harmonic * succession of numbers compared to the standard <b>random()</b> function. * It was invented by Ken Perlin in the 1980s and been used since in * graphical applications to produce procedural textures, natural motion, * shapes, terrains etc.<br /><br /> The main difference to the * <b>random()</b> function is that Perlin noise is defined in an infinite * n-dimensional space where each pair of coordinates corresponds to a * fixed semi-random value (fixed only for the lifespan of the program). * The resulting value will always be between 0.0 and 1.0. Processing can * compute 1D, 2D and 3D noise, depending on the number of coordinates * given. The noise value can be animated by moving through the noise space * as demonstrated in the example above. The 2nd and 3rd dimension can also * be interpreted as time.<br /><br />The actual noise is structured * similar to an audio signal, in respect to the function's use of * frequencies. Similar to the concept of harmonics in physics, perlin * noise is computed over several octaves which are added together for the * final result. <br /><br />Another way to adjust the character of the * resulting sequence is the scale of the input coordinates. As the * function works within an infinite space the value of the coordinates * doesn't matter as such, only the distance between successive coordinates * does (eg. when using <b>noise()</b> within a loop). As a general rule * the smaller the difference between coordinates, the smoother the * resulting noise sequence will be. Steps of 0.005-0.03 work best for most * applications, but this will differ depending on use. * * ( end auto-generated ) * * @webref math:random * @param x x-coordinate in noise space * @param y y-coordinate in noise space * @param z z-coordinate in noise space * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) */ public float noise(float x, float y, float z) { if (perlin == null) { if (perlinRandom == null) { perlinRandom = new Random(); } perlin = new float[PERLIN_SIZE + 1]; for (int i = 0; i < PERLIN_SIZE + 1; i++) { perlin[i] = perlinRandom.nextFloat(); //(float)Math.random(); } // [toxi 031112] // noise broke due to recent change of cos table in PGraphics // this will take care of it perlin_cosTable = PGraphics.cosLUT; perlin_TWOPI = perlin_PI = PGraphics.SINCOS_LENGTH; perlin_PI >>= 1; } if (x<0) x=-x; if (y<0) y=-y; if (z<0) z=-z; int xi=(int)x, yi=(int)y, zi=(int)z; float xf = x - xi; float yf = y - yi; float zf = z - zi; float rxf, ryf; float r=0; float ampl=0.5f; float n1,n2,n3; for (int i=0; i<perlin_octaves; i++) { int of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB); rxf=noise_fsc(xf); ryf=noise_fsc(yf); n1 = perlin[of&PERLIN_SIZE]; n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1); n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2); n1 += ryf*(n2-n1); of += PERLIN_ZWRAP; n2 = perlin[of&PERLIN_SIZE]; n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2); n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]; n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3); n2 += ryf*(n3-n2); n1 += noise_fsc(zf)*(n2-n1); r += n1*ampl; ampl *= perlin_amp_falloff; xi<<=1; xf*=2; yi<<=1; yf*=2; zi<<=1; zf*=2; if (xf>=1.0f) { xi++; xf--; } if (yf>=1.0f) { yi++; yf--; } if (zf>=1.0f) { zi++; zf--; } } return r; } // [toxi 031112] // now adjusts to the size of the cosLUT used via // the new variables, defined above private float noise_fsc(float i) { // using bagel's cosine table instead return 0.5f*(1.0f-perlin_cosTable[(int)(i*perlin_PI)%perlin_TWOPI]); } // [toxi 040903] // make perlin noise quality user controlled to allow // for different levels of detail. lower values will produce // smoother results as higher octaves are surpressed /** * ( begin auto-generated from noiseDetail.xml ) * * Adjusts the character and level of detail produced by the Perlin noise * function. Similar to harmonics in physics, noise is computed over * several octaves. Lower octaves contribute more to the output signal and * as such define the overal intensity of the noise, whereas higher octaves * create finer grained details in the noise sequence. By default, noise is * computed over 4 octaves with each octave contributing exactly half than * its predecessor, starting at 50% strength for the 1st octave. This * falloff amount can be changed by adding an additional function * parameter. Eg. a falloff factor of 0.75 means each octave will now have * 75% impact (25% less) of the previous lower octave. Any value between * 0.0 and 1.0 is valid, however note that values greater than 0.5 might * result in greater than 1.0 values returned by <b>noise()</b>.<br /><br * />By changing these parameters, the signal created by the <b>noise()</b> * function can be adapted to fit very specific needs and characteristics. * * ( end auto-generated ) * @webref math:random * @param lod number of octaves to be used by the noise * @param falloff falloff factor for each octave * @see PApplet#noise(float, float, float) */ public void noiseDetail(int lod) { if (lod>0) perlin_octaves=lod; } /** * @param falloff falloff factor for each octave */ public void noiseDetail(int lod, float falloff) { if (lod>0) perlin_octaves=lod; if (falloff>0) perlin_amp_falloff=falloff; } /** * ( begin auto-generated from noiseSeed.xml ) * * Sets the seed value for <b>noise()</b>. By default, <b>noise()</b> * produces different results each time the program is run. Set the * <b>value</b> parameter to a constant to return the same pseudo-random * numbers each time the software is run. * * ( end auto-generated ) * @webref math:random * @param what int * @see PApplet#noise(float, float, float) * @see PApplet#noiseDetail(int, float) * @see PApplet#random(float,float) * @see PApplet#randomSeed(long) */ public void noiseSeed(long what) { if (perlinRandom == null) perlinRandom = new Random(); perlinRandom.setSeed(what); // force table reset after changing the random number seed [0122] perlin = null; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . protected String[] loadImageFormats; /** * ( begin auto-generated from loadImage.xml ) * * Loads an image into a variable of type <b>PImage</b>. Four types of * images ( <b>.gif</b>, <b>.jpg</b>, <b>.tga</b>, <b>.png</b>) images may * be loaded. To load correctly, images must be located in the data * directory of the current sketch. In most cases, load all images in * <b>setup()</b> to preload them at the start of the program. Loading * images inside <b>draw()</b> will reduce the speed of a program.<br/> * <br/> <b>filename</b> parameter can also be a URL to a file found * online. For security reasons, a Processing sketch found online can only * download files from the same server from which it came. Getting around * this restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed * applet</a>.<br/> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>loadImage()</b>, as * shown in the third example on this page.<br/> * <br/> an image is not loaded successfully, the <b>null</b> value is * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned from <b>loadImage()</b> is null.<br/> * <br/> on the type of error, a <b>PImage</b> object may still be * returned, but the width and height of the image will be set to -1. This * happens if bad image data is returned or cannot be decoded properly. * Sometimes this happens with image URLs that produce a 403 error or that * redirect to a password prompt, because <b>loadImage()</b> will attempt * to interpret the HTML as image data. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @see PImage#PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#imageMode(int) * @see PGraphics#background(float, float, float, float) */ public PImage loadImage(String filename) { return loadImage(filename, null, null); } /** * @param extension the type of image to load, for example "png", "gif", "jpg" */ public PImage loadImage(String filename, String extension) { return loadImage(filename, extension, null); } /** * @nowebref */ public PImage loadImage(String filename, Object params) { return loadImage(filename, null, params); } /** * @nowebref */ public PImage loadImage(String filename, String extension, Object params) { if (extension == null) { String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } } // just in case. them users will try anything! extension = extension.toLowerCase(); if (extension.equals("tga")) { try { PImage image = loadImageTGA(filename); if (params != null) { image.setParams(g, params); } return image; } catch (IOException e) { e.printStackTrace(); return null; } } if (extension.equals("tif") || extension.equals("tiff")) { byte bytes[] = loadBytes(filename); PImage image = (bytes == null) ? null : PImage.loadTIFF(bytes); if (params != null) { image.setParams(g, params); } return image; } // For jpeg, gif, and png, load them using createImage(), // because the javax.imageio code was found to be much slower, see // <A HREF="http://dev.processing.org/bugs/show_bug.cgi?id=392">Bug 392</A>. try { if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif") || extension.equals("png") || extension.equals("unknown")) { byte bytes[] = loadBytes(filename); if (bytes == null) { return null; } else { Image awtImage = Toolkit.getDefaultToolkit().createImage(bytes); PImage image = loadImageMT(awtImage); if (image.width == -1) { System.err.println("The file " + filename + " contains bad image data, or may not be an image."); } // if it's a .gif image, test to see if it has transparency if (extension.equals("gif") || extension.equals("png")) { image.checkAlpha(); } if (params != null) { image.setParams(g, params); } return image; } } } catch (Exception e) { // show error, but move on to the stuff below, see if it'll work e.printStackTrace(); } if (loadImageFormats == null) { loadImageFormats = ImageIO.getReaderFormatNames(); } if (loadImageFormats != null) { for (int i = 0; i < loadImageFormats.length; i++) { if (extension.equals(loadImageFormats[i])) { PImage image; image = loadImageIO(filename); if (params != null) { image.setParams(g, params); } return image; } } } // failed, could not load image after all those attempts System.err.println("Could not find a method to load " + filename); return null; } public PImage requestImage(String filename) { return requestImage(filename, null, null); } /** * ( begin auto-generated from requestImage.xml ) * * This function load images on a separate thread so that your sketch does * not freeze while images load during <b>setup()</b>. While the image is * loading, its width and height will be 0. If an error occurs while * loading the image, its width and height will be set to -1. You'll know * when the image has loaded properly because its width and height will be * greater than 0. Asynchronous image loading (particularly when * downloading from a server) can dramatically improve performance.<br /> * <br/> <b>extension</b> parameter is used to determine the image type in * cases where the image filename does not end with a proper extension. * Specify the extension as the second parameter to <b>requestImage()</b>. * * ( end auto-generated ) * * @webref image:loading_displaying * @param filename name of the file to load, can be .gif, .jpg, .tga, or a handful of other image types depending on your platform * @param extension the type of image to load, for example "png", "gif", "jpg" * @see PApplet#loadImage(String, String) * @see PImage#PImage */ public PImage requestImage(String filename, String extension) { return requestImage(filename, extension, null); } /** * @nowebref */ public PImage requestImage(String filename, String extension, Object params) { PImage vessel = createImage(0, 0, ARGB, params); AsyncImageLoader ail = new AsyncImageLoader(filename, extension, vessel); ail.start(); return vessel; } /** * By trial and error, four image loading threads seem to work best when * loading images from online. This is consistent with the number of open * connections that web browsers will maintain. The variable is made public * (however no accessor has been added since it's esoteric) if you really * want to have control over the value used. For instance, when loading local * files, it might be better to only have a single thread (or two) loading * images so that you're disk isn't simply jumping around. */ public int requestImageMax = 4; volatile int requestImageCount; class AsyncImageLoader extends Thread { String filename; String extension; PImage vessel; public AsyncImageLoader(String filename, String extension, PImage vessel) { this.filename = filename; this.extension = extension; this.vessel = vessel; } public void run() { while (requestImageCount == requestImageMax) { try { Thread.sleep(10); } catch (InterruptedException e) { } } requestImageCount++; PImage actual = loadImage(filename, extension); // An error message should have already printed if (actual == null) { vessel.width = -1; vessel.height = -1; } else { vessel.width = actual.width; vessel.height = actual.height; vessel.format = actual.format; vessel.pixels = actual.pixels; } requestImageCount--; } } /** * Load an AWT image synchronously by setting up a MediaTracker for * a single image, and blocking until it has loaded. */ protected PImage loadImageMT(Image awtImage) { MediaTracker tracker = new MediaTracker(this); tracker.addImage(awtImage, 0); try { tracker.waitForAll(); } catch (InterruptedException e) { //e.printStackTrace(); // non-fatal, right? } PImage image = new PImage(awtImage); image.parent = this; return image; } /** * Use Java 1.4 ImageIO methods to load an image. */ protected PImage loadImageIO(String filename) { InputStream stream = createInput(filename); if (stream == null) { System.err.println("The image " + filename + " could not be found."); return null; } try { BufferedImage bi = ImageIO.read(stream); PImage outgoing = new PImage(bi.getWidth(), bi.getHeight()); outgoing.parent = this; bi.getRGB(0, 0, outgoing.width, outgoing.height, outgoing.pixels, 0, outgoing.width); // check the alpha for this image // was gonna call getType() on the image to see if RGB or ARGB, // but it's not actually useful, since gif images will come through // as TYPE_BYTE_INDEXED, which means it'll still have to check for // the transparency. also, would have to iterate through all the other // types and guess whether alpha was in there, so.. just gonna stick // with the old method. outgoing.checkAlpha(); // return the image return outgoing; } catch (Exception e) { e.printStackTrace(); return null; } } /** * Targa image loader for RLE-compressed TGA files. * <p> * Rewritten for 0115 to read/write RLE-encoded targa images. * For 0125, non-RLE encoded images are now supported, along with * images whose y-order is reversed (which is standard for TGA files). */ protected PImage loadImageTGA(String filename) throws IOException { InputStream is = createInput(filename); if (is == null) return null; byte header[] = new byte[18]; int offset = 0; do { int count = is.read(header, offset, header.length - offset); if (count == -1) return null; offset += count; } while (offset < 18); /* header[2] image type code 2 (0x02) - Uncompressed, RGB images. 3 (0x03) - Uncompressed, black and white images. 10 (0x0A) - Runlength encoded RGB images. 11 (0x0B) - Compressed, black and white images. (grayscale?) header[16] is the bit depth (8, 24, 32) header[17] image descriptor (packed bits) 0x20 is 32 = origin upper-left 0x28 is 32 + 8 = origin upper-left + 32 bits 7 6 5 4 3 2 1 0 128 64 32 16 8 4 2 1 */ int format = 0; if (((header[2] == 3) || (header[2] == 11)) && // B&W, plus RLE or not (header[16] == 8) && // 8 bits ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 bit format = ALPHA; } else if (((header[2] == 2) || (header[2] == 10)) && // RGB, RLE or not (header[16] == 24) && // 24 bits ((header[17] == 0x20) || (header[17] == 0))) { // origin format = RGB; } else if (((header[2] == 2) || (header[2] == 10)) && (header[16] == 32) && ((header[17] == 0x8) || (header[17] == 0x28))) { // origin, 32 format = ARGB; } if (format == 0) { System.err.println("Unknown .tga file format for " + filename); //" (" + header[2] + " " + //(header[16] & 0xff) + " " + //hex(header[17], 2) + ")"); return null; } int w = ((header[13] & 0xff) << 8) + (header[12] & 0xff); int h = ((header[15] & 0xff) << 8) + (header[14] & 0xff); PImage outgoing = createImage(w, h, format); // where "reversed" means upper-left corner (normal for most of // the modernized world, but "reversed" for the tga spec) boolean reversed = (header[17] & 0x20) != 0; if ((header[2] == 2) || (header[2] == 3)) { // not RLE encoded if (reversed) { int index = (h-1) * w; switch (format) { case ALPHA: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read(); } index -= w; } break; case RGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } index -= w; } break; case ARGB: for (int y = h-1; y >= 0; y--) { for (int x = 0; x < w; x++) { outgoing.pixels[index + x] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } index -= w; } } } else { // not reversed int count = w * h; switch (format) { case ALPHA: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read(); } break; case RGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | 0xff000000; } break; case ARGB: for (int i = 0; i < count; i++) { outgoing.pixels[i] = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); } break; } } } else { // header[2] is 10 or 11 int index = 0; int px[] = outgoing.pixels; while (index < px.length) { int num = is.read(); boolean isRLE = (num & 0x80) != 0; if (isRLE) { num -= 127; // (num & 0x7F) + 1 int pixel = 0; switch (format) { case ALPHA: pixel = is.read(); break; case RGB: pixel = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); break; case ARGB: pixel = is.read() | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); break; } for (int i = 0; i < num; i++) { px[index++] = pixel; if (index == px.length) break; } } else { // write up to 127 bytes as uncompressed num += 1; switch (format) { case ALPHA: for (int i = 0; i < num; i++) { px[index++] = is.read(); } break; case RGB: for (int i = 0; i < num; i++) { px[index++] = 0xFF000000 | is.read() | (is.read() << 8) | (is.read() << 16); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; case ARGB: for (int i = 0; i < num; i++) { px[index++] = is.read() | //(is.read() << 24) | (is.read() << 8) | (is.read() << 16) | (is.read() << 24); //(is.read() << 16) | (is.read() << 8) | is.read(); } break; } } } if (!reversed) { int[] temp = new int[w]; for (int y = 0; y < h/2; y++) { int z = (h-1) - y; System.arraycopy(px, y*w, temp, 0, w); System.arraycopy(px, z*w, px, y*w, w); System.arraycopy(temp, 0, px, z*w, w); } } } return outgoing; } ////////////////////////////////////////////////////////////// // SHAPE I/O protected String[] loadShapeFormats; /** * ( begin auto-generated from loadShape.xml ) * * Loads vector shapes into a variable of type <b>PShape</b>. Currently, * only SVG files may be loaded. To load correctly, the file must be * located in the data directory of the current sketch. In most cases, * <b>loadShape()</b> should be used inside <b>setup()</b> because loading * shapes inside <b>draw()</b> will reduce the speed of a sketch.<br/> * <br/> <b>filename</b> parameter can also be a URL to a file found * online. For security reasons, a Processing sketch found online can only * download files from the same server from which it came. Getting around * this restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed * applet</a>.<br/> * <br/> a shape is not loaded successfully, the <b>null</b> value is * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned from <b>loadShape()</b> is null. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param filename name of the file to load * @see PShape#PShape * @see PGraphics#shape(PShape, float, float, float, float) * @see PGraphics#shapeMode(int) */ public PShape loadShape(String filename) { return loadShape(filename, null); } /** * @nowebref */ public PShape loadShape(String filename, Object params) { String extension; String lower = filename.toLowerCase(); int dot = filename.lastIndexOf('.'); if (dot == -1) { extension = "unknown"; // no extension found } extension = lower.substring(dot + 1); // check for, and strip any parameters on the url, i.e. // filename.jpg?blah=blah&something=that int question = extension.indexOf('?'); if (question != -1) { extension = extension.substring(0, question); } if (extension.equals("svg")) { return new PShapeSVG(this, filename); } else if (extension.equals("svgz")) { try { InputStream input = new GZIPInputStream(createInput(filename)); XML xml = new XML(createReader(input)); return new PShapeSVG(xml); } catch (IOException e) { e.printStackTrace(); } } else { // Loading the formats supported by the renderer. loadShapeFormats = g.getSupportedShapeFormats(); if (loadShapeFormats != null) { for (int i = 0; i < loadShapeFormats.length; i++) { if (extension.equals(loadShapeFormats[i])) { return g.loadShape(filename, params); } } } } return null; } /** * Creates an empty shape, with the specified size and parameters. * The actual type will depend on the renderer. */ /* public PShape createShape(int size, Object params) { return g.createShape(size, params); } */ /* public PShape createGroup(String name) { PShape shape = new PShape(PShape.GROUP); shape.setName(name); shape.g = g; return shape; } public PShape createPrimitive(String name, int type) { PShape shape = new PShape(); shape.family = PShape.PRIMITIVE; shape.primitive = type; shape.setName(name); shape.g = g; return shape; } public PShape createShapePath(String name) { PShape shape = new PShape(); shape.family = PShape.PATH; shape.setName(name); shape.g = g; shape.vertexInit(); return shape; } public PShape createGeometry(String name, int type) { PShape shape = new PShape(); shape.family = PShape.GEOMETRY; shape.primitive = type; shape.setName(name); shape.g = g; shape.vertexInit(); return shape; } */ ////////////////////////////////////////////////////////////// // NODE I/O (XML, JSON, etc.) public XML loadXML(String filename) { return new XML(this, filename); } // public PData loadData(String filename) { // if (filename.toLowerCase().endsWith(".json")) { // return new PData(this, filename); // } else { // throw new RuntimeException("filename used for loadNode() must end with XML"); // } // } ////////////////////////////////////////////////////////////// // FONT I/O /** * ( begin auto-generated from loadFont.xml ) * * Loads a font into a variable of type <b>PFont</b>. To load correctly, * fonts must be located in the data directory of the current sketch. To * create a font to use with Processing, select "Create Font..." from the * Tools menu. This will create a font in the format Processing requires * and also adds it to the current sketch's data directory.<br /> * <br /> * Like <b>loadImage()</b> and other functions that load data, the * <b>loadFont()</b> function should not be used inside <b>draw()</b>, * because it will slow down the sketch considerably, as the font will be * re-loaded from the disk (or network) on each frame.<br /> * <br /> * For most renderers, Processing displays fonts using the .vlw font * format, which uses images for each letter, rather than defining them * through vector data. When <b>hint(ENABLE_NATIVE_FONTS)</b> is used with * the JAVA2D renderer, the native version of a font will be used if it is * installed on the user's machine.<br /> * <br /> * Using <b>createFont()</b> (instead of loadFont) enables vector data to * be used with the JAVA2D (default) renderer setting. This can be helpful * when many font sizes are needed, or when using any renderer based on * JAVA2D, such as the PDF library. * * ( end auto-generated ) * @webref typography:loading_displaying * @param filename name of the font to load * @see PFont#PFont * @see PGraphics#textFont(PFont, float) * @see PGraphics#text(String, float, float, float, float, float) * @see PApplet#createFont(String, float, boolean, char[]) */ public PFont loadFont(String filename) { try { InputStream input = createInput(filename); return new PFont(input); } catch (Exception e) { die("Could not load font " + filename + ". " + "Make sure that the font has been copied " + "to the data folder of your sketch.", e); } return null; } /** * Used by PGraphics to remove the requirement for loading a font! */ protected PFont createDefaultFont(float size) { // Font f = new Font("SansSerif", Font.PLAIN, 12); // println("n: " + f.getName()); // println("fn: " + f.getFontName()); // println("ps: " + f.getPSName()); return createFont("Lucida Sans", size, true, null); } public PFont createFont(String name, float size) { return createFont(name, size, true, null); } public PFont createFont(String name, float size, boolean smooth) { return createFont(name, size, smooth, null); } /** * ( begin auto-generated from createFont.xml ) * * Dynamically converts a font to the format used by Processing from either * a font name that's installed on the computer, or from a .ttf or .otf * file inside the sketches "data" folder. This function is an advanced * feature for precise control. On most occasions you should create fonts * through selecting "Create Font..." from the Tools menu. * <br /><br /> * Use the <b>PFont.list()</b> method to first determine the names for the * fonts recognized by the computer and are compatible with this function. * Because of limitations in Java, not all fonts can be used and some might * work with one operating system and not others. When sharing a sketch * with other people or posting it on the web, you may need to include a * .ttf or .otf version of your font in the data directory of the sketch * because other people might not have the font installed on their * computer. Only fonts that can legally be distributed should be included * with a sketch. * <br /><br /> * The <b>size</b> parameter states the font size you want to generate. The * <b>smooth</b> parameter specifies if the font should be antialiased or * not, and the <b>charset</b> parameter is an array of chars that * specifies the characters to generate. * <br /><br /> * This function creates a bitmapped version of a font in the same manner * as the Create Font tool. It loads a font by name, and converts it to a * series of images based on the size of the font. When possible, the * <b>text()</b> function will use a native font rather than the bitmapped * version created behind the scenes with <b>createFont()</b>. For * instance, when using P2D, the actual native version of the font will be * employed by the sketch, improving drawing quality and performance. With * the P3D renderer, the bitmapped version will be used. While this can * drastically improve speed and appearance, results are poor when * exporting if the sketch does not include the .otf or .ttf file, and the * requested font is not available on the machine running the sketch. * * ( end auto-generated ) * @webref typography:loading_displaying * @param name name of the font to load * @param size point size of the font * @param smooth true for an antialiased font, false for aliased * @param charset array containing characters to be generated * @see PFont#PFont * @see PGraphics#textFont(PFont, float) * @see PGraphics#text(String, float, float, float, float, float) * @see PApplet#loadFont(String) */ public PFont createFont(String name, float size, boolean smooth, char charset[]) { String lowerName = name.toLowerCase(); Font baseFont = null; try { InputStream stream = null; if (lowerName.endsWith(".otf") || lowerName.endsWith(".ttf")) { stream = createInput(name); if (stream == null) { System.err.println("The font \"" + name + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } baseFont = Font.createFont(Font.TRUETYPE_FONT, createInput(name)); } else { baseFont = PFont.findFont(name); } return new PFont(baseFont.deriveFont(size), smooth, charset, stream != null); } catch (Exception e) { System.err.println("Problem createFont(" + name + ")"); e.printStackTrace(); return null; } } ////////////////////////////////////////////////////////////// // FILE/FOLDER SELECTION public File selectedFile; protected Frame parentFrame; protected void checkParentFrame() { if (parentFrame == null) { Component comp = getParent(); while (comp != null) { if (comp instanceof Frame) { parentFrame = (Frame) comp; break; } comp = comp.getParent(); } // Who you callin' a hack? if (parentFrame == null) { parentFrame = new Frame(); } } } /** * Open a platform-specific file chooser dialog to select a file for input. * @return full path to the selected file, or null if no selection. */ public String selectInput() { return selectInput("Select a file..."); } /** * ( begin auto-generated from selectInput.xml ) * * Opens a platform-specific file chooser dialog to select a file for * input. This function returns the full path to the selected file as a * <b>String</b>, or <b>null</b> if no selection. * * ( end auto-generated ) * @webref input:files * @param prompt message you want the user to see in the file chooser * @see PApplet#selectOutput(String) * @see PApplet#selectFolder(String) */ public String selectInput(String prompt) { return selectFileImpl(prompt, FileDialog.LOAD); } /** * Open a platform-specific file save dialog to select a file for output. * @return full path to the file entered, or null if canceled. */ public String selectOutput() { return selectOutput("Save as..."); } /** * ( begin auto-generated from selectOutput.xml ) * * Open a platform-specific file save dialog to create of select a file for * output. This function returns the full path to the selected file as a * <b>String</b>, or <b>null</b> if no selection. If you select an existing * file, that file will be replaced. Alternatively, you can navigate to a * folder and create a new file to write to. * * ( end auto-generated ) * @webref output:files * @param prompt message you want the user to see in the file chooser * @see PApplet#selectInput(String) * @see PApplet#selectFolder(String) */ public String selectOutput(String prompt) { return selectFileImpl(prompt, FileDialog.SAVE); } protected String selectFileImpl(final String prompt, final int mode) { checkParentFrame(); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { FileDialog fileDialog = new FileDialog(parentFrame, prompt, mode); fileDialog.setVisible(true); String directory = fileDialog.getDirectory(); String filename = fileDialog.getFile(); selectedFile = (filename == null) ? null : new File(directory, filename); } }); return (selectedFile == null) ? null : selectedFile.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); return null; } } public String selectFolder() { return selectFolder("Select a folder..."); } /** * ( begin auto-generated from selectFolder.xml ) * * Opens a platform-specific file chooser dialog to select a folder for * input. This function returns the full path to the selected folder as a * <b>String</b>, or <b>null</b> if no selection. * * ( end auto-generated ) * @webref input:files * @param prompt message you want the user to see in the file chooser * @see PApplet#selectOutput(String) * @see PApplet#selectInput(String) */ public String selectFolder(final String prompt) { checkParentFrame(); try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { if (platform == MACOSX) { FileDialog fileDialog = new FileDialog(parentFrame, prompt, FileDialog.LOAD); System.setProperty("apple.awt.fileDialogForDirectories", "true"); fileDialog.setVisible(true); System.setProperty("apple.awt.fileDialogForDirectories", "false"); String filename = fileDialog.getFile(); selectedFile = (filename == null) ? null : new File(fileDialog.getDirectory(), fileDialog.getFile()); } else { JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(prompt); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returned = fileChooser.showOpenDialog(parentFrame); System.out.println(returned); if (returned == JFileChooser.CANCEL_OPTION) { selectedFile = null; } else { selectedFile = fileChooser.getSelectedFile(); } } } }); return (selectedFile == null) ? null : selectedFile.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); return null; } } ////////////////////////////////////////////////////////////// // READERS AND WRITERS /** * ( begin auto-generated from createReader.xml ) * * Creates a <b>BufferedReader</b> object that can be used to read files * line-by-line as individual <b>String</b> objects. This is the complement * to the <b>createWriter()</b> function. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref input:files * @param filename name of the file to be opened * @see BufferedReader * @see PApplet#createWriter(String) * @see PrintWriter */ public BufferedReader createReader(String filename) { try { InputStream is = createInput(filename); if (is == null) { System.err.println(filename + " does not exist or could not be read"); return null; } return createReader(is); } catch (Exception e) { if (filename == null) { System.err.println("Filename passed to reader() was null"); } else { System.err.println("Couldn't create a reader for " + filename); } } return null; } /** * @nowebref */ static public BufferedReader createReader(File file) { try { InputStream is = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { is = new GZIPInputStream(is); } return createReader(is); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createReader() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a reader for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to read lines from a stream. If I have to type the * following lines any more I'm gonna send Sun my medical bills. */ static public BufferedReader createReader(InputStream input) { InputStreamReader isr = null; try { isr = new InputStreamReader(input, "UTF-8"); } catch (UnsupportedEncodingException e) { } // not gonna happen return new BufferedReader(isr); } /** * ( begin auto-generated from createWriter.xml ) * * Creates a new file in the sketch folder, and a <b>PrintWriter</b> object * to write to it. For the file to be made correctly, it should be flushed * and must be closed with its <b>flush()</b> and <b>close()</b> methods * (see above example). * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to be created * @see PrintWriter * @see PApplet#createReader * @see BufferedReader */ public PrintWriter createWriter(String filename) { return createWriter(saveFile(filename)); } /** * @nowebref * I want to print lines to a file. I have RSI from typing these * eight lines of code so many times. */ static public PrintWriter createWriter(File file) { try { createPath(file); // make sure in-between folders exist OutputStream output = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } return createWriter(output); } catch (Exception e) { if (file == null) { throw new RuntimeException("File passed to createWriter() was null"); } else { e.printStackTrace(); throw new RuntimeException("Couldn't create a writer for " + file.getAbsolutePath()); } } //return null; } /** * @nowebref * I want to print lines to a file. Why am I always explaining myself? * It's the JavaSoft API engineers who need to explain themselves. */ static public PrintWriter createWriter(OutputStream output) { try { BufferedOutputStream bos = new BufferedOutputStream(output, 8192); OutputStreamWriter osw = new OutputStreamWriter(bos, "UTF-8"); return new PrintWriter(osw); } catch (UnsupportedEncodingException e) { } // not gonna happen return null; } ////////////////////////////////////////////////////////////// // FILE INPUT /** * @deprecated As of release 0136, use createInput() instead. */ public InputStream openStream(String filename) { return createInput(filename); } /** * ( begin auto-generated from createInput.xml ) * * This is a function for advanced programmers to open a Java InputStream. * It's useful if you want to use the facilities provided by PApplet to * easily open files from the data folder or from a URL, but want an * InputStream object so that you can use other parts of Java to take more * control of how the stream is read.<br /> * <br /> * The filename passed in can be:<br /> * - A URL, for instance <b>openStream("http://processing.org/")</b><br /> * - A file in the sketch's <b>data</b> folder<br /> * - The full path to a file to be opened locally (when running as an * application)<br /> * <br /> * If the requested item doesn't exist, null is returned. If not online, * this will also check to see if the user is asking for a file whose name * isn't properly capitalized. If capitalization is different, an error * will be printed to the console. This helps prevent issues that appear * when a sketch is exported to the web, where case sensitivity matters, as * opposed to running from inside the Processing Development Environment on * Windows or Mac OS, where case sensitivity is preserved but ignored.<br /> * <br /> * If the file ends with <b>.gz</b>, the stream will automatically be gzip * decompressed. If you don't want the automatic decompression, use the * related function <b>createInputRaw()</b>. * <br /> * In earlier releases, this function was called <b>openStream()</b>.<br /> * <br /> * * ( end auto-generated ) * * <h3>Advanced</h3> * Simplified method to open a Java InputStream. * <p> * This method is useful if you want to use the facilities provided * by PApplet to easily open things from the data folder or from a URL, * but want an InputStream object so that you can use other Java * methods to take more control of how the stream is read. * <p> * If the requested item doesn't exist, null is returned. * (Prior to 0096, die() would be called, killing the applet) * <p> * For 0096+, the "data" folder is exported intact with subfolders, * and openStream() properly handles subdirectories from the data folder * <p> * If not online, this will also check to see if the user is asking * for a file whose name isn't properly capitalized. This helps prevent * issues when a sketch is exported to the web, where case sensitivity * matters, as opposed to Windows and the Mac OS default where * case sensitivity is preserved but ignored. * <p> * It is strongly recommended that libraries use this method to open * data files, so that the loading sequence is handled in the same way * as functions like loadBytes(), loadImage(), etc. * <p> * The filename passed in can be: * <UL> * <LI>A URL, for instance openStream("http://processing.org/"); * <LI>A file in the sketch's data folder * <LI>Another file to be opened locally (when running as an application) * </UL> * * @webref input:files * @param filename the name of the file to use as input * @see PApplet#createOutput(String) * @see PApplet#selectOutput(String) * @see PApplet#selectInput(String) * */ public InputStream createInput(String filename) { InputStream input = createInputRaw(filename); if ((input != null) && filename.toLowerCase().endsWith(".gz")) { try { return new GZIPInputStream(input); } catch (IOException e) { e.printStackTrace(); return null; } } return input; } /** * Call openStream() without automatic gzip decompression. */ public InputStream createInputRaw(String filename) { InputStream stream = null; if (filename == null) return null; if (filename.length() == 0) { // an error will be called by the parent function //System.err.println("The filename passed to openStream() was empty."); return null; } // safe to check for this as a url first. this will prevent online // access logs from being spammed with GET /sketchfolder/http://blahblah if (filename.indexOf(":") != -1) { // at least smells like URL try { URL url = new URL(filename); stream = url.openStream(); return stream; } catch (MalformedURLException mfue) { // not a url, that's fine } catch (FileNotFoundException fnfe) { // Java 1.5 likes to throw this when URL not available. (fix for 0119) // http://dev.processing.org/bugs/show_bug.cgi?id=403 } catch (IOException e) { // changed for 0117, shouldn't be throwing exception e.printStackTrace(); //System.err.println("Error downloading from URL " + filename); return null; //throw new RuntimeException("Error downloading from URL " + filename); } } // Moved this earlier than the getResourceAsStream() checks, because // calling getResourceAsStream() on a directory lists its contents. // http://dev.processing.org/bugs/show_bug.cgi?id=716 try { // First see if it's in a data folder. This may fail by throwing // a SecurityException. If so, this whole block will be skipped. File file = new File(dataPath(filename)); if (!file.exists()) { // next see if it's just in the sketch folder file = new File(sketchPath, filename); } if (file.isDirectory()) { return null; } if (file.exists()) { try { // handle case sensitivity check String filePath = file.getCanonicalPath(); String filenameActual = new File(filePath).getName(); // make sure there isn't a subfolder prepended to the name String filenameShort = new File(filename).getName(); // if the actual filename is the same, but capitalized // differently, warn the user. //if (filenameActual.equalsIgnoreCase(filenameShort) && //!filenameActual.equals(filenameShort)) { if (!filenameActual.equals(filenameShort)) { throw new RuntimeException("This file is named " + filenameActual + " not " + filename + ". Rename the file " + "or change your code."); } } catch (IOException e) { } } // if this file is ok, may as well just load it stream = new FileInputStream(file); if (stream != null) return stream; // have to break these out because a general Exception might // catch the RuntimeException being thrown above } catch (IOException ioe) { } catch (SecurityException se) { } // Using getClassLoader() prevents java from converting dots // to slashes or requiring a slash at the beginning. // (a slash as a prefix means that it'll load from the root of // the jar, rather than trying to dig into the package location) ClassLoader cl = getClass().getClassLoader(); // by default, data files are exported to the root path of the jar. // (not the data folder) so check there first. stream = cl.getResourceAsStream("data/" + filename); if (stream != null) { String cn = stream.getClass().getName(); // this is an irritation of sun's java plug-in, which will return // a non-null stream for an object that doesn't exist. like all good // things, this is probably introduced in java 1.5. awesome! // http://dev.processing.org/bugs/show_bug.cgi?id=359 if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // When used with an online script, also need to check without the // data folder, in case it's not in a subfolder called 'data'. // http://dev.processing.org/bugs/show_bug.cgi?id=389 stream = cl.getResourceAsStream(filename); if (stream != null) { String cn = stream.getClass().getName(); if (!cn.equals("sun.plugin.cache.EmptyInputStream")) { return stream; } } // Finally, something special for the Internet Explorer users. Turns out // that we can't get files that are part of the same folder using the // methods above when using IE, so we have to resort to the old skool // getDocumentBase() from teh applet dayz. 1996, my brotha. try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); // if (conn instanceof HttpURLConnection) { // HttpURLConnection httpConnection = (HttpURLConnection) conn; // // test for 401 result (HTTP only) // int responseCode = httpConnection.getResponseCode(); // } } } catch (Exception e) { } // IO or NPE or... // Now try it with a 'data' subfolder. getting kinda desperate for data... try { URL base = getDocumentBase(); if (base != null) { URL url = new URL(base, "data/" + filename); URLConnection conn = url.openConnection(); return conn.getInputStream(); } } catch (Exception e) { } try { // attempt to load from a local file, used when running as // an application, or as a signed applet try { // first try to catch any security exceptions try { stream = new FileInputStream(dataPath(filename)); if (stream != null) return stream; } catch (IOException e2) { } try { stream = new FileInputStream(sketchPath(filename)); if (stream != null) return stream; } catch (Exception e) { } // ignored try { stream = new FileInputStream(filename); if (stream != null) return stream; } catch (IOException e1) { } } catch (SecurityException se) { } // online, whups } catch (Exception e) { //die(e.getMessage(), e); e.printStackTrace(); } return null; } /** * @nowebref */ static public InputStream createInput(File file) { if (file == null) { throw new IllegalArgumentException("File passed to createInput() was null"); } try { InputStream input = new FileInputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPInputStream(input); } return input; } catch (IOException e) { System.err.println("Could not createInput() for " + file); e.printStackTrace(); return null; } } /** * ( begin auto-generated from loadBytes.xml ) * * Reads the contents of a file or url and places it in a byte array. If a * file is specified, it must be located in the sketch's "data" * directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * * ( end auto-generated ) * @webref input:files * @param filename name of a file in the data folder or a URL. * @see PApplet#loadStrings(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) * */ public byte[] loadBytes(String filename) { InputStream is = createInput(filename); if (is != null) return loadBytes(is); System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public byte[] loadBytes(InputStream input) { try { BufferedInputStream bis = new BufferedInputStream(input); ByteArrayOutputStream out = new ByteArrayOutputStream(); int c = bis.read(); while (c != -1) { out.write(c); c = bis.read(); } return out.toByteArray(); } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Couldn't load bytes from stream"); } return null; } /** * @nowebref */ static public byte[] loadBytes(File file) { InputStream is = createInput(file); return loadBytes(is); } /** * @nowebref */ static public String[] loadStrings(File file) { InputStream is = createInput(file); if (is != null) return loadStrings(is); return null; } /** * ( begin auto-generated from loadStrings.xml ) * * Reads the contents of a file or url and creates a String array of its * individual lines. If a file is specified, it must be located in the * sketch's "data" directory/folder.<br /> * <br /> * The filename parameter can also be a URL to a file found online. For * security reasons, a Processing sketch found online can only download * files from the same server from which it came. Getting around this * restriction requires a <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</a>. * <br /> * If the file is not available or an error occurs, <b>null</b> will be * returned and an error message will be printed to the console. The error * message does not halt the program, however the null value may cause a * NullPointerException if your code does not check whether the value * returned is null. * <br/> <br/> * Starting with Processing release 0134, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * * <h3>Advanced</h3> * Load data from a file and shove it into a String array. * <p> * Exceptions are handled internally, when an error, occurs, an * exception is printed to the console and 'null' is returned, * but the program continues running. This is a tradeoff between * 1) showing the user that there was a problem but 2) not requiring * that all i/o code is contained in try/catch blocks, for the sake * of new users (or people who are just trying to get things done * in a "scripting" fashion. If you want to handle exceptions, * use Java methods for I/O. * * @webref input:files * @param filename name of the file or url to load * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) * @see PApplet#saveBytes(String, byte[]) */ public String[] loadStrings(String filename) { InputStream is = createInput(filename); if (is != null) return loadStrings(is); System.err.println("The file \"" + filename + "\" " + "is missing or inaccessible, make sure " + "the URL is valid or that the file has been " + "added to your sketch and is readable."); return null; } /** * @nowebref */ static public String[] loadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); return loadStrings(reader); } catch (IOException e) { e.printStackTrace(); } return null; } static public String[] loadStrings(BufferedReader reader) { try { String lines[] = new String[100]; int lineCount = 0; String line = null; while ((line = reader.readLine()) != null) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } lines[lineCount++] = line; } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropriate amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { e.printStackTrace(); //throw new RuntimeException("Error inside loadStrings()"); } return null; } ////////////////////////////////////////////////////////////// // FILE OUTPUT /** * ( begin auto-generated from createOutput.xml ) * * Similar to <b>createInput()</b>, this creates a Java <b>OutputStream</b> * for a given filename or path. The file will be created in the sketch * folder, or in the same folder as an exported application. * <br /><br /> * If the path does not exist, intermediate folders will be created. If an * exception occurs, it will be printed to the console, and <b>null</b> * will be returned. * <br /><br /> * This function is a convenience over the Java approach that requires you * to 1) create a FileOutputStream object, 2) determine the exact file * location, and 3) handle exceptions. Exceptions are handled internally by * the function, which is more appropriate for "sketch" projects. * <br /><br /> * If the output filename ends with <b>.gz</b>, the output will be * automatically GZIP compressed as it is written. * * ( end auto-generated ) * @webref output:files * @param filename name of the file to open * @see PApplet#createInput(String) * @see PApplet#selectOutput() */ public OutputStream createOutput(String filename) { return createOutput(saveFile(filename)); } /** * @nowebref */ static public OutputStream createOutput(File file) { try { createPath(file); // make sure the path exists FileOutputStream fos = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { return new GZIPOutputStream(fos); } return fos; } catch (IOException e) { e.printStackTrace(); } return null; } /** * ( begin auto-generated from saveStream.xml ) * * Save the contents of a stream to a file in the sketch folder. This is * basically <b>saveBytes(blah, loadBytes())</b>, but done more efficiently * (and with less confusing syntax).<br /> * <br /> * When using the <b>targetFile</b> parameter, it writes to a <b>File</b> * object for greater control over the file location. (Note that unlike * some other functions, this will not automatically compress or uncompress * gzip files.) * * ( end auto-generated ) * * @webref output:files * @param targetFilename name of the file to write to * @param sourceLocation location to save the file * @see PApplet#createOutput(String) */ public boolean saveStream(String targetFilename, String sourceLocation) { return saveStream(saveFile(targetFilename), sourceLocation); } /** * Identical to the other saveStream(), but writes to a File * object, for greater control over the file location. * <p/> * Note that unlike other api methods, this will not automatically * compress or uncompress gzip files. * * @param targetFile the file to write to */ public boolean saveStream(File targetFile, String sourceLocation) { return saveStream(targetFile, createInputRaw(sourceLocation)); } /** * @nowebref */ public boolean saveStream(String targetFilename, InputStream sourceStream) { return saveStream(saveFile(targetFilename), sourceStream); } /** * @nowebref */ static public boolean saveStream(File targetFile, InputStream sourceStream) { File tempFile = null; try { File parentDir = targetFile.getParentFile(); // make sure that this path actually exists before writing createPath(targetFile); tempFile = File.createTempFile(targetFile.getName(), null, parentDir); FileOutputStream targetStream = new FileOutputStream(tempFile); saveStream(targetStream, sourceStream); targetStream.close(); targetStream = null; if (targetFile.exists()) { if (!targetFile.delete()) { System.err.println("Could not replace " + targetFile.getAbsolutePath() + "."); } } if (!tempFile.renameTo(targetFile)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); return false; } return true; } catch (IOException e) { if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); return false; } } /** * @nowebref */ static public void saveStream(OutputStream targetStream, InputStream sourceStream) throws IOException { BufferedInputStream bis = new BufferedInputStream(sourceStream, 16384); BufferedOutputStream bos = new BufferedOutputStream(targetStream); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); } /** * ( begin auto-generated from saveBytes.xml ) * * Opposite of <b>loadBytes()</b>, will write an entire array of bytes to a * file. The data is saved in binary format. This file is saved to the * sketch's folder, which is opened by selecting "Show sketch folder" from * the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki. * * ( end auto-generated ) * * @webref output:files * @param filename name of the file to write to * @param buffer array of bytes to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveStrings(String, String[]) */ public void saveBytes(String filename, byte buffer[]) { saveBytes(saveFile(filename), buffer); } /** * @nowebref * Saves bytes to a specific File location specified by the user. */ static public void saveBytes(File file, byte buffer[]) { File tempFile = null; try { File parentDir = file.getParentFile(); tempFile = File.createTempFile(file.getName(), null, parentDir); /* String filename = file.getAbsolutePath(); createPath(filename); OutputStream output = new FileOutputStream(file); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } */ OutputStream output = createOutput(tempFile); saveBytes(output, buffer); output.close(); output = null; if (file.exists()) { if (!file.delete()) { System.err.println("Could not replace " + file.getAbsolutePath()); } } if (!tempFile.renameTo(file)) { System.err.println("Could not rename temporary file " + tempFile.getAbsolutePath()); } } catch (IOException e) { System.err.println("error saving bytes to " + file); if (tempFile != null) { tempFile.delete(); } e.printStackTrace(); } } /** * @nowebref * Spews a buffer of bytes to an OutputStream. */ static public void saveBytes(OutputStream output, byte buffer[]) { try { output.write(buffer); output.flush(); } catch (IOException e) { e.printStackTrace(); } } // /** * ( begin auto-generated from saveStrings.xml ) * * Writes an array of strings to a file, one line per string. This file is * saved to the sketch's folder, which is opened by selecting "Show sketch * folder" from the "Sketch" menu.<br /> * <br /> * It is not possible to use saveXxxxx() functions inside a web browser * unless the sketch is <a * href="http://wiki.processing.org/w/Sign_an_Applet">signed applet</A>. To * save a file back to a server, see the <a * href="http://wiki.processing.org/w/Saving_files_to_a_web-server">save to * web</A> code snippet on the Processing Wiki.<br/> * <br/ > * Starting with Processing 1.0, all files loaded and saved by the * Processing API use UTF-8 encoding. In previous releases, the default * encoding for your platform was used, which causes problems when files * are moved to other platforms. * * ( end auto-generated ) * @webref output:files * @param filename filename for output * @param strings string array to be written * @see PApplet#loadStrings(String) * @see PApplet#loadBytes(String) * @see PApplet#saveBytes(String, byte[]) */ public void saveStrings(String filename, String strings[]) { saveStrings(saveFile(filename), strings); } /** * @nowebref */ static public void saveStrings(File file, String strings[]) { saveStrings(createOutput(file), strings); /* try { String location = file.getAbsolutePath(); createPath(location); OutputStream output = new FileOutputStream(location); if (file.getName().toLowerCase().endsWith(".gz")) { output = new GZIPOutputStream(output); } saveStrings(output, strings); output.close(); } catch (IOException e) { e.printStackTrace(); } */ } /** * @nowebref */ static public void saveStrings(OutputStream output, String strings[]) { PrintWriter writer = createWriter(output); for (int i = 0; i < strings.length; i++) { writer.println(strings[i]); } writer.flush(); writer.close(); } ////////////////////////////////////////////////////////////// /** * Prepend the sketch folder path to the filename (or path) that is * passed in. External libraries should use this function to save to * the sketch folder. * <p/> * Note that when running as an applet inside a web browser, * the sketchPath will be set to null, because security restrictions * prevent applets from accessing that information. * <p/> * This will also cause an error if the sketch is not inited properly, * meaning that init() was never called on the PApplet when hosted * my some other main() or by other code. For proper use of init(), * see the examples in the main description text for PApplet. */ public String sketchPath(String where) { if (sketchPath == null) { return where; // throw new RuntimeException("The applet was not inited properly, " + // "or security restrictions prevented " + // "it from determining its path."); } // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. // for 0120, added a try/catch anyways. try { if (new File(where).isAbsolute()) return where; } catch (Exception e) { } return sketchPath + File.separator + where; } public File sketchFile(String where) { return new File(sketchPath(where)); } /** * Returns a path inside the applet folder to save to. Like sketchPath(), * but creates any in-between folders so that things save properly. * <p/> * All saveXxxx() functions use the path to the sketch folder, rather than * its data folder. Once exported, the data folder will be found inside the * jar file of the exported application or applet. In this case, it's not * possible to save data into the jar file, because it will often be running * from a server, or marked in-use if running from a local file system. * With this in mind, saving to the data path doesn't make sense anyway. * If you know you're running locally, and want to save to the data folder, * use <TT>saveXxxx("data/blah.dat")</TT>. */ public String savePath(String where) { if (where == null) return null; String filename = sketchPath(where); createPath(filename); return filename; } /** * Identical to savePath(), but returns a File object. */ public File saveFile(String where) { return new File(savePath(where)); } /** * Return a full path to an item in the data folder. * <p> * This is only available with applications, not applets or Android. * On Windows and Linux, this is simply the data folder, which is located * in the same directory as the EXE file and lib folders. On Mac OS X, this * is a path to the data folder buried inside Contents/Resources/Java. * For the latter point, that also means that the data folder should not be * considered writable. Use sketchPath() for now, or inputPath() and * outputPath() once they're available in the 2.0 release. * <p> * dataPath() is not supported with applets because applets have their data * folder wrapped into the JAR file. To read data from the data folder that * works with an applet, you should use other methods such as createInput(), * createReader(), or loadStrings(). */ public String dataPath(String where) { return dataFile(where).getAbsolutePath(); } /** * Return a full path to an item in the data folder as a File object. * See the dataPath() method for more information. */ public File dataFile(String where) { // isAbsolute() could throw an access exception, but so will writing // to the local disk using the sketch path, so this is safe here. File why = new File(where); if (why.isAbsolute()) return why; String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); if (jarPath.contains("Contents/Resources/Java/")) { File containingFolder = new File(jarPath).getParentFile(); File dataFolder = new File(containingFolder, "data"); return new File(dataFolder, where); } // Windows, Linux, or when not using a Mac OS X .app file return new File(sketchPath + File.separator + "data" + File.separator + where); } /** * On Windows and Linux, this is simply the data folder. On Mac OS X, this is * the path to the data folder buried inside Contents/Resources/Java */ // public File inputFile(String where) { // } // public String inputPath(String where) { // } /** * Takes a path and creates any in-between folders if they don't * already exist. Useful when trying to save to a subfolder that * may not actually exist. */ static public void createPath(String path) { createPath(new File(path)); } static public void createPath(File file) { try { String parent = file.getParent(); if (parent != null) { File unit = new File(parent); if (!unit.exists()) unit.mkdirs(); } } catch (SecurityException se) { System.err.println("You don't have permissions to create " + file.getAbsolutePath()); } } ////////////////////////////////////////////////////////////// // URL ENCODING static public String urlEncode(String what) { try { return URLEncoder.encode(what, "UTF-8"); } catch (UnsupportedEncodingException e) { // oh c'mon return null; } } static public String urlDecode(String what) { try { return URLDecoder.decode(what, "UTF-8"); } catch (UnsupportedEncodingException e) { // safe per the JDK source return null; } } ////////////////////////////////////////////////////////////// // SORT /** * ( begin auto-generated from sort.xml ) * * Sorts an array of numbers from smallest to largest and puts an array of * words in alphabetical order. The original array is not modified, a * re-ordered array is returned. The <b>count</b> parameter states the * number of elements to sort. For example if there are 12 elements in an * array and if count is the value 5, only the first five elements on the * array will be sorted. <!--As of release 0126, the alphabetical ordering * is case insensitive.--> * * ( end auto-generated ) * @webref data:array_functions * @param what array to sort * @see PApplet#reverse(boolean[]) */ static public byte[] sort(byte what[]) { return sort(what, what.length); } /** * @param count number of elements to sort, starting from 0 */ static public byte[] sort(byte[] what, int count) { byte[] outgoing = new byte[what.length]; System.arraycopy(what, 0, outgoing, 0, what.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public char[] sort(char what[]) { return sort(what, what.length); } static public char[] sort(char[] what, int count) { char[] outgoing = new char[what.length]; System.arraycopy(what, 0, outgoing, 0, what.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public int[] sort(int what[]) { return sort(what, what.length); } static public int[] sort(int[] what, int count) { int[] outgoing = new int[what.length]; System.arraycopy(what, 0, outgoing, 0, what.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public float[] sort(float what[]) { return sort(what, what.length); } static public float[] sort(float[] what, int count) { float[] outgoing = new float[what.length]; System.arraycopy(what, 0, outgoing, 0, what.length); Arrays.sort(outgoing, 0, count); return outgoing; } static public String[] sort(String what[]) { return sort(what, what.length); } static public String[] sort(String[] what, int count) { String[] outgoing = new String[what.length]; System.arraycopy(what, 0, outgoing, 0, what.length); Arrays.sort(outgoing, 0, count); return outgoing; } ////////////////////////////////////////////////////////////// // ARRAY UTILITIES /** * ( begin auto-generated from arrayCopy.xml ) * * Copies an array (or part of an array) to another array. The <b>src</b> * array is copied to the <b>dst</b> array, beginning at the position * specified by <b>srcPos</b> and into the position specified by * <b>dstPos</b>. The number of elements to copy is determined by * <b>length</b>. The simplified version with two arguments copies an * entire array to another of the same size. It is equivalent to * "arrayCopy(src, 0, dst, 0, src.length)". This function is far more * efficient for copying array data than iterating through a <b>for</b> and * copying each element. * * ( end auto-generated ) * @webref data:array_functions * @param src the source array * @param srcPosition starting position in the source array * @param dst the destination array of the same data type as the source array * @param dstPosition starting position in the destination array * @param length number of array elements to be copied * @see PApplet#concat(boolean[], boolean[]) */ static public void arrayCopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * Convenience method for arraycopy(). * Identical to <CODE>arraycopy(src, 0, dst, 0, length);</CODE> */ static public void arrayCopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * Shortcut to copy the entire contents of * the source into the destination array. * Identical to <CODE>arraycopy(src, 0, dst, 0, src.length);</CODE> */ static public void arrayCopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } // /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, int srcPosition, Object dst, int dstPosition, int length) { System.arraycopy(src, srcPosition, dst, dstPosition, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst, int length) { System.arraycopy(src, 0, dst, 0, length); } /** * @deprecated Use arrayCopy() instead. */ static public void arraycopy(Object src, Object dst) { System.arraycopy(src, 0, dst, 0, Array.getLength(src)); } /** * ( begin auto-generated from expand.xml ) * * Increases the size of an array. By default, this function doubles the * size of the array, but the optional <b>newSize</b> parameter provides * precise control over the increase in size. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) expand(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list the array to expand * @see PApplet#shorten(boolean[]) */ static public boolean[] expand(boolean list[]) { return expand(list, list.length << 1); } /** * @param newSize new size for the array */ static public boolean[] expand(boolean list[], int newSize) { boolean temp[] = new boolean[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public byte[] expand(byte list[]) { return expand(list, list.length << 1); } static public byte[] expand(byte list[], int newSize) { byte temp[] = new byte[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public char[] expand(char list[]) { return expand(list, list.length << 1); } static public char[] expand(char list[], int newSize) { char temp[] = new char[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public int[] expand(int list[]) { return expand(list, list.length << 1); } static public int[] expand(int list[], int newSize) { int temp[] = new int[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public long[] expand(long list[]) { return expand(list, list.length << 1); } static public long[] expand(long list[], int newSize) { long temp[] = new long[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public float[] expand(float list[]) { return expand(list, list.length << 1); } static public float[] expand(float list[], int newSize) { float temp[] = new float[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public double[] expand(double list[]) { return expand(list, list.length << 1); } static public double[] expand(double list[], int newSize) { double temp[] = new double[newSize]; System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } static public String[] expand(String list[]) { return expand(list, list.length << 1); } static public String[] expand(String list[], int newSize) { String temp[] = new String[newSize]; // in case the new size is smaller than list.length System.arraycopy(list, 0, temp, 0, Math.min(newSize, list.length)); return temp; } /** * @nowebref */ static public Object expand(Object array) { return expand(array, Array.getLength(array) << 1); } static public Object expand(Object list, int newSize) { Class<?> type = list.getClass().getComponentType(); Object temp = Array.newInstance(type, newSize); System.arraycopy(list, 0, temp, 0, Math.min(Array.getLength(list), newSize)); return temp; } // contract() has been removed in revision 0124, use subset() instead. // (expand() is also functionally equivalent) /** * ( begin auto-generated from append.xml ) * * Expands an array by one element and adds data to the new position. The * datatype of the <b>element</b> parameter must be the same as the * datatype of the array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) append(originalArray, element)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param b array to append * @param value new data for the array * @see PApplet#shorten(boolean[]) * @see PApplet#expand(boolean[]) */ static public byte[] append(byte b[], byte value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public char[] append(char b[], char value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public int[] append(int b[], int value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public float[] append(float b[], float value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public String[] append(String b[], String value) { b = expand(b, b.length + 1); b[b.length-1] = value; return b; } static public Object append(Object b, Object value) { int length = Array.getLength(b); b = expand(b, length + 1); Array.set(b, length, value); return b; } /** * ( begin auto-generated from shorten.xml ) * * Decreases an array by one element and returns the shortened array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) shorten(originalArray)</em>. * * ( end auto-generated ) * * @webref data:array_functions * @param list array to shorten * @see PApplet#append(byte[], byte) * @see PApplet#expand(boolean[]) */ static public boolean[] shorten(boolean list[]) { return subset(list, 0, list.length-1); } static public byte[] shorten(byte list[]) { return subset(list, 0, list.length-1); } static public char[] shorten(char list[]) { return subset(list, 0, list.length-1); } static public int[] shorten(int list[]) { return subset(list, 0, list.length-1); } static public float[] shorten(float list[]) { return subset(list, 0, list.length-1); } static public String[] shorten(String list[]) { return subset(list, 0, list.length-1); } static public Object shorten(Object list) { int length = Array.getLength(list); return subset(list, 0, length - 1); } /** * ( begin auto-generated from splice.xml ) * * Inserts a value or array of values into an existing array. The first two * parameters must be of the same datatype. The <b>array</b> parameter * defines the array which will be modified and the second parameter * defines the data which will be inserted. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) splice(array1, array2, index)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to splice into * @param v value to be spliced in * @param index position in the array from which to insert data * @see PApplet#concat(boolean[], boolean[]) * @see PApplet#subset(boolean[], int, int) */ static final public boolean[] splice(boolean list[], boolean v, int index) { boolean outgoing[] = new boolean[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public boolean[] splice(boolean list[], boolean v[], int index) { boolean outgoing[] = new boolean[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte v, int index) { byte outgoing[] = new byte[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public byte[] splice(byte list[], byte v[], int index) { byte outgoing[] = new byte[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public char[] splice(char list[], char v, int index) { char outgoing[] = new char[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public char[] splice(char list[], char v[], int index) { char outgoing[] = new char[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public int[] splice(int list[], int v, int index) { int outgoing[] = new int[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public int[] splice(int list[], int v[], int index) { int outgoing[] = new int[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public float[] splice(float list[], float v, int index) { float outgoing[] = new float[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public float[] splice(float list[], float v[], int index) { float outgoing[] = new float[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public String[] splice(String list[], String v, int index) { String outgoing[] = new String[list.length + 1]; System.arraycopy(list, 0, outgoing, 0, index); outgoing[index] = v; System.arraycopy(list, index, outgoing, index + 1, list.length - index); return outgoing; } static final public String[] splice(String list[], String v[], int index) { String outgoing[] = new String[list.length + v.length]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, v.length); System.arraycopy(list, index, outgoing, index + v.length, list.length - index); return outgoing; } static final public Object splice(Object list, Object v, int index) { Object[] outgoing = null; int length = Array.getLength(list); // check whether item being spliced in is an array if (v.getClass().getName().charAt(0) == '[') { int vlength = Array.getLength(v); outgoing = new Object[length + vlength]; System.arraycopy(list, 0, outgoing, 0, index); System.arraycopy(v, 0, outgoing, index, vlength); System.arraycopy(list, index, outgoing, index + vlength, length - index); } else { outgoing = new Object[length + 1]; System.arraycopy(list, 0, outgoing, 0, index); Array.set(outgoing, index, v); System.arraycopy(list, index, outgoing, index + 1, length - index); } return outgoing; } static public boolean[] subset(boolean list[], int start) { return subset(list, start, list.length - start); } /** * ( begin auto-generated from subset.xml ) * * Extracts an array of elements from an existing array. The <b>array</b> * parameter defines the array from which the elements will be copied and * the <b>offset</b> and <b>length</b> parameters determine which elements * to extract. If no <b>length</b> is given, elements will be extracted * from the <b>offset</b> to the end of the array. When specifying the * <b>offset</b> remember the first array element is 0. This function does * not change the source array. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) subset(originalArray, 0, 4)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param list array to extract from * @param start position to begin * @param count number of values to extract * @see PApplet#splice(boolean[], boolean, int) */ static public boolean[] subset(boolean list[], int start, int count) { boolean output[] = new boolean[count]; System.arraycopy(list, start, output, 0, count); return output; } static public byte[] subset(byte list[], int start) { return subset(list, start, list.length - start); } static public byte[] subset(byte list[], int start, int count) { byte output[] = new byte[count]; System.arraycopy(list, start, output, 0, count); return output; } static public char[] subset(char list[], int start) { return subset(list, start, list.length - start); } static public char[] subset(char list[], int start, int count) { char output[] = new char[count]; System.arraycopy(list, start, output, 0, count); return output; } static public int[] subset(int list[], int start) { return subset(list, start, list.length - start); } static public int[] subset(int list[], int start, int count) { int output[] = new int[count]; System.arraycopy(list, start, output, 0, count); return output; } static public float[] subset(float list[], int start) { return subset(list, start, list.length - start); } static public float[] subset(float list[], int start, int count) { float output[] = new float[count]; System.arraycopy(list, start, output, 0, count); return output; } static public String[] subset(String list[], int start) { return subset(list, start, list.length - start); } static public String[] subset(String list[], int start, int count) { String output[] = new String[count]; System.arraycopy(list, start, output, 0, count); return output; } static public Object subset(Object list, int start) { int length = Array.getLength(list); return subset(list, start, length - start); } static public Object subset(Object list, int start, int count) { Class<?> type = list.getClass().getComponentType(); Object outgoing = Array.newInstance(type, count); System.arraycopy(list, start, outgoing, 0, count); return outgoing; } /** * ( begin auto-generated from concat.xml ) * * Concatenates two arrays. For example, concatenating the array { 1, 2, 3 * } and the array { 4, 5, 6 } yields { 1, 2, 3, 4, 5, 6 }. Both parameters * must be arrays of the same datatype. * <br/> <br/> * When using an array of objects, the data returned from the function must * be cast to the object array's data type. For example: <em>SomeClass[] * items = (SomeClass[]) concat(array1, array2)</em>. * * ( end auto-generated ) * @webref data:array_functions * @param a first array to concatenate * @param b second array to concatenate * @see PApplet#splice(boolean[], boolean, int) * @see PApplet#arrayCopy(Object, int, Object, int, int) */ static public boolean[] concat(boolean a[], boolean b[]) { boolean c[] = new boolean[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public byte[] concat(byte a[], byte b[]) { byte c[] = new byte[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public char[] concat(char a[], char b[]) { char c[] = new char[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public int[] concat(int a[], int b[]) { int c[] = new int[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public float[] concat(float a[], float b[]) { float c[] = new float[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public String[] concat(String a[], String b[]) { String c[] = new String[a.length + b.length]; System.arraycopy(a, 0, c, 0, a.length); System.arraycopy(b, 0, c, a.length, b.length); return c; } static public Object concat(Object a, Object b) { Class<?> type = a.getClass().getComponentType(); int alength = Array.getLength(a); int blength = Array.getLength(b); Object outgoing = Array.newInstance(type, alength + blength); System.arraycopy(a, 0, outgoing, 0, alength); System.arraycopy(b, 0, outgoing, alength, blength); return outgoing; } // /** * ( begin auto-generated from reverse.xml ) * * Reverses the order of an array. * * ( end auto-generated ) * @webref data:array_functions * @param list booleans[], bytes[], chars[], ints[], floats[], or Strings[] * @see PApplet#sort(String[], int) */ static public boolean[] reverse(boolean list[]) { boolean outgoing[] = new boolean[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public byte[] reverse(byte list[]) { byte outgoing[] = new byte[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public char[] reverse(char list[]) { char outgoing[] = new char[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public int[] reverse(int list[]) { int outgoing[] = new int[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public float[] reverse(float list[]) { float outgoing[] = new float[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public String[] reverse(String list[]) { String outgoing[] = new String[list.length]; int length1 = list.length - 1; for (int i = 0; i < list.length; i++) { outgoing[i] = list[length1 - i]; } return outgoing; } static public Object reverse(Object list) { Class<?> type = list.getClass().getComponentType(); int length = Array.getLength(list); Object outgoing = Array.newInstance(type, length); for (int i = 0; i < length; i++) { Array.set(outgoing, i, Array.get(list, (length - 1) - i)); } return outgoing; } ////////////////////////////////////////////////////////////// // STRINGS /** * ( begin auto-generated from trim.xml ) * * Removes whitespace characters from the beginning and end of a String. In * addition to standard whitespace characters such as space, carriage * return, and tab, this function also removes the Unicode "nbsp" character. * * ( end auto-generated ) * @webref data:string_functions * @param str any string * @see PApplet#split(String, String) * @see PApplet#join(String[], char) */ static public String trim(String str) { return str.replace('\u00A0', ' ').trim(); } /** * @param array a String array */ static public String[] trim(String[] array) { String[] outgoing = new String[array.length]; for (int i = 0; i < array.length; i++) { if (array[i] != null) { outgoing[i] = array[i].replace('\u00A0', ' ').trim(); } } return outgoing; } /** * ( begin auto-generated from join.xml ) * * Combines an array of Strings into one String, each separated by the * character(s) used for the <b>separator</b> parameter. To join arrays of * ints or floats, it's necessary to first convert them to strings using * <b>nf()</b> or <b>nfs()</b>. * * ( end auto-generated ) * @webref data:string_functions * @param str array of Strings * @param separator char or String to be placed between each item * @see PApplet#split(String, String) * @see PApplet#trim(String) * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) */ static public String join(String str[], char separator) { return join(str, String.valueOf(separator)); } static public String join(String str[], String separator) { StringBuffer buffer = new StringBuffer(); for (int i = 0; i < str.length; i++) { if (i != 0) buffer.append(separator); buffer.append(str[i]); } return buffer.toString(); } static public String[] splitTokens(String what) { return splitTokens(what, WHITESPACE); } /** * ( begin auto-generated from splitTokens.xml ) * * The splitTokens() function splits a String at one or many character * "tokens." The <b>tokens</b> parameter specifies the character or * characters to be used as a boundary. * <br/> <br/> * If no <b>tokens</b> character is specified, any whitespace character is * used to split. Whitespace characters include tab (\\t), line feed (\\n), * carriage return (\\r), form feed (\\f), and space. To convert a String * to an array of integers or floats, use the datatype conversion functions * <b>int()</b> and <b>float()</b> to convert the array of Strings. * * ( end auto-generated ) * @webref data:string_functions * @param what the string to be split * @param delim list of individual characters that will be used as separators * @see PApplet#split(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] splitTokens(String what, String delim) { StringTokenizer toker = new StringTokenizer(what, delim); String pieces[] = new String[toker.countTokens()]; int index = 0; while (toker.hasMoreTokens()) { pieces[index++] = toker.nextToken(); } return pieces; } /** * ( begin auto-generated from split.xml ) * * The split() function breaks a string into pieces using a character or * string as the divider. The <b>delim</b> parameter specifies the * character or characters that mark the boundaries between each piece. A * String[] array is returned that contains each of the pieces. * <br/> <br/> * If the result is a set of numbers, you can convert the String[] array to * to a float[] or int[] array using the datatype conversion functions * <b>int()</b> and <b>float()</b> (see example above). * <br/> <br/> * The <b>splitTokens()</b> function works in a similar fashion, except * that it splits using a range of characters instead of a specific * character or sequence. * <!-- /><br /> * This function uses regular expressions to determine how the <b>delim</b> * parameter divides the <b>str</b> parameter. Therefore, if you use * characters such parentheses and brackets that are used with regular * expressions as a part of the <b>delim</b> parameter, you'll need to put * two blackslashes (\\\\) in front of the character (see example above). * You can read more about <a * href="http://en.wikipedia.org/wiki/Regular_expression">regular * expressions</a> and <a * href="http://en.wikipedia.org/wiki/Escape_character">escape * characters</a> on Wikipedia. * --> * * ( end auto-generated ) * @webref data:string_functions * @usage web_application * @param what string to be split * @param delim the character or String used to separate the data */ static public String[] split(String what, char delim) { // do this so that the exception occurs inside the user's // program, rather than appearing to be a bug inside split() if (what == null) return null; //return split(what, String.valueOf(delim)); // huh char chars[] = what.toCharArray(); int splitCount = 0; //1; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) splitCount++; } // make sure that there is something in the input string //if (chars.length > 0) { // if the last char is a delimeter, get rid of it.. //if (chars[chars.length-1] == delim) splitCount--; // on second thought, i don't agree with this, will disable //} if (splitCount == 0) { String splits[] = new String[1]; splits[0] = new String(what); return splits; } //int pieceCount = splitCount + 1; String splits[] = new String[splitCount + 1]; int splitIndex = 0; int startIndex = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] == delim) { splits[splitIndex++] = new String(chars, startIndex, i-startIndex); startIndex = i + 1; } } //if (startIndex != chars.length) { splits[splitIndex] = new String(chars, startIndex, chars.length-startIndex); //} return splits; } static public String[] split(String what, String delim) { ArrayList<String> items = new ArrayList<String>(); int index; int offset = 0; while ((index = what.indexOf(delim, offset)) != -1) { items.add(what.substring(offset, index)); offset = index + delim.length(); } items.add(what.substring(offset)); String[] outgoing = new String[items.size()]; items.toArray(outgoing); return outgoing; } static protected HashMap<String, Pattern> matchPatterns; static Pattern matchPattern(String regexp) { Pattern p = null; if (matchPatterns == null) { matchPatterns = new HashMap<String, Pattern>(); } else { p = matchPatterns.get(regexp); } if (p == null) { if (matchPatterns.size() == 10) { // Just clear out the match patterns here if more than 10 are being // used. It's not terribly efficient, but changes that you have >10 // different match patterns are very slim, unless you're doing // something really tricky (like custom match() methods), in which // case match() won't be efficient anyway. (And you should just be // using your own Java code.) The alternative is using a queue here, // but that's a silly amount of work for negligible benefit. matchPatterns.clear(); } p = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL); matchPatterns.put(regexp, p); } return p; } /** * ( begin auto-generated from match.xml ) * * The match() function is used to apply a regular expression to a piece of * text, and return matching groups (elements found inside parentheses) as * a String array. No match will return null. If no groups are specified in * the regexp, but the sequence matches, an array of length one (with the * matched text as the first element of the array) will be returned.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match. If the sequence did * match, an array is returned. * If there are groups (specified by sets of parentheses) in the regexp, * then the contents of each will be returned in the array. * Element [0] of a regexp match returns the entire matching string, and * the match groups start at element [1] (the first group is [1], the * second [2], and so on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param what the String to be searched * @param regexp the regexp to be used for matching * @see PApplet#matchAll(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[] match(String what, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(what); if (m.find()) { int count = m.groupCount() + 1; String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } return groups; } return null; } /** * ( begin auto-generated from matchAll.xml ) * * This function is used to apply a regular expression to a piece of text, * and return a list of matching groups (elements found inside parentheses) * as a two-dimensional String array. No matches will return null. If no * groups are specified in the regexp, but the sequence matches, a two * dimensional array is still returned, but the second dimension is only of * length one.<br /> * <br /> * To use the function, first check to see if the result is null. If the * result is null, then the sequence did not match at all. If the sequence * did match, a 2D array is returned. If there are groups (specified by * sets of parentheses) in the regexp, then the contents of each will be * returned in the array. * Assuming, a loop with counter variable i, element [i][0] of a regexp * match returns the entire matching string, and the match groups start at * element [i][1] (the first group is [i][1], the second [i][2], and so * on).<br /> * <br /> * The syntax can be found in the reference for Java's <a * href="http://download.oracle.com/javase/6/docs/api/">Pattern</a> class. * For regular expression syntax, read the <a * href="http://download.oracle.com/javase/tutorial/essential/regex/">Java * Tutorial</a> on the topic. * * ( end auto-generated ) * @webref data:string_functions * @param what the String to search inside * @param regexp the regexp to be used for matching * @see PApplet#match(String, String) * @see PApplet#split(String, String) * @see PApplet#splitTokens(String, String) * @see PApplet#join(String[], String) * @see PApplet#trim(String) */ static public String[][] matchAll(String what, String regexp) { Pattern p = matchPattern(regexp); Matcher m = p.matcher(what); ArrayList<String[]> results = new ArrayList<String[]>(); int count = m.groupCount() + 1; while (m.find()) { String[] groups = new String[count]; for (int i = 0; i < count; i++) { groups[i] = m.group(i); } results.add(groups); } if (results.isEmpty()) { return null; } String[][] matches = new String[results.size()][count]; for (int i = 0; i < matches.length; i++) { matches[i] = results.get(i); } return matches; } ////////////////////////////////////////////////////////////// // CASTING FUNCTIONS, INSERTED BY PREPROC /** * Convert a char to a boolean. 'T', 't', and '1' will become the * boolean value true, while 'F', 'f', or '0' will become false. */ /* static final public boolean parseBoolean(char what) { return ((what == 't') || (what == 'T') || (what == '1')); } */ /** * <p>Convert an integer to a boolean. Because of how Java handles upgrading * numbers, this will also cover byte and char (as they will upgrade to * an int without any sort of explicit cast).</p> * <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p> * @return false if 0, true if any other number */ static final public boolean parseBoolean(int what) { return (what != 0); } /* // removed because this makes no useful sense static final public boolean parseBoolean(float what) { return (what != 0); } */ /** * Convert the string "true" or "false" to a boolean. * @return true if 'what' is "true" or "TRUE", false otherwise */ static final public boolean parseBoolean(String what) { return new Boolean(what).booleanValue(); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* // removed, no need to introduce strange syntax from other languages static final public boolean[] parseBoolean(char what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = ((what[i] == 't') || (what[i] == 'T') || (what[i] == '1')); } return outgoing; } */ /** * Convert a byte array to a boolean array. Each element will be * evaluated identical to the integer case, where a byte equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ /* static final public boolean[] parseBoolean(byte what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ /** * Convert an int array to a boolean array. An int equal * to zero will return false, and any other value will return true. * @return array of boolean elements */ static final public boolean[] parseBoolean(int what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } /* // removed, not necessary... if necessary, convert to int array first static final public boolean[] parseBoolean(float what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (what[i] != 0); } return outgoing; } */ static final public boolean[] parseBoolean(String what[]) { boolean outgoing[] = new boolean[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = new Boolean(what[i]).booleanValue(); } return outgoing; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte parseByte(boolean what) { return what ? (byte)1 : 0; } static final public byte parseByte(char what) { return (byte) what; } static final public byte parseByte(int what) { return (byte) what; } static final public byte parseByte(float what) { return (byte) what; } /* // nixed, no precedent static final public byte[] parseByte(String what) { // note: array[] return what.getBytes(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public byte[] parseByte(boolean what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? (byte)1 : 0; } return outgoing; } static final public byte[] parseByte(char what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(int what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } static final public byte[] parseByte(float what[]) { byte outgoing[] = new byte[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (byte) what[i]; } return outgoing; } /* static final public byte[][] parseByte(String what[]) { // note: array[][] byte outgoing[][] = new byte[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].getBytes(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char parseChar(boolean what) { // 0/1 or T/F ? return what ? 't' : 'f'; } */ static final public char parseChar(byte what) { return (char) (what & 0xff); } static final public char parseChar(int what) { return (char) what; } /* static final public char parseChar(float what) { // nonsensical return (char) what; } static final public char[] parseChar(String what) { // note: array[] return what.toCharArray(); } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public char[] parseChar(boolean what[]) { // 0/1 or T/F ? char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i] ? 't' : 'f'; } return outgoing; } */ static final public char[] parseChar(byte what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) (what[i] & 0xff); } return outgoing; } static final public char[] parseChar(int what[]) { char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } /* static final public char[] parseChar(float what[]) { // nonsensical char outgoing[] = new char[what.length]; for (int i = 0; i < what.length; i++) { outgoing[i] = (char) what[i]; } return outgoing; } static final public char[][] parseChar(String what[]) { // note: array[][] char outgoing[][] = new char[what.length][]; for (int i = 0; i < what.length; i++) { outgoing[i] = what[i].toCharArray(); } return outgoing; } */ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int parseInt(boolean what) { return what ? 1 : 0; } /** * Note that parseInt() will un-sign a signed byte value. */ static final public int parseInt(byte what) { return what & 0xff; } /** * Note that parseInt('5') is unlike String in the sense that it * won't return 5, but the ascii value. This is because ((int) someChar) * returns the ascii value, and parseInt() is just longhand for the cast. */ static final public int parseInt(char what) { return what; } /** * Same as floor(), or an (int) cast. */ static final public int parseInt(float what) { return (int) what; } /** * Parse a String into an int value. Returns 0 if the value is bad. */ static final public int parseInt(String what) { return parseInt(what, 0); } /** * Parse a String to an int, and provide an alternate value that * should be used when the number is invalid. */ static final public int parseInt(String what, int otherwise) { try { int offset = what.indexOf('.'); if (offset == -1) { return Integer.parseInt(what); } else { return Integer.parseInt(what.substring(0, offset)); } } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public int[] parseInt(boolean what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i] ? 1 : 0; } return list; } static final public int[] parseInt(byte what[]) { // note this unsigns int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = (what[i] & 0xff); } return list; } static final public int[] parseInt(char what[]) { int list[] = new int[what.length]; for (int i = 0; i < what.length; i++) { list[i] = what[i]; } return list; } static public int[] parseInt(float what[]) { int inties[] = new int[what.length]; for (int i = 0; i < what.length; i++) { inties[i] = (int)what[i]; } return inties; } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, it will be set to zero. * * String s[] = { "1", "300", "44" }; * int numbers[] = parseInt(s); * * numbers will contain { 1, 300, 44 } */ static public int[] parseInt(String what[]) { return parseInt(what, 0); } /** * Make an array of int elements from an array of String objects. * If the String can't be parsed as a number, its entry in the * array will be set to the value of the "missing" parameter. * * String s[] = { "1", "300", "apple", "44" }; * int numbers[] = parseInt(s, 9999); * * numbers will contain { 1, 300, 9999, 44 } */ static public int[] parseInt(String what[], int missing) { int output[] = new int[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = Integer.parseInt(what[i]); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float parseFloat(boolean what) { return what ? 1 : 0; } */ /** * Convert an int to a float value. Also handles bytes because of * Java's rules for upgrading values. */ static final public float parseFloat(int what) { // also handles byte return what; } static final public float parseFloat(String what) { return parseFloat(what, Float.NaN); } static final public float parseFloat(String what, float otherwise) { try { return new Float(what).floatValue(); } catch (NumberFormatException e) { } return otherwise; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /* static final public float[] parseFloat(boolean what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i] ? 1 : 0; } return floaties; } static final public float[] parseFloat(char what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = (char) what[i]; } return floaties; } */ static final public float[] parseByte(byte what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(int what[]) { float floaties[] = new float[what.length]; for (int i = 0; i < what.length; i++) { floaties[i] = what[i]; } return floaties; } static final public float[] parseFloat(String what[]) { return parseFloat(what, Float.NaN); } static final public float[] parseFloat(String what[], float missing) { float output[] = new float[what.length]; for (int i = 0; i < what.length; i++) { try { output[i] = new Float(what[i]).floatValue(); } catch (NumberFormatException e) { output[i] = missing; } } return output; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String str(boolean x) { return String.valueOf(x); } static final public String str(byte x) { return String.valueOf(x); } static final public String str(char x) { return String.valueOf(x); } static final public String str(int x) { return String.valueOf(x); } static final public String str(float x) { return String.valueOf(x); } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . static final public String[] str(boolean x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(byte x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(char x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(int x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } static final public String[] str(float x[]) { String s[] = new String[x.length]; for (int i = 0; i < x.length; i++) s[i] = String.valueOf(x[i]); return s; } ////////////////////////////////////////////////////////////// // INT NUMBER FORMATTING /** * Integer number formatter. */ static private NumberFormat int_nf; static private int int_nf_digits; static private boolean int_nf_commas; static public String[] nf(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], digits); } return formatted; } /** * ( begin auto-generated from nf.xml ) * * Utility function for formatting numbers into strings. There are two * versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers.<br /><br />As shown in the above * example, <b>nf()</b> is used to add zeros to the left and/or right of a * number. This is typically for aligning a list of numbers. To * <em>remove</em> digits from a floating-point number, use the * <b>int()</b>, <b>ceil()</b>, <b>floor()</b>, or <b>round()</b> * functions. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zero * @see PApplet#nfs(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String nf(int num, int digits) { if ((int_nf != null) && (int_nf_digits == digits) && !int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(false); // no commas int_nf_commas = false; int_nf.setMinimumIntegerDigits(digits); int_nf_digits = digits; return int_nf.format(num); } /** * ( begin auto-generated from nfc.xml ) * * Utility function for formatting numbers into strings and placing * appropriate commas to mark units of 1000. There are two versions, one * for formatting ints and one for formatting an array of ints. The value * for the <b>digits</b> parameter should always be a positive integer. * <br/> <br/> * For a non-US locale, this will insert periods instead of commas, or * whatever is apprioriate for that region. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String[] nfc(int num[]) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i]); } return formatted; } /** * nfc() or "number format with commas". This is an unfortunate misnomer * because in locales where a comma is not the separator for numbers, it * won't actually be outputting a comma, it'll use whatever makes sense for * the locale. */ static public String nfc(int num) { if ((int_nf != null) && (int_nf_digits == 0) && int_nf_commas) { return int_nf.format(num); } int_nf = NumberFormat.getInstance(); int_nf.setGroupingUsed(true); int_nf_commas = true; int_nf.setMinimumIntegerDigits(0); int_nf_digits = 0; return int_nf.format(num); } /** * number format signed (or space) * Formats a number but leaves a blank space in the front * when it's positive so that it can be properly aligned with * numbers that have a negative sign in front of them. */ /** * ( begin auto-generated from nfs.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but leaves a blank space in front of positive numbers so * they align with negative numbers in spite of the minus symbol. There are * two versions, one for formatting floats and one for formatting ints. The * values for the <b>digits</b>, <b>left</b>, and <b>right</b> parameters * should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfp(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfs(int num, int digits) { return (num < 0) ? nf(num, digits) : (' ' + nf(num, digits)); } static public String[] nfs(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], digits); } return formatted; } // /** * number format positive (or plus) * Formats a number, always placing a - or + sign * in the front when it's negative or positive. */ /** * ( begin auto-generated from nfp.xml ) * * Utility function for formatting numbers into strings. Similar to * <b>nf()</b> but puts a "+" in front of positive numbers and a "-" in * front of negative numbers. There are two versions, one for formatting * floats and one for formatting ints. The values for the <b>digits</b>, * <b>left</b>, and <b>right</b> parameters should always be positive integers. * * ( end auto-generated ) * @webref data:string_functions * @param num[] the number(s) to format * @param digits number of digits to pad with zeroes * @see PApplet#nf(float, int, int) * @see PApplet#nfs(float, int, int) * @see PApplet#nfc(float, int) */ static public String nfp(int num, int digits) { return (num < 0) ? nf(num, digits) : ('+' + nf(num, digits)); } static public String[] nfp(int num[], int digits) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], digits); } return formatted; } ////////////////////////////////////////////////////////////// // FLOAT NUMBER FORMATTING static private NumberFormat float_nf; static private int float_nf_left, float_nf_right; static private boolean float_nf_commas; static public String[] nf(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nf(num[i], left, right); } return formatted; } /** * @param num[] the number(s) to format * @param left number of digits to the left of the decimal point * @param right number of digits to the right of the decimal point */ static public String nf(float num, int left, int right) { if ((float_nf != null) && (float_nf_left == left) && (float_nf_right == right) && !float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(false); float_nf_commas = false; if (left != 0) float_nf.setMinimumIntegerDigits(left); if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = left; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param right number of digits to the right of the decimal point */ static public String[] nfc(float num[], int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfc(num[i], right); } return formatted; } static public String nfc(float num, int right) { if ((float_nf != null) && (float_nf_left == 0) && (float_nf_right == right) && float_nf_commas) { return float_nf.format(num); } float_nf = NumberFormat.getInstance(); float_nf.setGroupingUsed(true); float_nf_commas = true; if (right != 0) { float_nf.setMinimumFractionDigits(right); float_nf.setMaximumFractionDigits(right); } float_nf_left = 0; float_nf_right = right; return float_nf.format(num); } /** * @param num[] the number(s) to format * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfs(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfs(num[i], left, right); } return formatted; } static public String nfs(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : (' ' + nf(num, left, right)); } /** * @param num[] the number(s) to format * @param left the number of digits to the left of the decimal point * @param right the number of digits to the right of the decimal point */ static public String[] nfp(float num[], int left, int right) { String formatted[] = new String[num.length]; for (int i = 0; i < formatted.length; i++) { formatted[i] = nfp(num[i], left, right); } return formatted; } /** * @param num the number(s) to format */ static public String nfp(float num, int left, int right) { return (num < 0) ? nf(num, left, right) : ('+' + nf(num, left, right)); } ////////////////////////////////////////////////////////////// // HEX/BINARY CONVERSION /** * ( begin auto-generated from hex.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent hexadecimal notation. For example color(0, 102, 153) will * convert to the String "FF006699". This function can help make your geeky * debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 8, because an int value can * only represent up to 32 bits. Specifying more than eight digits will * simply shorten the string to eight anyway. * * ( end auto-generated ) * @webref data:conversion * @param what the value to convert * @see PApplet#unhex(String) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public String hex(byte what) { return hex(what, 2); } static final public String hex(char what) { return hex(what, 4); } static final public String hex(int what) { return hex(what, 8); } /** * @param digits the number of digits (maximum 8) */ static final public String hex(int what, int digits) { String stuff = Integer.toHexString(what).toUpperCase(); if (digits > 8) { digits = 8; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { return "00000000".substring(8 - (digits-length)) + stuff; } return stuff; } /** * ( begin auto-generated from unhex.xml ) * * Converts a String representation of a hexadecimal number to its * equivalent integer value. * * ( end auto-generated ) * * @webref data:conversion * @param what String to convert to an integer * @see PApplet#hex(int, int) * @see PApplet#binary(byte) * @see PApplet#unbinary(String) */ static final public int unhex(String what) { // has to parse as a Long so that it'll work for numbers bigger than 2^31 return (int) (Long.parseLong(what, 16)); } // /** * Returns a String that contains the binary value of a byte. * The returned value will always have 8 digits. */ static final public String binary(byte what) { return binary(what, 8); } /** * Returns a String that contains the binary value of a char. * The returned value will always have 16 digits because chars * are two bytes long. */ static final public String binary(char what) { return binary(what, 16); } /** * Returns a String that contains the binary value of an int. The length * depends on the size of the number itself. If you want a specific number * of digits use binary(int what, int digits) to specify how many. */ static final public String binary(int what) { return binary(what, 32); } /* * Returns a String that contains the binary value of an int. * The digits parameter determines how many digits will be used. */ /** * ( begin auto-generated from binary.xml ) * * Converts a byte, char, int, or color to a String containing the * equivalent binary notation. For example color(0, 102, 153, 255) will * convert to the String "11111111000000000110011010011001". This function * can help make your geeky debugging sessions much happier. * <br/> <br/> * Note that the maximum number of digits is 32, because an int value can * only represent up to 32 bits. Specifying more than 32 digits will simply * shorten the string to 32 anyway. * * ( end auto-generated ) * @webref data:conversion * @param what value to convert * @param digits number of digits to return * @see PApplet#unbinary(String) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public String binary(int what, int digits) { String stuff = Integer.toBinaryString(what); if (digits > 32) { digits = 32; } int length = stuff.length(); if (length > digits) { return stuff.substring(length - digits); } else if (length < digits) { int offset = 32 - (digits-length); return "00000000000000000000000000000000".substring(offset) + stuff; } return stuff; } /** * ( begin auto-generated from unbinary.xml ) * * Converts a String representation of a binary number to its equivalent * integer value. For example, unbinary("00001000") will return 8. * * ( end auto-generated ) * @webref data:conversion * @param what String to convert to an integer * @see PApplet#binary(byte) * @see PApplet#hex(int,int) * @see PApplet#unhex(String) */ static final public int unbinary(String what) { return Integer.parseInt(what, 2); } ////////////////////////////////////////////////////////////// // COLOR FUNCTIONS // moved here so that they can work without // the graphics actually being instantiated (outside setup) /** * ( begin auto-generated from color.xml ) * * Creates colors for storing in variables of the <b>color</b> datatype. * The parameters are interpreted as RGB or HSB values depending on the * current <b>colorMode()</b>. The default mode is RGB values from 0 to 255 * and therefore, the function call <b>color(255, 204, 0)</b> will return a * bright yellow color. More about how colors are stored can be found in * the reference for the <a href="color_datatype.html">color</a> datatype. * * ( end auto-generated ) * @webref color:creating_reading * @param gray number specifying value between white and black * @see PApplet#colorMode(int) */ public final int color(int gray) { if (g == null) { if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(gray); } /** * @nowebref * @param fgray number specifying value between white and black */ public final int color(float fgray) { if (g == null) { int gray = (int) fgray; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray); } /** * As of 0116 this also takes color(#FF8800, alpha) * * @param alpha relative to current color range */ public final int color(int gray, int alpha) { if (g == null) { if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; if (gray > 255) { // then assume this is actually a #FF8800 return (alpha << 24) | (gray & 0xFFFFFF); } else { //if (gray > 255) gray = 255; else if (gray < 0) gray = 0; return (alpha << 24) | (gray << 16) | (gray << 8) | gray; } } return g.color(gray, alpha); } /** * @nowebref */ public final int color(float fgray, float falpha) { if (g == null) { int gray = (int) fgray; int alpha = (int) falpha; if (gray > 255) gray = 255; else if (gray < 0) gray = 0; if (alpha > 255) alpha = 255; else if (alpha < 0) alpha = 0; return 0xff000000 | (gray << 16) | (gray << 8) | gray; } return g.color(fgray, falpha); } /** * @param x red or hue values relative to the current color range * @param y green or saturation values relative to the current color range * @param z blue or brightness values relative to the current color range */ public final int color(int x, int y, int z) { if (g == null) { if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return 0xff000000 | (x << 16) | (y << 8) | z; } return g.color(x, y, z); } public final int color(int x, int y, int z, int a) { if (g == null) { if (a > 255) a = 255; else if (a < 0) a = 0; if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return (a << 24) | (x << 16) | (y << 8) | z; } return g.color(x, y, z, a); } public final int color(float x, float y, float z) { if (g == null) { if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return 0xff000000 | ((int)x << 16) | ((int)y << 8) | (int)z; } return g.color(x, y, z); } public final int color(float x, float y, float z, float a) { if (g == null) { if (a > 255) a = 255; else if (a < 0) a = 0; if (x > 255) x = 255; else if (x < 0) x = 0; if (y > 255) y = 255; else if (y < 0) y = 0; if (z > 255) z = 255; else if (z < 0) z = 0; return ((int)a << 24) | ((int)x << 16) | ((int)y << 8) | (int)z; } return g.color(x, y, z, a); } ////////////////////////////////////////////////////////////// // MAIN /** * Set this sketch to communicate its state back to the PDE. * <p/> * This uses the stderr stream to write positions of the window * (so that it will be saved by the PDE for the next run) and * notify on quit. See more notes in the Worker class. */ public void setupExternalMessages() { frame.addComponentListener(new ComponentAdapter() { public void componentMoved(ComponentEvent e) { Point where = ((Frame) e.getSource()).getLocation(); System.err.println(PApplet.EXTERNAL_MOVE + " " + where.x + " " + where.y); System.err.flush(); // doesn't seem to help or hurt } }); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { // System.err.println(PApplet.EXTERNAL_QUIT); // System.err.flush(); // important // System.exit(0); exit(); // don't quit, need to just shut everything down (0133) } }); } /** * Set up a listener that will fire proper component resize events * in cases where frame.setResizable(true) is called. */ public void setupFrameResizeListener() { frame.addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { // Ignore bad resize events fired during setup to fix // http://dev.processing.org/bugs/show_bug.cgi?id=341 // This should also fix the blank screen on Linux bug // http://dev.processing.org/bugs/show_bug.cgi?id=282 if (frame.isResizable()) { // might be multiple resize calls before visible (i.e. first // when pack() is called, then when it's resized for use). // ignore them because it's not the user resizing things. Frame farm = (Frame) e.getComponent(); if (farm.isVisible()) { Insets insets = farm.getInsets(); Dimension windowSize = farm.getSize(); int usableW = windowSize.width - insets.left - insets.right; int usableH = windowSize.height - insets.top - insets.bottom; // the ComponentListener in PApplet will handle calling size() setBounds(insets.left, insets.top, usableW, usableH); } } } }); } /** * GIF image of the Processing logo. */ static public final byte[] ICON_IMAGE = { 71, 73, 70, 56, 57, 97, 16, 0, 16, 0, -77, 0, 0, 0, 0, 0, -1, -1, -1, 12, 12, 13, -15, -15, -14, 45, 57, 74, 54, 80, 111, 47, 71, 97, 62, 88, 117, 1, 14, 27, 7, 41, 73, 15, 52, 85, 2, 31, 55, 4, 54, 94, 18, 69, 109, 37, 87, 126, -1, -1, -1, 33, -7, 4, 1, 0, 0, 15, 0, 44, 0, 0, 0, 0, 16, 0, 16, 0, 0, 4, 122, -16, -107, 114, -86, -67, 83, 30, -42, 26, -17, -100, -45, 56, -57, -108, 48, 40, 122, -90, 104, 67, -91, -51, 32, -53, 77, -78, -100, 47, -86, 12, 76, -110, -20, -74, -101, 97, -93, 27, 40, 20, -65, 65, 48, -111, 99, -20, -112, -117, -123, -47, -105, 24, 114, -112, 74, 69, 84, 25, 93, 88, -75, 9, 46, 2, 49, 88, -116, -67, 7, -19, -83, 60, 38, 3, -34, 2, 66, -95, 27, -98, 13, 4, -17, 55, 33, 109, 11, 11, -2, -128, 121, 123, 62, 91, 120, -128, 127, 122, 115, 102, 2, 119, 0, -116, -113, -119, 6, 102, 121, -108, -126, 5, 18, 6, 4, -102, -101, -100, 114, 15, 17, 0, 59 }; /** * main() method for running this class from the command line. * <p> * <B>The options shown here are not yet finalized and will be * changing over the next several releases.</B> * <p> * The simplest way to turn and applet into an application is to * add the following code to your program: * <PRE>static public void main(String args[]) { * PApplet.main(new String[] { "YourSketchName" }); * }</PRE> * This will properly launch your applet from a double-clickable * .jar or from the command line. * <PRE> * Parameters useful for launching or also used by the PDE: * * --location=x,y upper-lefthand corner of where the applet * should appear on screen. if not used, * the default is to center on the main screen. * * --present put the applet into full screen presentation * mode. requires java 1.4 or later. * * --exclusive use full screen exclusive mode when presenting. * disables new windows or interaction with other * monitors, this is like a "game" mode. * * --hide-stop use to hide the stop button in situations where * you don't want to allow users to exit. also * see the FAQ on information for capturing the ESC * key when running in presentation mode. * * --stop-color=#xxxxxx color of the 'stop' text used to quit an * sketch when it's in present mode. * * --bgcolor=#xxxxxx background color of the window. * * --sketch-path location of where to save files from functions * like saveStrings() or saveFrame(). defaults to * the folder that the java application was * launched from, which means if this isn't set by * the pde, everything goes into the same folder * as processing.exe. * * --display=n set what display should be used by this applet. * displays are numbered starting from 1. * * Parameters used by Processing when running via the PDE * * --external set when the applet is being used by the PDE * * --editor-location=x,y position of the upper-lefthand corner of the * editor window, for placement of applet window * </PRE> */ static public void runSketch(String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; boolean exclusive = false; Color backgroundColor = Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value) - 1; //DisplayMode dm = device.getDisplayMode(); //if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { present = true; } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; - break; + break; // because of break, argIndex won't increment again } } argIndex++; } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } Frame frame = new Frame(displayDevice.getDefaultConfiguration()); /* Frame frame = null; if (displayDevice != null) { frame = new Frame(displayDevice.getDefaultConfiguration()); } else { frame = new Frame(); } */ //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // remove the grow box by default // users who want it back can call frame.setResizable(true) // frame.setResizable(false); // moved later (issue #467) // Set the trimmings around the image Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); frame.setIconImage(image); frame.setTitle(name); final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // these are needed before init/start applet.frame = frame; applet.sketchPath = folder; - applet.args = PApplet.subset(args, 1); + // pass everything after the class name in as args to the sketch itself + // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts) + applet.args = PApplet.subset(args, argIndex + 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle fullScreenRect = null; // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { frame.setUndecorated(true); frame.setBackground(backgroundColor); if (exclusive) { displayDevice.setFullScreenWindow(frame); // this trashes the location of the window on os x //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); fullScreenRect = frame.getBounds(); } else { DisplayMode mode = displayDevice.getDisplayMode(); fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight()); frame.setBounds(fullScreenRect); frame.setVisible(true); } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } //println("not default size " + applet.width + " " + applet.height); //println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")"); if (present) { // After the pack(), the screen bounds are gonna be 0s frame.setBounds(fullScreenRect); applet.setBounds((fullScreenRect.width - applet.width) / 2, (fullScreenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, fullScreenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from PdeRuntime // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.screenWidth - 33) || (locationY + windowH > applet.screenHeight - 33)) { // otherwise center on screen locationX = (applet.screenWidth - windowW) / 2; locationY = (applet.screenHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen frame.setLocation((applet.screenWidth - applet.width) / 2, (applet.screenHeight - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor == Color.black) { //BLACK) { // this means no bg color unless specified backgroundColor = SystemColor.control; } frame.setBackground(backgroundColor); int usableWindowH = windowH - insets.top - insets.bottom; applet.setBounds((windowW - applet.width)/2, insets.top + (usableWindowH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } public static void main(final String[] args) { runSketch(args, null); } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core public void flush() { if (recorder != null) recorder.flush(); g.flush(); } /** * ( begin auto-generated from hint.xml ) * * Set various hints and hacks for the renderer. This is used to handle * obscure rendering features that cannot be implemented in a consistent * manner across renderers. Many options will often graduate to standard * features instead of hints over time. * <br/> <br/> * hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for P3D. This * can help force anti-aliasing if it has not been enabled by the user. On * some graphics cards, this can also be set by the graphics driver's * control panel, however not all cards make this available. This hint must * be called immediately after the size() command because it resets the * renderer, obliterating any settings and anything drawn (and like size(), * re-running the code that came before it again). * <br/> <br/> * hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always * enables 2x smoothing when the P3D renderer is used. This hint disables * the default 2x smoothing and returns the smoothing behavior found in * earlier releases, where smooth() and noSmooth() could be used to enable * and disable smoothing, though the quality was inferior. * <br/> <br/> * hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are * installed, rather than the bitmapped version from a .vlw file. This is * useful with the default (or JAVA2D) renderer setting, as it will improve * font rendering speed. This is not enabled by default, because it can be * misleading while testing because the type will look great on your * machine (because you have the font installed) but lousy on others' * machines if the identical font is unavailable. This option can only be * set per-sketch, and must be called before any use of textFont(). * <br/> <br/> * hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on * top of everything at will. When depth testing is disabled, items will be * drawn to the screen sequentially, like a painting. This hint is most * often used to draw in 3D, then draw in 2D on top of it (for instance, to * draw GUI controls in 2D on top of a 3D interface). Starting in release * 0149, this will also clear the depth buffer. Restore the default with * hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared, * any 3D drawing that happens later in draw() will ignore existing shapes * on the screen. * <br/> <br/> * hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and * lines in P3D and OPENGL. This can slow performance considerably, and the * algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT). * <br/> <br/> * hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the P3D renderer setting * by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT). * <br/> <br/> * <!--hint(ENABLE_ACCURATE_TEXTURES) - Enables better texture accuracy for * the P3D renderer. This option will do a better job of dealing with * textures in perspective. hint(DISABLE_ACCURATE_TEXTURES) returns to the * default. This hint is not likely to last long. * <br/> <br/>--> * As of release 0149, unhint() has been removed in favor of adding * additional ENABLE/DISABLE constants to reset the default behavior. This * prevents the double negatives, and also reinforces which hints can be * enabled or disabled. * * ( end auto-generated ) * @webref rendering * @param which name of the hint to be enabled or disabled * @see PGraphics * @see PApplet#createGraphics(int, int, String, String) * @see PApplet#size(int, int) */ public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } public boolean hintEnabled(int which) { return g.hintEnabled(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMALIZED, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref shape:vertex * @param mode either IMAGE or NORMALIZED * @see PGraphics#texture(PImage) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref shape:vertex * @param image the texture to apply * @see PGraphics#textureMode(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * * @param image reference to a PImage object */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** This feature is in testing, do not use or rely upon its implementation */ public void breakShape() { if (recorder != null) recorder.breakShape(); g.breakShape(); } public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse * @param d height of the ellipse * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse * @param d height of the arc's ellipse * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions, creates a cube * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } public void image(PImage image, float x, float y) { if (recorder != null) recorder.image(image, x, y); g.image(image, x, y); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param image the image to display * @param x x-coordinate of the image * @param y y-coordinate of the image * @param c width to display the image * @param d height to display the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage image, float x, float y, float c, float d) { if (recorder != null) recorder.image(image, x, y, c, d); g.image(image, x, y, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage image, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2); g.image(image, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) */ public void shape(PShape shape, float x, float y, float c, float d) { if (recorder != null) recorder.shape(shape, x, y, c, d); g.shape(shape, x, y, c, d); } public void textAlign(int align) { if (recorder != null) recorder.textAlign(align); g.textAlign(align); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float, float, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c) { if (recorder != null) recorder.text(c); g.text(c); } /** * <h3>Advanced</h3> * Draw a single character on screen. * Extremely slow when used with textMode(SCREEN) and Java 2D, * because loadPixels has to be called first and updatePixels last. * * @param x x-coordinate of text * @param y y-coordinate of text */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * @param str the alphanumeric symbols to be displayed */ public void text(String str) { if (recorder != null) recorder.text(str); g.text(str); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index to start writing characters * @param stop array index to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(String s, float x1, float y1, float x2, float y2, float z) { if (recorder != null) recorder.text(s, x1, y1, x2, y2, z); g.text(s, x1, y1, x2, y2, z); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the alphanumeric symbols to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param tx left/right translation * @param ty up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float tx, float ty) { if (recorder != null) recorder.translate(tx, ty); g.translate(tx, ty); } /** * @param tz forward/backward translation */ public void translate(float tx, float ty, float tz) { if (recorder != null) recorder.translate(tx, ty, tz); g.translate(tx, ty, tz); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param vx * @param vy * @param vz */ public void rotate(float angle, float vx, float vy, float vz) { if (recorder != null) recorder.rotate(angle, vx, vy, vz); g.rotate(angle, vx, vy, vz); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#translate(float, float, float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param sx percentage to scale the object in the x-axis * @param sy percentage to scale the objects in the y-axis */ public void scale(float sx, float sy) { if (recorder != null) recorder.scale(sx, sy); g.scale(sx, sy); } /** * @param x percentage to scale the object in the x-axis * @param y percentage to scale the objects in the y-axis * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of nearest farthest plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane * @param far far component of the clipping plane * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float x, float y, float z) { if (recorder != null) recorder.stroke(x, y, z); g.stroke(x, y, z); } public void stroke(float x, float y, float z, float alpha) { if (recorder != null) recorder.stroke(x, y, z, alpha); g.stroke(x, y, z, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param rgb color value in hexadecimal notation * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray any valid number */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void tint(float x, float y, float z) { if (recorder != null) recorder.tint(x, y, z); g.tint(x, y, z); } /** * @param z opacity of the image */ public void tint(float x, float y, float z, float a) { if (recorder != null) recorder.tint(x, y, z, a); g.tint(x, y, z, a); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } public void fill(float x, float y, float z) { if (recorder != null) recorder.fill(x, y, z); g.fill(x, y, z); } /** * @param a opacity of the fill */ public void fill(float x, float y, float z, float a) { if (recorder != null) recorder.fill(x, y, z, a); g.fill(x, y, z, a); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void ambient(float x, float y, float z) { if (recorder != null) recorder.ambient(x, y, z); g.ambient(x, y, z); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void specular(float x, float y, float z) { if (recorder != null) recorder.specular(x, y, z); g.specular(x, y, z); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void emissive(float x, float y, float z) { if (recorder != null) recorder.emissive(x, y, z); g.emissive(x, y, z); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float red, float green, float blue) { if (recorder != null) recorder.ambientLight(red, green, blue); g.ambientLight(red, green, blue); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float red, float green, float blue, float x, float y, float z) { if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z); g.ambientLight(red, green, blue, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float red, float green, float blue, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz); g.directionalLight(red, green, blue, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float red, float green, float blue, float x, float y, float z) { if (recorder != null) recorder.pointLight(red, green, blue, x, y, z); g.pointLight(red, green, blue, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float red, float green, float blue, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float x, float y, float z) { if (recorder != null) recorder.lightSpecular(x, y, z); g.lightSpecular(x, y, z); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param x red or hue value (depending on the current color mode) * @param y green or saturation value (depending on the current color mode) * @param z blue or brightness value (depending on the current color mode) */ public void background(float x, float y, float z) { if (recorder != null) recorder.background(x, y, z); g.background(x, y, z); } /** * @param a opacity of the background */ public void background(float x, float y, float z, float a) { if (recorder != null) recorder.background(x, y, z, a); g.background(x, y, z, a); } /** * @param image PImage to set as background (must be same size as the program) * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task. * <P> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000), because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Using image.filter(OPAQUE) will handle this easily. * <P> * When using 3D, this will also clear the zbuffer (if it exists). */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param maxX range for the red or hue depending on the current color mode * @param maxY range for the green or saturation depending on the current color mode * @param maxZ range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float maxX, float maxY, float maxZ) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ); g.colorMode(mode, maxX, maxY, maxZ); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float maxX, float maxY, float maxZ, float maxA) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA); g.colorMode(mode, maxX, maxY, maxZ, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int what) { return g.alpha(what); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int what) { return g.red(what); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int what) { return g.green(what); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int what) { return g.blue(what); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int what) { return g.hue(what); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int what) { return g.saturation(what); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int what) { return g.brightness(what); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } public PShape createShape() { return g.createShape(); } public PShape createShape(int type) { return g.createShape(type); } public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void delete() { if (recorder != null) recorder.delete(); g.delete(); } /** * Store data of some kind for a renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PGraphics renderer, Object storage) { if (recorder != null) recorder.setCache(renderer, storage); g.setCache(renderer, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PGraphics renderer) { return g.getCache(renderer); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PGraphics renderer) { if (recorder != null) recorder.removeCache(renderer); g.removeCache(renderer); } /** * Store parameters for a renderer that requires extra metadata of * some kind. * @param renderer The PGraphics renderer associated to the image * @param storage The parameters required by the renderer */ public void setParams(PGraphics renderer, Object params) { if (recorder != null) recorder.setParams(renderer, params); g.setParams(renderer, params); } /** * Get the parameters for the specified renderer. * @param renderer The PGraphics renderer associated to the image * @return parameters stored for the specified renderer */ public Object getParams(PGraphics renderer) { return g.getParams(renderer); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose parameters should be removed */ public void removeParams(PGraphics renderer) { if (recorder != null) recorder.removeParams(renderer); g.removeParams(renderer); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param src image to draw on screen */ public void set(int x, int y, PImage src) { if (recorder != null) recorder.set(x, y, src); g.set(x, y, src); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(int maskArray[]) { if (recorder != null) recorder.mask(maskArray); g.mask(maskArray); } /** * @param maskImg a PImage object used as the alpha channel for "img", must be same dimensions as "img" */ public void mask(PImage maskImg) { if (recorder != null) recorder.mask(maskImg); g.mask(maskImg); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } /** * ( begin auto-generated from blendColor.xml ) * * Blends two color values together based on the blending mode given as the * <b>MODE</b> parameter. The possible modes are described in the reference * for the <b>blend()</b> function. * * ( end auto-generated ) * <h3>Advanced</h3> * <UL> * <LI>REPLACE - destination colour equals colour of source pixel: C = A. * Sometimes called "Normal" or "Copy" in other software. * * <LI>BLEND - linear interpolation of colours: * <TT>C = A*factor + B</TT> * * <LI>ADD - additive blending with white clip: * <TT>C = min(A*factor + B, 255)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Burn", * and Director calls it "Add Pin". * * <LI>SUBTRACT - substractive blend with black clip: * <TT>C = max(B - A*factor, 0)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Dodge", * and Director calls it "Subtract Pin". * * <LI>DARKEST - only the darkest colour succeeds: * <TT>C = min(A*factor, B)</TT>. * Illustrator calls this "Darken". * * <LI>LIGHTEST - only the lightest colour succeeds: * <TT>C = max(A*factor, B)</TT>. * Illustrator calls this "Lighten". * * <LI>DIFFERENCE - subtract colors from underlying image. * * <LI>EXCLUSION - similar to DIFFERENCE, but less extreme. * * <LI>MULTIPLY - Multiply the colors, result will always be darker. * * <LI>SCREEN - Opposite multiply, uses inverse values of the colors. * * <LI>OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values. * * <LI>HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. * * <LI>SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh. * * <LI>DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop. * * <LI>BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop. * </UL> * <P>A useful reference for blending modes and their algorithms can be * found in the <A HREF="http://www.w3.org/TR/SVG12/rendering.html">SVG</A> * specification.</P> * <P>It is important to note that Processing uses "fast" code, not * necessarily "correct" code. No biggie, most software does. A nitpicker * can find numerous "off by 1 division" problems in the blend code where * <TT>&gt;&gt;8</TT> or <TT>&gt;&gt;7</TT> is used when strictly speaking * <TT>/255.0</T> or <TT>/127.0</TT> should have been used.</P> * <P>For instance, exclusion (not intended for real-time use) reads * <TT>r1 + r2 - ((2 * r1 * r2) / 255)</TT> because <TT>255 == 1.0</TT> * not <TT>256 == 1.0</TT>. In other words, <TT>(255*255)>>8</TT> is not * the same as <TT>(255*255)/255</TT>. But for real-time use the shifts * are preferrable, and the difference is insignificant for applications * built with Processing.</P> * * @webref color:creating_reading * @usage web_application * @param c1 the first color to blend * @param c2 the second color to blend * @param mode either BLEND, ADD, SUBTRACT, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, or BURN * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) * @see PApplet#color(float, float, float, float) */ static public int blendColor(int c1, int c2, int mode) { return PGraphics.blendColor(c1, c2, mode); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
false
true
static public void runSketch(String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; boolean exclusive = false; Color backgroundColor = Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value) - 1; //DisplayMode dm = device.getDisplayMode(); //if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { present = true; } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; break; } } argIndex++; } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } Frame frame = new Frame(displayDevice.getDefaultConfiguration()); /* Frame frame = null; if (displayDevice != null) { frame = new Frame(displayDevice.getDefaultConfiguration()); } else { frame = new Frame(); } */ //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // remove the grow box by default // users who want it back can call frame.setResizable(true) // frame.setResizable(false); // moved later (issue #467) // Set the trimmings around the image Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); frame.setIconImage(image); frame.setTitle(name); final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // these are needed before init/start applet.frame = frame; applet.sketchPath = folder; applet.args = PApplet.subset(args, 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle fullScreenRect = null; // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { frame.setUndecorated(true); frame.setBackground(backgroundColor); if (exclusive) { displayDevice.setFullScreenWindow(frame); // this trashes the location of the window on os x //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); fullScreenRect = frame.getBounds(); } else { DisplayMode mode = displayDevice.getDisplayMode(); fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight()); frame.setBounds(fullScreenRect); frame.setVisible(true); } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } //println("not default size " + applet.width + " " + applet.height); //println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")"); if (present) { // After the pack(), the screen bounds are gonna be 0s frame.setBounds(fullScreenRect); applet.setBounds((fullScreenRect.width - applet.width) / 2, (fullScreenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, fullScreenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from PdeRuntime // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.screenWidth - 33) || (locationY + windowH > applet.screenHeight - 33)) { // otherwise center on screen locationX = (applet.screenWidth - windowW) / 2; locationY = (applet.screenHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen frame.setLocation((applet.screenWidth - applet.width) / 2, (applet.screenHeight - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor == Color.black) { //BLACK) { // this means no bg color unless specified backgroundColor = SystemColor.control; } frame.setBackground(backgroundColor); int usableWindowH = windowH - insets.top - insets.bottom; applet.setBounds((windowW - applet.width)/2, insets.top + (usableWindowH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } public static void main(final String[] args) { runSketch(args, null); } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core public void flush() { if (recorder != null) recorder.flush(); g.flush(); } /** * ( begin auto-generated from hint.xml ) * * Set various hints and hacks for the renderer. This is used to handle * obscure rendering features that cannot be implemented in a consistent * manner across renderers. Many options will often graduate to standard * features instead of hints over time. * <br/> <br/> * hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for P3D. This * can help force anti-aliasing if it has not been enabled by the user. On * some graphics cards, this can also be set by the graphics driver's * control panel, however not all cards make this available. This hint must * be called immediately after the size() command because it resets the * renderer, obliterating any settings and anything drawn (and like size(), * re-running the code that came before it again). * <br/> <br/> * hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always * enables 2x smoothing when the P3D renderer is used. This hint disables * the default 2x smoothing and returns the smoothing behavior found in * earlier releases, where smooth() and noSmooth() could be used to enable * and disable smoothing, though the quality was inferior. * <br/> <br/> * hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are * installed, rather than the bitmapped version from a .vlw file. This is * useful with the default (or JAVA2D) renderer setting, as it will improve * font rendering speed. This is not enabled by default, because it can be * misleading while testing because the type will look great on your * machine (because you have the font installed) but lousy on others' * machines if the identical font is unavailable. This option can only be * set per-sketch, and must be called before any use of textFont(). * <br/> <br/> * hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on * top of everything at will. When depth testing is disabled, items will be * drawn to the screen sequentially, like a painting. This hint is most * often used to draw in 3D, then draw in 2D on top of it (for instance, to * draw GUI controls in 2D on top of a 3D interface). Starting in release * 0149, this will also clear the depth buffer. Restore the default with * hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared, * any 3D drawing that happens later in draw() will ignore existing shapes * on the screen. * <br/> <br/> * hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and * lines in P3D and OPENGL. This can slow performance considerably, and the * algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT). * <br/> <br/> * hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the P3D renderer setting * by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT). * <br/> <br/> * <!--hint(ENABLE_ACCURATE_TEXTURES) - Enables better texture accuracy for * the P3D renderer. This option will do a better job of dealing with * textures in perspective. hint(DISABLE_ACCURATE_TEXTURES) returns to the * default. This hint is not likely to last long. * <br/> <br/>--> * As of release 0149, unhint() has been removed in favor of adding * additional ENABLE/DISABLE constants to reset the default behavior. This * prevents the double negatives, and also reinforces which hints can be * enabled or disabled. * * ( end auto-generated ) * @webref rendering * @param which name of the hint to be enabled or disabled * @see PGraphics * @see PApplet#createGraphics(int, int, String, String) * @see PApplet#size(int, int) */ public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } public boolean hintEnabled(int which) { return g.hintEnabled(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMALIZED, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref shape:vertex * @param mode either IMAGE or NORMALIZED * @see PGraphics#texture(PImage) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref shape:vertex * @param image the texture to apply * @see PGraphics#textureMode(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * * @param image reference to a PImage object */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** This feature is in testing, do not use or rely upon its implementation */ public void breakShape() { if (recorder != null) recorder.breakShape(); g.breakShape(); } public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse * @param d height of the ellipse * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse * @param d height of the arc's ellipse * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions, creates a cube * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } public void image(PImage image, float x, float y) { if (recorder != null) recorder.image(image, x, y); g.image(image, x, y); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param image the image to display * @param x x-coordinate of the image * @param y y-coordinate of the image * @param c width to display the image * @param d height to display the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage image, float x, float y, float c, float d) { if (recorder != null) recorder.image(image, x, y, c, d); g.image(image, x, y, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage image, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2); g.image(image, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) */ public void shape(PShape shape, float x, float y, float c, float d) { if (recorder != null) recorder.shape(shape, x, y, c, d); g.shape(shape, x, y, c, d); } public void textAlign(int align) { if (recorder != null) recorder.textAlign(align); g.textAlign(align); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float, float, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c) { if (recorder != null) recorder.text(c); g.text(c); } /** * <h3>Advanced</h3> * Draw a single character on screen. * Extremely slow when used with textMode(SCREEN) and Java 2D, * because loadPixels has to be called first and updatePixels last. * * @param x x-coordinate of text * @param y y-coordinate of text */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * @param str the alphanumeric symbols to be displayed */ public void text(String str) { if (recorder != null) recorder.text(str); g.text(str); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index to start writing characters * @param stop array index to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(String s, float x1, float y1, float x2, float y2, float z) { if (recorder != null) recorder.text(s, x1, y1, x2, y2, z); g.text(s, x1, y1, x2, y2, z); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the alphanumeric symbols to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param tx left/right translation * @param ty up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float tx, float ty) { if (recorder != null) recorder.translate(tx, ty); g.translate(tx, ty); } /** * @param tz forward/backward translation */ public void translate(float tx, float ty, float tz) { if (recorder != null) recorder.translate(tx, ty, tz); g.translate(tx, ty, tz); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param vx * @param vy * @param vz */ public void rotate(float angle, float vx, float vy, float vz) { if (recorder != null) recorder.rotate(angle, vx, vy, vz); g.rotate(angle, vx, vy, vz); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#translate(float, float, float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param sx percentage to scale the object in the x-axis * @param sy percentage to scale the objects in the y-axis */ public void scale(float sx, float sy) { if (recorder != null) recorder.scale(sx, sy); g.scale(sx, sy); } /** * @param x percentage to scale the object in the x-axis * @param y percentage to scale the objects in the y-axis * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of nearest farthest plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane * @param far far component of the clipping plane * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float x, float y, float z) { if (recorder != null) recorder.stroke(x, y, z); g.stroke(x, y, z); } public void stroke(float x, float y, float z, float alpha) { if (recorder != null) recorder.stroke(x, y, z, alpha); g.stroke(x, y, z, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param rgb color value in hexadecimal notation * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray any valid number */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void tint(float x, float y, float z) { if (recorder != null) recorder.tint(x, y, z); g.tint(x, y, z); } /** * @param z opacity of the image */ public void tint(float x, float y, float z, float a) { if (recorder != null) recorder.tint(x, y, z, a); g.tint(x, y, z, a); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } public void fill(float x, float y, float z) { if (recorder != null) recorder.fill(x, y, z); g.fill(x, y, z); } /** * @param a opacity of the fill */ public void fill(float x, float y, float z, float a) { if (recorder != null) recorder.fill(x, y, z, a); g.fill(x, y, z, a); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void ambient(float x, float y, float z) { if (recorder != null) recorder.ambient(x, y, z); g.ambient(x, y, z); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void specular(float x, float y, float z) { if (recorder != null) recorder.specular(x, y, z); g.specular(x, y, z); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void emissive(float x, float y, float z) { if (recorder != null) recorder.emissive(x, y, z); g.emissive(x, y, z); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float red, float green, float blue) { if (recorder != null) recorder.ambientLight(red, green, blue); g.ambientLight(red, green, blue); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float red, float green, float blue, float x, float y, float z) { if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z); g.ambientLight(red, green, blue, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float red, float green, float blue, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz); g.directionalLight(red, green, blue, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float red, float green, float blue, float x, float y, float z) { if (recorder != null) recorder.pointLight(red, green, blue, x, y, z); g.pointLight(red, green, blue, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float red, float green, float blue, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float x, float y, float z) { if (recorder != null) recorder.lightSpecular(x, y, z); g.lightSpecular(x, y, z); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param x red or hue value (depending on the current color mode) * @param y green or saturation value (depending on the current color mode) * @param z blue or brightness value (depending on the current color mode) */ public void background(float x, float y, float z) { if (recorder != null) recorder.background(x, y, z); g.background(x, y, z); } /** * @param a opacity of the background */ public void background(float x, float y, float z, float a) { if (recorder != null) recorder.background(x, y, z, a); g.background(x, y, z, a); } /** * @param image PImage to set as background (must be same size as the program) * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task. * <P> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000), because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Using image.filter(OPAQUE) will handle this easily. * <P> * When using 3D, this will also clear the zbuffer (if it exists). */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param maxX range for the red or hue depending on the current color mode * @param maxY range for the green or saturation depending on the current color mode * @param maxZ range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float maxX, float maxY, float maxZ) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ); g.colorMode(mode, maxX, maxY, maxZ); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float maxX, float maxY, float maxZ, float maxA) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA); g.colorMode(mode, maxX, maxY, maxZ, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int what) { return g.alpha(what); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int what) { return g.red(what); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int what) { return g.green(what); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int what) { return g.blue(what); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int what) { return g.hue(what); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int what) { return g.saturation(what); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int what) { return g.brightness(what); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } public PShape createShape() { return g.createShape(); } public PShape createShape(int type) { return g.createShape(type); } public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void delete() { if (recorder != null) recorder.delete(); g.delete(); } /** * Store data of some kind for a renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PGraphics renderer, Object storage) { if (recorder != null) recorder.setCache(renderer, storage); g.setCache(renderer, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PGraphics renderer) { return g.getCache(renderer); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PGraphics renderer) { if (recorder != null) recorder.removeCache(renderer); g.removeCache(renderer); } /** * Store parameters for a renderer that requires extra metadata of * some kind. * @param renderer The PGraphics renderer associated to the image * @param storage The parameters required by the renderer */ public void setParams(PGraphics renderer, Object params) { if (recorder != null) recorder.setParams(renderer, params); g.setParams(renderer, params); } /** * Get the parameters for the specified renderer. * @param renderer The PGraphics renderer associated to the image * @return parameters stored for the specified renderer */ public Object getParams(PGraphics renderer) { return g.getParams(renderer); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose parameters should be removed */ public void removeParams(PGraphics renderer) { if (recorder != null) recorder.removeParams(renderer); g.removeParams(renderer); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param src image to draw on screen */ public void set(int x, int y, PImage src) { if (recorder != null) recorder.set(x, y, src); g.set(x, y, src); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(int maskArray[]) { if (recorder != null) recorder.mask(maskArray); g.mask(maskArray); } /** * @param maskImg a PImage object used as the alpha channel for "img", must be same dimensions as "img" */ public void mask(PImage maskImg) { if (recorder != null) recorder.mask(maskImg); g.mask(maskImg); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } /** * ( begin auto-generated from blendColor.xml ) * * Blends two color values together based on the blending mode given as the * <b>MODE</b> parameter. The possible modes are described in the reference * for the <b>blend()</b> function. * * ( end auto-generated ) * <h3>Advanced</h3> * <UL> * <LI>REPLACE - destination colour equals colour of source pixel: C = A. * Sometimes called "Normal" or "Copy" in other software. * * <LI>BLEND - linear interpolation of colours: * <TT>C = A*factor + B</TT> * * <LI>ADD - additive blending with white clip: * <TT>C = min(A*factor + B, 255)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Burn", * and Director calls it "Add Pin". * * <LI>SUBTRACT - substractive blend with black clip: * <TT>C = max(B - A*factor, 0)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Dodge", * and Director calls it "Subtract Pin". * * <LI>DARKEST - only the darkest colour succeeds: * <TT>C = min(A*factor, B)</TT>. * Illustrator calls this "Darken". * * <LI>LIGHTEST - only the lightest colour succeeds: * <TT>C = max(A*factor, B)</TT>. * Illustrator calls this "Lighten". * * <LI>DIFFERENCE - subtract colors from underlying image. * * <LI>EXCLUSION - similar to DIFFERENCE, but less extreme. * * <LI>MULTIPLY - Multiply the colors, result will always be darker. * * <LI>SCREEN - Opposite multiply, uses inverse values of the colors. * * <LI>OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values. * * <LI>HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. * * <LI>SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh. * * <LI>DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop. * * <LI>BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop. * </UL> * <P>A useful reference for blending modes and their algorithms can be * found in the <A HREF="http://www.w3.org/TR/SVG12/rendering.html">SVG</A> * specification.</P> * <P>It is important to note that Processing uses "fast" code, not * necessarily "correct" code. No biggie, most software does. A nitpicker * can find numerous "off by 1 division" problems in the blend code where * <TT>&gt;&gt;8</TT> or <TT>&gt;&gt;7</TT> is used when strictly speaking * <TT>/255.0</T> or <TT>/127.0</TT> should have been used.</P> * <P>For instance, exclusion (not intended for real-time use) reads * <TT>r1 + r2 - ((2 * r1 * r2) / 255)</TT> because <TT>255 == 1.0</TT> * not <TT>256 == 1.0</TT>. In other words, <TT>(255*255)>>8</TT> is not * the same as <TT>(255*255)/255</TT>. But for real-time use the shifts * are preferrable, and the difference is insignificant for applications * built with Processing.</P> * * @webref color:creating_reading * @usage web_application * @param c1 the first color to blend * @param c2 the second color to blend * @param mode either BLEND, ADD, SUBTRACT, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, or BURN * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) * @see PApplet#color(float, float, float, float) */ static public int blendColor(int c1, int c2, int mode) { return PGraphics.blendColor(c1, c2, mode); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
static public void runSketch(String args[], final PApplet constructedApplet) { // Disable abyssmally slow Sun renderer on OS X 10.5. if (platform == MACOSX) { // Only run this on OS X otherwise it can cause a permissions error. // http://dev.processing.org/bugs/show_bug.cgi?id=976 System.setProperty("apple.awt.graphics.UseQuartz", String.valueOf(useQuartz)); } // This doesn't do anything. // if (platform == WINDOWS) { // // For now, disable the D3D renderer on Java 6u10 because // // it causes problems with Present mode. // // http://dev.processing.org/bugs/show_bug.cgi?id=1009 // System.setProperty("sun.java2d.d3d", "false"); // } if (args.length < 1) { System.err.println("Usage: PApplet <appletname>"); System.err.println("For additional options, " + "see the Javadoc for PApplet"); System.exit(1); } boolean external = false; int[] location = null; int[] editorLocation = null; String name = null; boolean present = false; boolean exclusive = false; Color backgroundColor = Color.BLACK; Color stopColor = Color.GRAY; GraphicsDevice displayDevice = null; boolean hideStop = false; String param = null, value = null; // try to get the user folder. if running under java web start, // this may cause a security exception if the code is not signed. // http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Integrate;action=display;num=1159386274 String folder = null; try { folder = System.getProperty("user.dir"); } catch (Exception e) { } int argIndex = 0; while (argIndex < args.length) { int equals = args[argIndex].indexOf('='); if (equals != -1) { param = args[argIndex].substring(0, equals); value = args[argIndex].substring(equals + 1); if (param.equals(ARGS_EDITOR_LOCATION)) { external = true; editorLocation = parseInt(split(value, ',')); } else if (param.equals(ARGS_DISPLAY)) { int deviceIndex = Integer.parseInt(value) - 1; //DisplayMode dm = device.getDisplayMode(); //if ((dm.getWidth() == 1024) && (dm.getHeight() == 768)) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice devices[] = environment.getScreenDevices(); if ((deviceIndex >= 0) && (deviceIndex < devices.length)) { displayDevice = devices[deviceIndex]; } else { System.err.println("Display " + value + " does not exist, " + "using the default display instead."); } } else if (param.equals(ARGS_BGCOLOR)) { if (value.charAt(0) == '#') value = value.substring(1); backgroundColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_STOP_COLOR)) { if (value.charAt(0) == '#') value = value.substring(1); stopColor = new Color(Integer.parseInt(value, 16)); } else if (param.equals(ARGS_SKETCH_FOLDER)) { folder = value; } else if (param.equals(ARGS_LOCATION)) { location = parseInt(split(value, ',')); } } else { if (args[argIndex].equals(ARGS_PRESENT)) { present = true; } else if (args[argIndex].equals(ARGS_EXCLUSIVE)) { exclusive = true; } else if (args[argIndex].equals(ARGS_HIDE_STOP)) { hideStop = true; } else if (args[argIndex].equals(ARGS_EXTERNAL)) { external = true; } else { name = args[argIndex]; break; // because of break, argIndex won't increment again } } argIndex++; } // Set this property before getting into any GUI init code //System.setProperty("com.apple.mrj.application.apple.menu.about.name", name); // This )*)(*@#$ Apple crap don't work no matter where you put it // (static method of the class, at the top of main, wherever) if (displayDevice == null) { GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment(); displayDevice = environment.getDefaultScreenDevice(); } Frame frame = new Frame(displayDevice.getDefaultConfiguration()); /* Frame frame = null; if (displayDevice != null) { frame = new Frame(displayDevice.getDefaultConfiguration()); } else { frame = new Frame(); } */ //Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); // remove the grow box by default // users who want it back can call frame.setResizable(true) // frame.setResizable(false); // moved later (issue #467) // Set the trimmings around the image Image image = Toolkit.getDefaultToolkit().createImage(ICON_IMAGE); frame.setIconImage(image); frame.setTitle(name); final PApplet applet; if (constructedApplet != null) { applet = constructedApplet; } else { try { Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(name); applet = (PApplet) c.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } // these are needed before init/start applet.frame = frame; applet.sketchPath = folder; // pass everything after the class name in as args to the sketch itself // (fixed for 2.0a5, this was just subsetting by 1, which didn't skip opts) applet.args = PApplet.subset(args, argIndex + 1); applet.external = external; // Need to save the window bounds at full screen, // because pack() will cause the bounds to go to zero. // http://dev.processing.org/bugs/show_bug.cgi?id=923 Rectangle fullScreenRect = null; // For 0149, moving this code (up to the pack() method) before init(). // For OpenGL (and perhaps other renderers in the future), a peer is // needed before a GLDrawable can be created. So pack() needs to be // called on the Frame before applet.init(), which itself calls size(), // and launches the Thread that will kick off setup(). // http://dev.processing.org/bugs/show_bug.cgi?id=891 // http://dev.processing.org/bugs/show_bug.cgi?id=908 if (present) { frame.setUndecorated(true); frame.setBackground(backgroundColor); if (exclusive) { displayDevice.setFullScreenWindow(frame); // this trashes the location of the window on os x //frame.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH); fullScreenRect = frame.getBounds(); } else { DisplayMode mode = displayDevice.getDisplayMode(); fullScreenRect = new Rectangle(0, 0, mode.getWidth(), mode.getHeight()); frame.setBounds(fullScreenRect); frame.setVisible(true); } } frame.setLayout(null); frame.add(applet); if (present) { frame.invalidate(); } else { frame.pack(); } // insufficient, places the 100x100 sketches offset strangely //frame.validate(); // disabling resize has to happen after pack() to avoid apparent Apple bug // http://code.google.com/p/processing/issues/detail?id=467 frame.setResizable(false); applet.init(); // Wait until the applet has figured out its width. // In a static mode app, this will be after setup() has completed, // and the empty draw() has set "finished" to true. // TODO make sure this won't hang if the applet has an exception. while (applet.defaultSize && !applet.finished) { //System.out.println("default size"); try { Thread.sleep(5); } catch (InterruptedException e) { //System.out.println("interrupt"); } } //println("not default size " + applet.width + " " + applet.height); //println(" (g width/height is " + applet.g.width + "x" + applet.g.height + ")"); if (present) { // After the pack(), the screen bounds are gonna be 0s frame.setBounds(fullScreenRect); applet.setBounds((fullScreenRect.width - applet.width) / 2, (fullScreenRect.height - applet.height) / 2, applet.width, applet.height); if (!hideStop) { Label label = new Label("stop"); label.setForeground(stopColor); label.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { System.exit(0); } }); frame.add(label); Dimension labelSize = label.getPreferredSize(); // sometimes shows up truncated on mac //System.out.println("label width is " + labelSize.width); labelSize = new Dimension(100, labelSize.height); label.setSize(labelSize); label.setLocation(20, fullScreenRect.height - labelSize.height - 20); } // not always running externally when in present mode if (external) { applet.setupExternalMessages(); } } else { // if not presenting // can't do pack earlier cuz present mode don't like it // (can't go full screen with a frame after calling pack) // frame.pack(); // get insets. get more. Insets insets = frame.getInsets(); int windowW = Math.max(applet.width, MIN_WINDOW_WIDTH) + insets.left + insets.right; int windowH = Math.max(applet.height, MIN_WINDOW_HEIGHT) + insets.top + insets.bottom; frame.setSize(windowW, windowH); if (location != null) { // a specific location was received from PdeRuntime // (applet has been run more than once, user placed window) frame.setLocation(location[0], location[1]); } else if (external) { int locationX = editorLocation[0] - 20; int locationY = editorLocation[1]; if (locationX - windowW > 10) { // if it fits to the left of the window frame.setLocation(locationX - windowW, locationY); } else { // doesn't fit // if it fits inside the editor window, // offset slightly from upper lefthand corner // so that it's plunked inside the text area locationX = editorLocation[0] + 66; locationY = editorLocation[1] + 66; if ((locationX + windowW > applet.screenWidth - 33) || (locationY + windowH > applet.screenHeight - 33)) { // otherwise center on screen locationX = (applet.screenWidth - windowW) / 2; locationY = (applet.screenHeight - windowH) / 2; } frame.setLocation(locationX, locationY); } } else { // just center on screen frame.setLocation((applet.screenWidth - applet.width) / 2, (applet.screenHeight - applet.height) / 2); } Point frameLoc = frame.getLocation(); if (frameLoc.y < 0) { // Windows actually allows you to place frames where they can't be // closed. Awesome. http://dev.processing.org/bugs/show_bug.cgi?id=1508 frame.setLocation(frameLoc.x, 30); } if (backgroundColor == Color.black) { //BLACK) { // this means no bg color unless specified backgroundColor = SystemColor.control; } frame.setBackground(backgroundColor); int usableWindowH = windowH - insets.top - insets.bottom; applet.setBounds((windowW - applet.width)/2, insets.top + (usableWindowH - applet.height)/2, applet.width, applet.height); if (external) { applet.setupExternalMessages(); } else { // !external frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } // handle frame resizing events applet.setupFrameResizeListener(); // all set for rockin if (applet.displayable()) { frame.setVisible(true); } } // Disabling for 0185, because it causes an assertion failure on OS X // http://code.google.com/p/processing/issues/detail?id=258 // (Although this doesn't seem to be the one that was causing problems.) //applet.requestFocus(); // ask for keydowns } public static void main(final String[] args) { runSketch(args, null); } /** * These methods provide a means for running an already-constructed * sketch. In particular, it makes it easy to launch a sketch in * Jython: * * <pre>class MySketch(PApplet): * pass * *MySketch().runSketch();</pre> */ protected void runSketch(final String[] args) { final String[] argsWithSketchName = new String[args.length + 1]; System.arraycopy(args, 0, argsWithSketchName, 0, args.length); final String className = this.getClass().getSimpleName(); final String cleanedClass = className.replaceAll("__[^_]+__\\$", "").replaceAll("\\$\\d+", ""); argsWithSketchName[args.length] = cleanedClass; runSketch(argsWithSketchName, this); } protected void runSketch() { runSketch(new String[0]); } ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from beginRecord.xml ) * * Opens a new file and all subsequent drawing functions are echoed to this * file as well as the display window. The <b>beginRecord()</b> function * requires two parameters, the first is the renderer and the second is the * file name. This function is always used with <b>endRecord()</b> to stop * the recording process and close the file. * <br /> <br /> * Note that beginRecord() will only pick up any settings that happen after * it has been called. For instance, if you call textFont() before * beginRecord(), then that font will not be set for the file that you're * recording to. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF * @param filename filename for output * @see PApplet#endRecord() */ public PGraphics beginRecord(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); beginRecord(rec); return rec; } /** * @nowebref * Begin recording (echoing) commands to the specified PGraphics object. */ public void beginRecord(PGraphics recorder) { this.recorder = recorder; recorder.beginDraw(); } /** * ( begin auto-generated from endRecord.xml ) * * Stops the recording process started by <b>beginRecord()</b> and closes * the file. * * ( end auto-generated ) * @webref output:files * @see PApplet#beginRecord(String, String) */ public void endRecord() { if (recorder != null) { recorder.endDraw(); recorder.dispose(); recorder = null; } } /** * ( begin auto-generated from beginRaw.xml ) * * To create vectors from 3D data, use the <b>beginRaw()</b> and * <b>endRaw()</b> commands. These commands will grab the shape data just * before it is rendered to the screen. At this stage, your entire scene is * nothing but a long list of individual lines and triangles. This means * that a shape created with <b>sphere()</b> function will be made up of * hundreds of triangles, rather than a single object. Or that a * multi-segment line shape (such as a curve) will be rendered as * individual segments. * <br /><br /> * When using <b>beginRaw()</b> and <b>endRaw()</b>, it's possible to write * to either a 2D or 3D renderer. For instance, <b>beginRaw()</b> with the * PDF library will write the geometry as flattened triangles and lines, * even if recording from the <b>P3D</b> renderer. * <br /><br /> * If you want a background to show up in your files, use <b>rect(0, 0, * width, height)</b> after setting the <b>fill()</b> to the background * color. Otherwise the background will not be rendered to the file because * the background is not shape. * <br /><br /> * Using <b>hint(ENABLE_DEPTH_SORT)</b> can improve the appearance of 3D * geometry drawn to 2D file formats. See the <b>hint()</b> reference for * more details. * <br /><br /> * See examples in the reference for the <b>PDF</b> and <b>DXF</b> * libraries for more information. * * ( end auto-generated ) * * @webref output:files * @param renderer for example, PDF or DXF * @param filename filename for output * @see PApplet#endRaw() * @see PApplet#hint(int) */ public PGraphics beginRaw(String renderer, String filename) { filename = insertFrame(filename); PGraphics rec = createGraphics(width, height, renderer, filename); g.beginRaw(rec); return rec; } /** * @nowebref * Begin recording raw shape data to the specified renderer. * * This simply echoes to g.beginRaw(), but since is placed here (rather than * generated by preproc.pl) for clarity and so that it doesn't echo the * command should beginRecord() be in use. * * @param rawGraphics ??? */ public void beginRaw(PGraphics rawGraphics) { g.beginRaw(rawGraphics); } /** * ( begin auto-generated from endRaw.xml ) * * Complement to <b>beginRaw()</b>; they must always be used together. See * the <b>beginRaw()</b> reference for details. * * ( end auto-generated ) * * @webref output:files * @see PApplet#beginRaw(String, String) */ public void endRaw() { g.endRaw(); } /** * Starts shape recording and returns the PShape object that will * contain the geometry. */ /* public PShape beginRecord() { return g.beginRecord(); } */ ////////////////////////////////////////////////////////////// /** * ( begin auto-generated from loadPixels.xml ) * * Loads the pixel data for the display window into the <b>pixels[]</b> * array. This function must always be called before reading from or * writing to <b>pixels[]</b>. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * * ( end auto-generated ) * <h3>Advanced</h3> * Override the g.pixels[] function to set the pixels[] array * that's part of the PApplet object. Allows the use of * pixels[] in the code, rather than g.pixels[]. * * @webref image:pixels * @see PApplet#pixels * @see PApplet#updatePixels() */ public void loadPixels() { g.loadPixels(); pixels = g.pixels; } /** * ( begin auto-generated from updatePixels.xml ) * * Updates the display window with the data in the <b>pixels[]</b> array. * Use in conjunction with <b>loadPixels()</b>. If you're only reading * pixels from the array, there's no need to call <b>updatePixels()</b> * unless there are changes. * <br/><br/> renderers may or may not seem to require <b>loadPixels()</b> * or <b>updatePixels()</b>. However, the rule is that any time you want to * manipulate the <b>pixels[]</b> array, you must first call * <b>loadPixels()</b>, and after changes have been made, call * <b>updatePixels()</b>. Even if the renderer may not seem to use this * function in the current Processing release, this will always be subject * to change. * <br/> <br/> * Currently, none of the renderers use the additional parameters to * <b>updatePixels()</b>, however this may be implemented in the future. * * ( end auto-generated ) * @webref image:pixels * @see PApplet#loadPixels() * @see PApplet#pixels */ public void updatePixels() { g.updatePixels(); } /** * @nowebref * @param x1 x-coordinate of the upper-left corner * @param y1 y-coordinate of the upper-left corner * @param x2 width of the region * @param y2 height of the region */ public void updatePixels(int x1, int y1, int x2, int y2) { g.updatePixels(x1, y1, x2, y2); } ////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS LINE IS AUTOMATICALLY GENERATED. DO NOT TOUCH! // This includes the Javadoc comments, which are automatically copied from // the PImage and PGraphics source code files. // public functions for processing.core public void flush() { if (recorder != null) recorder.flush(); g.flush(); } /** * ( begin auto-generated from hint.xml ) * * Set various hints and hacks for the renderer. This is used to handle * obscure rendering features that cannot be implemented in a consistent * manner across renderers. Many options will often graduate to standard * features instead of hints over time. * <br/> <br/> * hint(ENABLE_OPENGL_4X_SMOOTH) - Enable 4x anti-aliasing for P3D. This * can help force anti-aliasing if it has not been enabled by the user. On * some graphics cards, this can also be set by the graphics driver's * control panel, however not all cards make this available. This hint must * be called immediately after the size() command because it resets the * renderer, obliterating any settings and anything drawn (and like size(), * re-running the code that came before it again). * <br/> <br/> * hint(DISABLE_OPENGL_2X_SMOOTH) - In Processing 1.0, Processing always * enables 2x smoothing when the P3D renderer is used. This hint disables * the default 2x smoothing and returns the smoothing behavior found in * earlier releases, where smooth() and noSmooth() could be used to enable * and disable smoothing, though the quality was inferior. * <br/> <br/> * hint(ENABLE_NATIVE_FONTS) - Use the native version fonts when they are * installed, rather than the bitmapped version from a .vlw file. This is * useful with the default (or JAVA2D) renderer setting, as it will improve * font rendering speed. This is not enabled by default, because it can be * misleading while testing because the type will look great on your * machine (because you have the font installed) but lousy on others' * machines if the identical font is unavailable. This option can only be * set per-sketch, and must be called before any use of textFont(). * <br/> <br/> * hint(DISABLE_DEPTH_TEST) - Disable the zbuffer, allowing you to draw on * top of everything at will. When depth testing is disabled, items will be * drawn to the screen sequentially, like a painting. This hint is most * often used to draw in 3D, then draw in 2D on top of it (for instance, to * draw GUI controls in 2D on top of a 3D interface). Starting in release * 0149, this will also clear the depth buffer. Restore the default with * hint(ENABLE_DEPTH_TEST), but note that with the depth buffer cleared, * any 3D drawing that happens later in draw() will ignore existing shapes * on the screen. * <br/> <br/> * hint(ENABLE_DEPTH_SORT) - Enable primitive z-sorting of triangles and * lines in P3D and OPENGL. This can slow performance considerably, and the * algorithm is not yet perfect. Restore the default with hint(DISABLE_DEPTH_SORT). * <br/> <br/> * hint(DISABLE_OPENGL_ERROR_REPORT) - Speeds up the P3D renderer setting * by not checking for errors while running. Undo with hint(ENABLE_OPENGL_ERROR_REPORT). * <br/> <br/> * <!--hint(ENABLE_ACCURATE_TEXTURES) - Enables better texture accuracy for * the P3D renderer. This option will do a better job of dealing with * textures in perspective. hint(DISABLE_ACCURATE_TEXTURES) returns to the * default. This hint is not likely to last long. * <br/> <br/>--> * As of release 0149, unhint() has been removed in favor of adding * additional ENABLE/DISABLE constants to reset the default behavior. This * prevents the double negatives, and also reinforces which hints can be * enabled or disabled. * * ( end auto-generated ) * @webref rendering * @param which name of the hint to be enabled or disabled * @see PGraphics * @see PApplet#createGraphics(int, int, String, String) * @see PApplet#size(int, int) */ public void hint(int which) { if (recorder != null) recorder.hint(which); g.hint(which); } public boolean hintEnabled(int which) { return g.hintEnabled(which); } /** * Start a new shape of type POLYGON */ public void beginShape() { if (recorder != null) recorder.beginShape(); g.beginShape(); } /** * ( begin auto-generated from beginShape.xml ) * * Using the <b>beginShape()</b> and <b>endShape()</b> functions allow * creating more complex forms. <b>beginShape()</b> begins recording * vertices for a shape and <b>endShape()</b> stops recording. The value of * the <b>MODE</b> parameter tells it which types of shapes to create from * the provided vertices. With no mode specified, the shape can be any * irregular polygon. The parameters available for beginShape() are POINTS, * LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, and QUAD_STRIP. * After calling the <b>beginShape()</b> function, a series of * <b>vertex()</b> commands must follow. To stop drawing the shape, call * <b>endShape()</b>. The <b>vertex()</b> function with two parameters * specifies a position in 2D and the <b>vertex()</b> function with three * parameters specifies a position in 3D. Each shape will be outlined with * the current stroke color and filled with the fill color. * <br/> <br/> * Transformations such as <b>translate()</b>, <b>rotate()</b>, and * <b>scale()</b> do not work within <b>beginShape()</b>. It is also not * possible to use other shapes, such as <b>ellipse()</b> or <b>rect()</b> * within <b>beginShape()</b>. * <br/> <br/> * The P3D renderer settings allow <b>stroke()</b> and <b>fill()</b> * settings to be altered per-vertex, however the default P2D renderer does * not. Settings such as <b>strokeWeight()</b>, <b>strokeCap()</b>, and * <b>strokeJoin()</b> cannot be changed while inside a * <b>beginShape()</b>/<b>endShape()</b> block with any renderer. * * ( end auto-generated ) * @webref shape:vertex * @param kind either POINTS, LINES, TRIANGLES, TRIANGLE_FAN, TRIANGLE_STRIP, QUADS, QUAD_STRIP * @see PGraphics#endShape() * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) */ public void beginShape(int kind) { if (recorder != null) recorder.beginShape(kind); g.beginShape(kind); } /** * Sets whether the upcoming vertex is part of an edge. * Equivalent to glEdgeFlag(), for people familiar with OpenGL. */ public void edge(boolean edge) { if (recorder != null) recorder.edge(edge); g.edge(edge); } /** * ( begin auto-generated from normal.xml ) * * Sets the current normal vector. This is for drawing three dimensional * shapes and surfaces and specifies a vector perpendicular to the surface * of the shape which determines how lighting affects it. Processing * attempts to automatically assign normals to shapes, but since that's * imperfect, this is a better option when you want more control. This * function is identical to glNormal3f() in OpenGL. * * ( end auto-generated ) * @webref lights_camera:lights * @param nx x direction * @param ny y direction * @param nz z direction * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#lights() */ public void normal(float nx, float ny, float nz) { if (recorder != null) recorder.normal(nx, ny, nz); g.normal(nx, ny, nz); } /** * ( begin auto-generated from textureMode.xml ) * * Sets the coordinate space for texture mapping. There are two options, * IMAGE, which refers to the actual coordinates of the image, and * NORMALIZED, which refers to a normalized space of values ranging from 0 * to 1. The default mode is IMAGE. In IMAGE, if an image is 100 x 200 * pixels, mapping the image onto the entire size of a quad would require * the points (0,0) (0,100) (100,200) (0,200). The same mapping in * NORMAL_SPACE is (0,0) (0,1) (1,1) (0,1). * * ( end auto-generated ) * @webref shape:vertex * @param mode either IMAGE or NORMALIZED * @see PGraphics#texture(PImage) */ public void textureMode(int mode) { if (recorder != null) recorder.textureMode(mode); g.textureMode(mode); } /** * ( begin auto-generated from texture.xml ) * * Sets a texture to be applied to vertex points. The <b>texture()</b> * function must be called between <b>beginShape()</b> and * <b>endShape()</b> and before any calls to <b>vertex()</b>. * <br/> <br/> * When textures are in use, the fill color is ignored. Instead, use tint() * to specify the color of the texture as it is applied to the shape. * * ( end auto-generated ) * @webref shape:vertex * @param image the texture to apply * @see PGraphics#textureMode(int) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * * @param image reference to a PImage object */ public void texture(PImage image) { if (recorder != null) recorder.texture(image); g.texture(image); } /** * Removes texture image for current shape. * Needs to be called between beginShape and endShape * */ public void noTexture() { if (recorder != null) recorder.noTexture(); g.noTexture(); } public void vertex(float x, float y) { if (recorder != null) recorder.vertex(x, y); g.vertex(x, y); } public void vertex(float x, float y, float z) { if (recorder != null) recorder.vertex(x, y, z); g.vertex(x, y, z); } /** * Used by renderer subclasses or PShape to efficiently pass in already * formatted vertex information. * @param v vertex parameters, as a float array of length VERTEX_FIELD_COUNT */ public void vertex(float[] v) { if (recorder != null) recorder.vertex(v); g.vertex(v); } public void vertex(float x, float y, float u, float v) { if (recorder != null) recorder.vertex(x, y, u, v); g.vertex(x, y, u, v); } /** * ( begin auto-generated from vertex.xml ) * * All shapes are constructed by connecting a series of vertices. * <b>vertex()</b> is used to specify the vertex coordinates for points, * lines, triangles, quads, and polygons and is used exclusively within the * <b>beginShape()</b> and <b>endShape()</b> function.<br /> * <br /> * Drawing a vertex in 3D using the <b>z</b> parameter requires the P3D * parameter in combination with size as shown in the above example.<br /> * <br /> * This function is also used to map a texture onto the geometry. The * <b>texture()</b> function declares the texture to apply to the geometry * and the <b>u</b> and <b>v</b> coordinates set define the mapping of this * texture to the form. By default, the coordinates used for <b>u</b> and * <b>v</b> are specified in relation to the image's size in pixels, but * this relation can be changed with <b>textureMode()</b>. * * ( end auto-generated ) * @webref shape:vertex * @param x x-coordinate of the vertex * @param y y-coordinate of the vertex * @param z z-coordinate of the vertex * @param u horizontal coordinate for the texture mapping * @param v vertical coordinate for the texture mapping * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#bezierVertex(float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#texture(PImage) */ public void vertex(float x, float y, float z, float u, float v) { if (recorder != null) recorder.vertex(x, y, z, u, v); g.vertex(x, y, z, u, v); } /** This feature is in testing, do not use or rely upon its implementation */ public void breakShape() { if (recorder != null) recorder.breakShape(); g.breakShape(); } public void beginContour() { if (recorder != null) recorder.beginContour(); g.beginContour(); } public void endContour() { if (recorder != null) recorder.endContour(); g.endContour(); } public void endShape() { if (recorder != null) recorder.endShape(); g.endShape(); } /** * ( begin auto-generated from endShape.xml ) * * The <b>endShape()</b> function is the companion to <b>beginShape()</b> * and may only be called after <b>beginShape()</b>. When <b>endshape()</b> * is called, all of image data defined since the previous call to * <b>beginShape()</b> is written into the image buffer. The constant CLOSE * as the value for the MODE parameter to close the shape (to connect the * beginning and the end). * * ( end auto-generated ) * @webref shape:vertex * @param mode use CLOSE to close the shape * @see PGraphics#beginShape(int) */ public void endShape(int mode) { if (recorder != null) recorder.endShape(mode); g.endShape(mode); } public void clip(float a, float b, float c, float d) { if (recorder != null) recorder.clip(a, b, c, d); g.clip(a, b, c, d); } public void noClip() { if (recorder != null) recorder.noClip(); g.noClip(); } public void bezierVertex(float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezierVertex(x2, y2, x3, y3, x4, y4); g.bezierVertex(x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezierVertex.xml ) * * Specifies vertex coordinates for Bezier curves. Each call to * <b>bezierVertex()</b> defines the position of two control points and one * anchor point of a Bezier curve, adding a new segment to a line or shape. * The first time <b>bezierVertex()</b> is used within a * <b>beginShape()</b> call, it must be prefaced with a call to * <b>vertex()</b> to set the first anchor point. This function must be * used between <b>beginShape()</b> and <b>endShape()</b> and only when * there is no MODE parameter specified to <b>beginShape()</b>. Using the * 3D version requires rendering with P3D (see the Environment reference * for more information). * * ( end auto-generated ) * @webref shape:vertex * @param x2 the x-coordinate of the 1st control point * @param y2 the y-coordinate of the 1st control point * @param z2 the z-coordinate of the 1st control point * @param x3 the x-coordinate of the 2nd control point * @param y3 the y-coordinate of the 2nd control point * @param z3 the z-coordinate of the 2nd control point * @param x4 the x-coordinate of the anchor point * @param y4 the y-coordinate of the anchor point * @param z4 the z-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezierVertex(float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezierVertex(x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * @webref shape:vertex * @param cx the x-coordinate of the control point * @param cy the y-coordinate of the control point * @param x3 the x-coordinate of the anchor point * @param y3 the y-coordinate of the anchor point * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void quadraticVertex(float cx, float cy, float x3, float y3) { if (recorder != null) recorder.quadraticVertex(cx, cy, x3, y3); g.quadraticVertex(cx, cy, x3, y3); } /** * @param cz the z-coordinate of the control point * @param z3 the z-coordinate of the anchor point */ public void quadraticVertex(float cx, float cy, float cz, float x3, float y3, float z3) { if (recorder != null) recorder.quadraticVertex(cx, cy, cz, x3, y3, z3); g.quadraticVertex(cx, cy, cz, x3, y3, z3); } /** * ( begin auto-generated from curveVertex.xml ) * * Specifies vertex coordinates for curves. This function may only be used * between <b>beginShape()</b> and <b>endShape()</b> and only when there is * no MODE parameter specified to <b>beginShape()</b>. The first and last * points in a series of <b>curveVertex()</b> lines will be used to guide * the beginning and end of a the curve. A minimum of four points is * required to draw a tiny curve between the second and third points. * Adding a fifth point with <b>curveVertex()</b> will draw the curve * between the second, third, and fourth points. The <b>curveVertex()</b> * function is an implementation of Catmull-Rom splines. Using the 3D * version requires rendering with P3D (see the Environment reference for * more information). * * ( end auto-generated ) * * @webref shape:vertex * @param x the x-coordinate of the vertex * @param y the y-coordinate of the vertex * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#beginShape(int) * @see PGraphics#endShape(int) * @see PGraphics#vertex(float, float, float, float, float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#quadraticVertex(float, float, float, float, float, float) */ public void curveVertex(float x, float y) { if (recorder != null) recorder.curveVertex(x, y); g.curveVertex(x, y); } /** * @param z the z-coordinate of the vertex */ public void curveVertex(float x, float y, float z) { if (recorder != null) recorder.curveVertex(x, y, z); g.curveVertex(x, y, z); } /** * ( begin auto-generated from point.xml ) * * Draws a point, a coordinate in space at the dimension of one pixel. The * first parameter is the horizontal value for the point, the second value * is the vertical value for the point, and the optional third value is the * depth value. Drawing this shape in 3D with the <b>z</b> parameter * requires the P3D parameter in combination with <b>size()</b> as shown in * the above example. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param x x-coordinate of the point * @param y y-coordinate of the point */ public void point(float x, float y) { if (recorder != null) recorder.point(x, y); g.point(x, y); } /** * @param z z-coordinate of the point */ public void point(float x, float y, float z) { if (recorder != null) recorder.point(x, y, z); g.point(x, y, z); } /** * ( begin auto-generated from line.xml ) * * Draws a line (a direct path between two points) to the screen. The * version of <b>line()</b> with four parameters draws the line in 2D. To * color a line, use the <b>stroke()</b> function. A line cannot be filled, * therefore the <b>fill()</b> function will not affect the color of a * line. 2D lines are drawn with a width of one pixel by default, but this * can be changed with the <b>strokeWeight()</b> function. The version with * six parameters allows the line to be placed anywhere within XYZ space. * Drawing this shape in 3D with the <b>z</b> parameter requires the P3D * parameter in combination with <b>size()</b> as shown in the above example. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) * @see PGraphics#beginShape() */ public void line(float x1, float y1, float x2, float y2) { if (recorder != null) recorder.line(x1, y1, x2, y2); g.line(x1, y1, x2, y2); } /** * @param z1 z-coordinate of the first point * @param z2 z-coordinate of the second point */ public void line(float x1, float y1, float z1, float x2, float y2, float z2) { if (recorder != null) recorder.line(x1, y1, z1, x2, y2, z2); g.line(x1, y1, z1, x2, y2, z2); } /** * ( begin auto-generated from triangle.xml ) * * A triangle is a plane created by connecting three points. The first two * arguments specify the first point, the middle two arguments specify the * second point, and the last two arguments specify the third point. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first point * @param y1 y-coordinate of the first point * @param x2 x-coordinate of the second point * @param y2 y-coordinate of the second point * @param x3 x-coordinate of the third point * @param y3 y-coordinate of the third point * @see PApplet#beginShape() */ public void triangle(float x1, float y1, float x2, float y2, float x3, float y3) { if (recorder != null) recorder.triangle(x1, y1, x2, y2, x3, y3); g.triangle(x1, y1, x2, y2, x3, y3); } /** * ( begin auto-generated from quad.xml ) * * A quad is a quadrilateral, a four sided polygon. It is similar to a * rectangle, but the angles between its edges are not constrained to * ninety degrees. The first pair of parameters (x1,y1) sets the first * vertex and the subsequent pairs should proceed clockwise or * counter-clockwise around the defined shape. * * ( end auto-generated ) * @webref shape:2d_primitives * @param x1 x-coordinate of the first corner * @param y1 y-coordinate of the first corner * @param x2 x-coordinate of the second corner * @param y2 y-coordinate of the second corner * @param x3 x-coordinate of the third corner * @param y3 y-coordinate of the third corner * @param x4 x-coordinate of the fourth corner * @param y4 y-coordinate of the fourth corner */ public void quad(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.quad(x1, y1, x2, y2, x3, y3, x4, y4); g.quad(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from rectMode.xml ) * * Modifies the location from which rectangles draw. The default mode is * <b>rectMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>rect()</b> to specify the width and height. The syntax * <b>rectMode(CORNERS)</b> uses the first and second parameters of * <b>rect()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>rectMode(CENTER)</b> draws the image from its center point and uses * the third and forth parameters of <b>rect()</b> to specify the image's * width and height. The syntax <b>rectMode(RADIUS)</b> draws the image * from its center point and uses the third and forth parameters of * <b>rect()</b> to specify half of the image's width and height. The * parameter must be written in ALL CAPS because Processing is a case * sensitive language. Note: In version 125, the mode named CENTER_RADIUS * was shortened to RADIUS. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CORNER, CORNERS, CENTER, or RADIUS * @see PGraphics#rect(float, float, float, float) */ public void rectMode(int mode) { if (recorder != null) recorder.rectMode(mode); g.rectMode(mode); } /** * ( begin auto-generated from rect.xml ) * * Draws a rectangle to the screen. A rectangle is a four-sided shape with * every angle at ninety degrees. By default, the first two parameters set * the location of the upper-left corner, the third sets the width, and the * fourth sets the height. These parameters may be changed with the * <b>rectMode()</b> function. * * ( end auto-generated ) * * @webref shape:2d_primitives * @param a x-coordinate of the rectangle by default * @param b y-coordinate of the rectangle by default * @param c width of the rectangle by default * @param d height of the rectangle by default * @see PGraphics#rectMode(int) * @see PGraphics#quad(float, float, float, float, float, float, float, float) */ public void rect(float a, float b, float c, float d) { if (recorder != null) recorder.rect(a, b, c, d); g.rect(a, b, c, d); } /** * @param r radii for all four corners */ public void rect(float a, float b, float c, float d, float r) { if (recorder != null) recorder.rect(a, b, c, d, r); g.rect(a, b, c, d, r); } /** * @param tl radius for top-left corner * @param tr radius for top-right corner * @param br radius for bottom-right corner * @param bl radius for bottom-left corner */ public void rect(float a, float b, float c, float d, float tl, float tr, float br, float bl) { if (recorder != null) recorder.rect(a, b, c, d, tl, tr, br, bl); g.rect(a, b, c, d, tl, tr, br, bl); } /** * ( begin auto-generated from ellipseMode.xml ) * * The origin of the ellipse is modified by the <b>ellipseMode()</b> * function. The default configuration is <b>ellipseMode(CENTER)</b>, which * specifies the location of the ellipse as the center of the shape. The * <b>RADIUS</b> mode is the same, but the width and height parameters to * <b>ellipse()</b> specify the radius of the ellipse, rather than the * diameter. The <b>CORNER</b> mode draws the shape from the upper-left * corner of its bounding box. The <b>CORNERS</b> mode uses the four * parameters to <b>ellipse()</b> to set two opposing corners of the * ellipse's bounding box. The parameter must be written in ALL CAPS * because Processing is a case-sensitive language. * * ( end auto-generated ) * @webref shape:attributes * @param mode either CENTER, RADIUS, CORNER, or CORNERS * @see PApplet#ellipse(float, float, float, float) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipseMode(int mode) { if (recorder != null) recorder.ellipseMode(mode); g.ellipseMode(mode); } /** * ( begin auto-generated from ellipse.xml ) * * Draws an ellipse (oval) in the display window. An ellipse with an equal * <b>width</b> and <b>height</b> is a circle. The first two parameters set * the location, the third sets the width, and the fourth sets the height. * The origin may be changed with the <b>ellipseMode()</b> function. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the ellipse * @param b y-coordinate of the ellipse * @param c width of the ellipse * @param d height of the ellipse * @see PApplet#ellipseMode(int) * @see PApplet#arc(float, float, float, float, float, float) */ public void ellipse(float a, float b, float c, float d) { if (recorder != null) recorder.ellipse(a, b, c, d); g.ellipse(a, b, c, d); } /** * ( begin auto-generated from arc.xml ) * * Draws an arc in the display window. Arcs are drawn along the outer edge * of an ellipse defined by the <b>x</b>, <b>y</b>, <b>width</b> and * <b>height</b> parameters. The origin or the arc's ellipse may be changed * with the <b>ellipseMode()</b> function. The <b>start</b> and <b>stop</b> * parameters specify the angles at which to draw the arc. * * ( end auto-generated ) * @webref shape:2d_primitives * @param a x-coordinate of the arc's ellipse * @param b y-coordinate of the arc's ellipse * @param c width of the arc's ellipse * @param d height of the arc's ellipse * @param start angle to start the arc, specified in radians * @param stop angle to stop the arc, specified in radians * @see PApplet#ellipse(float, float, float, float) * @see PApplet#ellipseMode(int) */ public void arc(float a, float b, float c, float d, float start, float stop) { if (recorder != null) recorder.arc(a, b, c, d, start, stop); g.arc(a, b, c, d, start, stop); } /** * ( begin auto-generated from box.xml ) * * A box is an extruded rectangle. A box with equal dimension on all sides * is a cube. * * ( end auto-generated ) * * @webref shape:3d_primitives * @param size dimension of the box in all dimensions, creates a cube * @see PGraphics#sphere(float) */ public void box(float size) { if (recorder != null) recorder.box(size); g.box(size); } /** * @param w dimension of the box in the x-dimension * @param h dimension of the box in the y-dimension * @param d dimension of the box in the z-dimension */ public void box(float w, float h, float d) { if (recorder != null) recorder.box(w, h, d); g.box(w, h, d); } /** * ( begin auto-generated from sphereDetail.xml ) * * Controls the detail used to render a sphere by adjusting the number of * vertices of the sphere mesh. The default resolution is 30, which creates * a fairly detailed sphere definition with vertices every 360/30 = 12 * degrees. If you're going to render a great number of spheres per frame, * it is advised to reduce the level of detail using this function. The * setting stays active until <b>sphereDetail()</b> is called again with a * new parameter and so should <i>not</i> be called prior to every * <b>sphere()</b> statement, unless you wish to render spheres with * different settings, e.g. using less detail for smaller spheres or ones * further away from the camera. To control the detail of the horizontal * and vertical resolution independently, use the version of the functions * with two parameters. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code for sphereDetail() submitted by toxi [031031]. * Code for enhanced u/v version from davbol [080801]. * * @param res number of segments (minimum 3) used per full circle revolution * @webref shape:3d_primitives * @see PGraphics#sphere(float) */ public void sphereDetail(int res) { if (recorder != null) recorder.sphereDetail(res); g.sphereDetail(res); } /** * @param ures number of segments used longitudinally per full circle revolutoin * @param vres number of segments used latitudinally from top to bottom */ public void sphereDetail(int ures, int vres) { if (recorder != null) recorder.sphereDetail(ures, vres); g.sphereDetail(ures, vres); } /** * ( begin auto-generated from sphere.xml ) * * A sphere is a hollow ball made from tessellated triangles. * * ( end auto-generated ) * * <h3>Advanced</h3> * <P> * Implementation notes: * <P> * cache all the points of the sphere in a static array * top and bottom are just a bunch of triangles that land * in the center point * <P> * sphere is a series of concentric circles who radii vary * along the shape, based on, er.. cos or something * <PRE> * [toxi 031031] new sphere code. removed all multiplies with * radius, as scale() will take care of that anyway * * [toxi 031223] updated sphere code (removed modulos) * and introduced sphereAt(x,y,z,r) * to avoid additional translate()'s on the user/sketch side * * [davbol 080801] now using separate sphereDetailU/V * </PRE> * * @webref shape:3d_primitives * @param r the radius of the sphere * @see PGraphics#sphereDetail(int) */ public void sphere(float r) { if (recorder != null) recorder.sphere(r); g.sphere(r); } /** * ( begin auto-generated from bezierPoint.xml ) * * Evaluates the Bezier at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a bezier curve * at t. * * ( end auto-generated ) * * <h3>Advanced</h3> * For instance, to convert the following example:<PRE> * stroke(255, 102, 0); * line(85, 20, 10, 10); * line(90, 90, 15, 80); * stroke(0, 0, 0); * bezier(85, 20, 10, 10, 90, 90, 15, 80); * * // draw it in gray, using 10 steps instead of the default 20 * // this is a slower way to do it, but useful if you need * // to do things with the coordinates at each step * stroke(128); * beginShape(LINE_STRIP); * for (int i = 0; i <= 10; i++) { * float t = i / 10.0f; * float x = bezierPoint(85, 10, 90, 15, t); * float y = bezierPoint(20, 10, 90, 80, t); * vertex(x, y); * } * endShape();</PRE> * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierPoint(float a, float b, float c, float d, float t) { return g.bezierPoint(a, b, c, d, t); } /** * ( begin auto-generated from bezierTangent.xml ) * * Calculates the tangent of a point on a Bezier curve. There is a good * definition of <a href="http://en.wikipedia.org/wiki/Tangent" * target="new"><em>tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code submitted by Dave Bollinger (davol) for release 0136. * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curvePoint(float, float, float, float, float) */ public float bezierTangent(float a, float b, float c, float d, float t) { return g.bezierTangent(a, b, c, d, t); } /** * ( begin auto-generated from bezierDetail.xml ) * * Sets the resolution at which Beziers display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float, float) * @see PGraphics#curveTightness(float) */ public void bezierDetail(int detail) { if (recorder != null) recorder.bezierDetail(detail); g.bezierDetail(detail); } public void bezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.bezier(x1, y1, x2, y2, x3, y3, x4, y4); g.bezier(x1, y1, x2, y2, x3, y3, x4, y4); } /** * ( begin auto-generated from bezier.xml ) * * Draws a Bezier curve on the screen. These curves are defined by a series * of anchor and control points. The first two parameters specify the first * anchor point and the last two parameters specify the other anchor point. * The middle parameters specify the control points which define the shape * of the curve. Bezier curves were developed by French engineer Pierre * Bezier. Using the 3D version requires rendering with P3D (see the * Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * Draw a cubic bezier curve. The first and last points are * the on-curve points. The middle two are the 'control' points, * or 'handles' in an application like Illustrator. * <P> * Identical to typing: * <PRE>beginShape(); * vertex(x1, y1); * bezierVertex(x2, y2, x3, y3, x4, y4); * endShape(); * </PRE> * In Postscript-speak, this would be: * <PRE>moveto(x1, y1); * curveto(x2, y2, x3, y3, x4, y4);</PRE> * If you were to try and continue that curve like so: * <PRE>curveto(x5, y5, x6, y6, x7, y7);</PRE> * This would be done in processing by adding these statements: * <PRE>bezierVertex(x5, y5, x6, y6, x7, y7) * </PRE> * To draw a quadratic (instead of cubic) curve, * use the control point twice by doubling it: * <PRE>bezier(x1, y1, cx, cy, cx, cy, x2, y2);</PRE> * * @webref shape:curves * @param x1 coordinates for the first anchor point * @param y1 coordinates for the first anchor point * @param z1 coordinates for the first anchor point * @param x2 coordinates for the first control point * @param y2 coordinates for the first control point * @param z2 coordinates for the first control point * @param x3 coordinates for the second control point * @param y3 coordinates for the second control point * @param z3 coordinates for the second control point * @param x4 coordinates for the second anchor point * @param y4 coordinates for the second anchor point * @param z4 coordinates for the second anchor point * * @see PGraphics#bezierVertex(float, float, float, float, float, float) * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) */ public void bezier(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.bezier(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from curvePoint.xml ) * * Evalutes the curve at point t for points a, b, c, d. The parameter t * varies between 0 and 1, a and d are points on the curve, and b and c are * the control points. This can be done once with the x coordinates and a * second time with the y coordinates to get the location of a curve at t. * * ( end auto-generated ) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of second point on the curve * @param c coordinate of third point on the curve * @param d coordinate of fourth point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#bezierPoint(float, float, float, float, float) */ public float curvePoint(float a, float b, float c, float d, float t) { return g.curvePoint(a, b, c, d, t); } /** * ( begin auto-generated from curveTangent.xml ) * * Calculates the tangent of a point on a curve. There's a good definition * of <em><a href="http://en.wikipedia.org/wiki/Tangent" * target="new">tangent</em> on Wikipedia</a>. * * ( end auto-generated ) * * <h3>Advanced</h3> * Code thanks to Dave Bollinger (Bug #715) * * @webref shape:curves * @param a coordinate of first point on the curve * @param b coordinate of first control point * @param c coordinate of second control point * @param d coordinate of second point on the curve * @param t value between 0 and 1 * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curvePoint(float, float, float, float, float) * @see PGraphics#bezierTangent(float, float, float, float, float) */ public float curveTangent(float a, float b, float c, float d, float t) { return g.curveTangent(a, b, c, d, t); } /** * ( begin auto-generated from curveDetail.xml ) * * Sets the resolution at which curves display. The default value is 20. * This function is only useful when using the P3D renderer as the default * P2D renderer does not use this information. * * ( end auto-generated ) * * @webref shape:curves * @param detail resolution of the curves * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) */ public void curveDetail(int detail) { if (recorder != null) recorder.curveDetail(detail); g.curveDetail(detail); } /** * ( begin auto-generated from curveTightness.xml ) * * Modifies the quality of forms created with <b>curve()</b> and * <b>curveVertex()</b>. The parameter <b>squishy</b> determines how the * curve fits to the vertex points. The value 0.0 is the default value for * <b>squishy</b> (this value defines the curves to be Catmull-Rom splines) * and the value 1.0 connects all the points with straight lines. Values * within the range -5.0 and 5.0 will deform the curves but will leave them * recognizable and as values increase in magnitude, they will continue to deform. * * ( end auto-generated ) * * @webref shape:curves * @param tightness amount of deformation from the original vertices * @see PGraphics#curve(float, float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#curveVertex(float, float) */ public void curveTightness(float tightness) { if (recorder != null) recorder.curveTightness(tightness); g.curveTightness(tightness); } /** * ( begin auto-generated from curve.xml ) * * Draws a curved line on the screen. The first and second parameters * specify the beginning control point and the last two parameters specify * the ending control point. The middle parameters specify the start and * stop of the curve. Longer curves can be created by putting a series of * <b>curve()</b> functions together or using <b>curveVertex()</b>. An * additional function called <b>curveTightness()</b> provides control for * the visual quality of the curve. The <b>curve()</b> function is an * implementation of Catmull-Rom splines. Using the 3D version requires * rendering with P3D (see the Environment reference for more information). * * ( end auto-generated ) * * <h3>Advanced</h3> * As of revision 0070, this function no longer doubles the first * and last points. The curves are a bit more boring, but it's more * mathematically correct, and properly mirrored in curvePoint(). * <P> * Identical to typing out:<PRE> * beginShape(); * curveVertex(x1, y1); * curveVertex(x2, y2); * curveVertex(x3, y3); * curveVertex(x4, y4); * endShape(); * </PRE> * * @webref shape:curves * @param x1 coordinates for the beginning control point * @param y1 coordinates for the beginning control point * @param x2 coordinates for the first point * @param y2 coordinates for the first point * @param x3 coordinates for the second point * @param y3 coordinates for the second point * @param x4 coordinates for the ending control point * @param y4 coordinates for the ending control point * @see PGraphics#curveVertex(float, float) * @see PGraphics#curveTightness(float) * @see PGraphics#bezier(float, float, float, float, float, float, float, float, float, float, float, float) */ public void curve(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4) { if (recorder != null) recorder.curve(x1, y1, x2, y2, x3, y3, x4, y4); g.curve(x1, y1, x2, y2, x3, y3, x4, y4); } /** * @param z1 coordinates for the beginning control point * @param z2 coordinates for the first point * @param z3 coordinates for the second point * @param z4 coordinates for the ending control point */ public void curve(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, float x4, float y4, float z4) { if (recorder != null) recorder.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); g.curve(x1, y1, z1, x2, y2, z2, x3, y3, z3, x4, y4, z4); } /** * ( begin auto-generated from smooth.xml ) * * Draws all geometry with smooth (anti-aliased) edges. This will sometimes * slow down the frame rate of the application, but will enhance the visual * refinement. Note that <b>smooth()</b> will also improve image quality of * resized images, and <b>noSmooth()</b> will disable image (and font) * smoothing altogether. * * ( end auto-generated ) * * @webref shape:attributes * @see PGraphics#noSmooth() * @see PGraphics#hint(int) * @see PApplet#size(int, int, String) */ public void smooth() { if (recorder != null) recorder.smooth(); g.smooth(); } public void smooth(int level) { if (recorder != null) recorder.smooth(level); g.smooth(level); } /** * ( begin auto-generated from noSmooth.xml ) * * Draws all geometry with jagged (aliased) edges. * * ( end auto-generated ) * @webref shape:attributes * @see PGraphics#smooth() */ public void noSmooth() { if (recorder != null) recorder.noSmooth(); g.noSmooth(); } /** * ( begin auto-generated from imageMode.xml ) * * Modifies the location from which images draw. The default mode is * <b>imageMode(CORNER)</b>, which specifies the location to be the upper * left corner and uses the fourth and fifth parameters of <b>image()</b> * to set the image's width and height. The syntax * <b>imageMode(CORNERS)</b> uses the second and third parameters of * <b>image()</b> to set the location of one corner of the image and uses * the fourth and fifth parameters to set the opposite corner. Use * <b>imageMode(CENTER)</b> to draw images centered at the given x and y * position.<br /> * <br /> * The parameter to <b>imageMode()</b> must be written in ALL CAPS because * Processing is a case-sensitive language. * * ( end auto-generated ) * * @webref image:loading_displaying * @param mode either CORNER, CORNERS, or CENTER * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#image(PImage, float, float, float, float) * @see PGraphics#background(float, float, float, float) */ public void imageMode(int mode) { if (recorder != null) recorder.imageMode(mode); g.imageMode(mode); } public void image(PImage image, float x, float y) { if (recorder != null) recorder.image(image, x, y); g.image(image, x, y); } /** * ( begin auto-generated from image.xml ) * * Displays images to the screen. The images must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the image. Processing currently works with GIF, JPEG, and Targa * images. The <b>img</b> parameter specifies the image to display and the * <b>x</b> and <b>y</b> parameters define the location of the image from * its upper-left corner. The image is displayed at its original size * unless the <b>width</b> and <b>height</b> parameters specify a different * size.<br /> * <br /> * The <b>imageMode()</b> function changes the way the parameters work. For * example, a call to <b>imageMode(CORNERS)</b> will change the * <b>width</b> and <b>height</b> parameters to define the x and y values * of the opposite corner of the image.<br /> * <br /> * The color of an image may be modified with the <b>tint()</b> function. * This function will maintain transparency for GIF and PNG images. * * ( end auto-generated ) * * <h3>Advanced</h3> * Starting with release 0124, when using the default (JAVA2D) renderer, * smooth() will also improve image quality of resized images. * * @webref image:loading_displaying * @param image the image to display * @param x x-coordinate of the image * @param y y-coordinate of the image * @param c width to display the image * @param d height to display the image * @see PApplet#loadImage(String, String) * @see PImage * @see PGraphics#imageMode(int) * @see PGraphics#tint(float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#alpha(int) */ public void image(PImage image, float x, float y, float c, float d) { if (recorder != null) recorder.image(image, x, y, c, d); g.image(image, x, y, c, d); } /** * Draw an image(), also specifying u/v coordinates. * In this method, the u, v coordinates are always based on image space * location, regardless of the current textureMode(). * * @nowebref */ public void image(PImage image, float a, float b, float c, float d, int u1, int v1, int u2, int v2) { if (recorder != null) recorder.image(image, a, b, c, d, u1, v1, u2, v2); g.image(image, a, b, c, d, u1, v1, u2, v2); } /** * ( begin auto-generated from shapeMode.xml ) * * Modifies the location from which shapes draw. The default mode is * <b>shapeMode(CORNER)</b>, which specifies the location to be the upper * left corner of the shape and uses the third and fourth parameters of * <b>shape()</b> to specify the width and height. The syntax * <b>shapeMode(CORNERS)</b> uses the first and second parameters of * <b>shape()</b> to set the location of one corner and uses the third and * fourth parameters to set the opposite corner. The syntax * <b>shapeMode(CENTER)</b> draws the shape from its center point and uses * the third and forth parameters of <b>shape()</b> to specify the width * and height. The parameter must be written in "ALL CAPS" because * Processing is a case sensitive language. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param mode either CORNER, CORNERS, CENTER * @see PGraphics#shape(PShape) * @see PGraphics#rectMode(int) */ public void shapeMode(int mode) { if (recorder != null) recorder.shapeMode(mode); g.shapeMode(mode); } public void shape(PShape shape) { if (recorder != null) recorder.shape(shape); g.shape(shape); } /** * Convenience method to draw at a particular location. */ public void shape(PShape shape, float x, float y) { if (recorder != null) recorder.shape(shape, x, y); g.shape(shape, x, y); } /** * ( begin auto-generated from shape.xml ) * * Displays shapes to the screen. The shapes must be in the sketch's "data" * directory to load correctly. Select "Add file..." from the "Sketch" menu * to add the shape. Processing currently works with SVG shapes only. The * <b>sh</b> parameter specifies the shape to display and the <b>x</b> and * <b>y</b> parameters define the location of the shape from its upper-left * corner. The shape is displayed at its original size unless the * <b>width</b> and <b>height</b> parameters specify a different size. The * <b>shapeMode()</b> function changes the way the parameters work. A call * to <b>shapeMode(CORNERS)</b>, for example, will change the width and * height parameters to define the x and y values of the opposite corner of * the shape. * <br /><br /> * Note complex shapes may draw awkwardly with P3D. This renderer does not * yet support shapes that have holes or complicated breaks. * * ( end auto-generated ) * * @webref shape:loading_displaying * @param shape the shape to display * @param x x-coordinate of the shape * @param y y-coordinate of the shape * @param c width to display the shape * @param d height to display the shape * @see PShape * @see PApplet#loadShape(String) * @see PGraphics#shapeMode(int) */ public void shape(PShape shape, float x, float y, float c, float d) { if (recorder != null) recorder.shape(shape, x, y, c, d); g.shape(shape, x, y, c, d); } public void textAlign(int align) { if (recorder != null) recorder.textAlign(align); g.textAlign(align); } /** * ( begin auto-generated from textAlign.xml ) * * Sets the current alignment for drawing text. The parameters LEFT, * CENTER, and RIGHT set the display characteristics of the letters in * relation to the values for the <b>x</b> and <b>y</b> parameters of the * <b>text()</b> function. * <br/> <br/> * In Processing 0125 and later, an optional second parameter can be used * to vertically align the text. BASELINE is the default, and the vertical * alignment will be reset to BASELINE if the second parameter is not used. * The TOP and CENTER parameters are straightforward. The BOTTOM parameter * offsets the line based on the current <b>textDescent()</b>. For multiple * lines, the final line will be aligned to the bottom, with the previous * lines appearing above it. * <br/> <br/> * When using <b>text()</b> with width and height parameters, BASELINE is * ignored, and treated as TOP. (Otherwise, text would by default draw * outside the box, since BASELINE is the default setting. BASELINE is not * a useful drawing mode for text drawn in a rectangle.) * <br/> <br/> * The vertical alignment is based on the value of <b>textAscent()</b>, * which many fonts do not specify correctly. It may be necessary to use a * hack and offset by a few pixels by hand so that the offset looks * correct. To do this as less of a hack, use some percentage of * <b>textAscent()</b> or <b>textDescent()</b> so that the hack works even * if you change the size of the font. * * ( end auto-generated ) * * @webref typography:attributes * @param alignX horizontal alignment, either LEFT, CENTER, or RIGHT * @param alignY vertical alignment, either TOP, BOTTOM, CENTER, or BASELINE * @see PApplet#loadFont(String) * @see PFont * @see PGraphics#text(String, float, float, float, float, float) */ public void textAlign(int alignX, int alignY) { if (recorder != null) recorder.textAlign(alignX, alignY); g.textAlign(alignX, alignY); } /** * ( begin auto-generated from textAscent.xml ) * * Returns ascent of the current font at its current size. This information * is useful for determining the height of the font above the baseline. For * example, adding the <b>textAscent()</b> and <b>textDescent()</b> values * will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textDescent() */ public float textAscent() { return g.textAscent(); } /** * ( begin auto-generated from textDescent.xml ) * * Returns descent of the current font at its current size. This * information is useful for determining the height of the font below the * baseline. For example, adding the <b>textAscent()</b> and * <b>textDescent()</b> values will give you the total height of the line. * * ( end auto-generated ) * * @webref typography:metrics * @see PGraphics#textAscent() */ public float textDescent() { return g.textDescent(); } /** * ( begin auto-generated from textFont.xml ) * * Sets the current font that will be drawn with the <b>text()</b> * function. Fonts must be loaded with <b>loadFont()</b> before it can be * used. This font will be used in all subsequent calls to the * <b>text()</b> function. If no <b>size</b> parameter is input, the font * will appear at its original size (the size it was created at with the * "Create Font..." tool) until it is changed with <b>textSize()</b>. <br * /> <br /> Because fonts are usually bitmaped, you should create fonts at * the sizes that will be used most commonly. Using <b>textFont()</b> * without the size parameter will result in the cleanest-looking text. <br * /><br /> With the default (JAVA2D) and PDF renderers, it's also possible * to enable the use of native fonts via the command * <b>hint(ENABLE_NATIVE_FONTS)</b>. This will produce vector text in * JAVA2D sketches and PDF output in cases where the vector data is * available: when the font is still installed, or the font is created via * the <b>createFont()</b> function (rather than the Create Font tool). * * ( end auto-generated ) * * @webref typography:loading_displaying * @param which any variable of the type PFont * @see PApplet#createFont(String, float, boolean) * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) */ public void textFont(PFont which) { if (recorder != null) recorder.textFont(which); g.textFont(which); } /** * @param size the size of the letters in units of pixels */ public void textFont(PFont which, float size) { if (recorder != null) recorder.textFont(which, size); g.textFont(which, size); } /** * ( begin auto-generated from textLeading.xml ) * * Sets the spacing between lines of text in units of pixels. This setting * will be used in all subsequent calls to the <b>text()</b> function. * * ( end auto-generated ) * * @webref typography:attributes * @param leading the size in pixels for spacing between lines * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public void textLeading(float leading) { if (recorder != null) recorder.textLeading(leading); g.textLeading(leading); } /** * ( begin auto-generated from textMode.xml ) * * Sets the way text draws to the screen. In the default configuration, the * <b>MODEL</b> mode, it's possible to rotate, scale, and place letters in * two and three dimensional space.<br /> * <br /> * The <b>SHAPE</b> mode draws text using the the glyph outlines of * individual characters rather than as textures. This mode is only * supported with the <b>PDF</b> and <b>P3D</b> renderer settings. With the * <b>PDF</b> renderer, you must call <b>textMode(SHAPE)</b> before any * other drawing occurs. If the outlines are not available, then * <b>textMode(SHAPE)</b> will be ignored and <b>textMode(MODEL)</b> will * be used instead.<br /> * <br /> * The <b>textMode(SHAPE)</b> option in <b>P3D</b> can be combined with * <b>beginRaw()</b> to write vector-accurate text to 2D and 3D output * files, for instance <b>DXF</b> or <b>PDF</b>. The <b>SHAPE</b> mode is * not currently optimized for <b>P3D</b>, so if recording shape data, use * <b>textMode(MODEL)</b> until you're ready to capture the geometry with <b>beginRaw()</b>. * * ( end auto-generated ) * * @webref typography:attributes * @param mode either MODEL or SHAPE * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) * @see PGraphics#beginRaw(PGraphics) * @see PApplet#createFont(String, float, boolean) */ public void textMode(int mode) { if (recorder != null) recorder.textMode(mode); g.textMode(mode); } /** * ( begin auto-generated from textSize.xml ) * * Sets the current font size. This size will be used in all subsequent * calls to the <b>text()</b> function. Font size is measured in units of pixels. * * ( end auto-generated ) * * @webref typography:attributes * @param size the size of the letters in units of pixels * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public void textSize(float size) { if (recorder != null) recorder.textSize(size); g.textSize(size); } public float textWidth(char c) { return g.textWidth(c); } /** * ( begin auto-generated from textWidth.xml ) * * Calculates and returns the width of any character or text string. * * ( end auto-generated ) * * @webref typography:attributes * @param str * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#text(String, float, float, float, float, float) * @see PGraphics#textFont(PFont) */ public float textWidth(String str) { return g.textWidth(str); } /** * @nowebref */ public float textWidth(char[] chars, int start, int length) { return g.textWidth(chars, start, length); } /** * ( begin auto-generated from text.xml ) * * Draws text to the screen. Displays the information specified in the * <b>data</b> or <b>stringdata</b> parameters on the screen in the * position specified by the <b>x</b> and <b>y</b> parameters and the * optional <b>z</b> parameter. A default font will be used unless a font * is set with the <b>textFont()</b> function. Change the color of the text * with the <b>fill()</b> function. The text displays in relation to the * <b>textAlign()</b> function, which gives the option to draw to the left, * right, and center of the coordinates. * <br /><br /> * The <b>x2</b> and <b>y2</b> parameters define a rectangular area to * display within and may only be used with string data. For text drawn * inside a rectangle, the coordinates are interpreted based on the current * <b>rectMode()</b> setting. * * ( end auto-generated ) * * @webref typography:loading_displaying * @param c the alphanumeric character to be displayed * @see PGraphics#textAlign(int, int) * @see PGraphics#textMode(int) * @see PApplet#loadFont(String) * @see PFont#PFont * @see PGraphics#textFont(PFont) * @see PGraphics#rectMode(int) * @see PGraphics#fill(int, float) * @see_external String */ public void text(char c) { if (recorder != null) recorder.text(c); g.text(c); } /** * <h3>Advanced</h3> * Draw a single character on screen. * Extremely slow when used with textMode(SCREEN) and Java 2D, * because loadPixels has to be called first and updatePixels last. * * @param x x-coordinate of text * @param y y-coordinate of text */ public void text(char c, float x, float y) { if (recorder != null) recorder.text(c, x, y); g.text(c, x, y); } /** * @param z z-coordinate of text */ public void text(char c, float x, float y, float z) { if (recorder != null) recorder.text(c, x, y, z); g.text(c, x, y, z); } /** * @param str the alphanumeric symbols to be displayed */ public void text(String str) { if (recorder != null) recorder.text(str); g.text(str); } /** * <h3>Advanced</h3> * Draw a chunk of text. * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, but \r (carriage return, Windows and Mac OS) are * ignored. */ public void text(String str, float x, float y) { if (recorder != null) recorder.text(str, x, y); g.text(str, x, y); } /** * <h3>Advanced</h3> * Method to draw text from an array of chars. This method will usually be * more efficient than drawing from a String object, because the String will * not be converted to a char array before drawing. * @param chars the alphanumberic symbols to be displayed * @param start array index to start writing characters * @param stop array index to stop writing characters */ public void text(char[] chars, int start, int stop, float x, float y) { if (recorder != null) recorder.text(chars, start, stop, x, y); g.text(chars, start, stop, x, y); } /** * Same as above but with a z coordinate. */ public void text(String str, float x, float y, float z) { if (recorder != null) recorder.text(str, x, y, z); g.text(str, x, y, z); } public void text(char[] chars, int start, int stop, float x, float y, float z) { if (recorder != null) recorder.text(chars, start, stop, x, y, z); g.text(chars, start, stop, x, y, z); } /** * <h3>Advanced</h3> * Draw text in a box that is constrained to a particular size. * The current rectMode() determines what the coordinates mean * (whether x1/y1/x2/y2 or x/y/w/h). * <P/> * Note that the x,y coords of the start of the box * will align with the *ascent* of the text, not the baseline, * as is the case for the other text() functions. * <P/> * Newlines that are \n (Unix newline or linefeed char, ascii 10) * are honored, and \r (carriage return, Windows and Mac OS) are * ignored. * * @param x1 by default, the x-coordinate of text, see rectMode() for more info * @param y1 by default, the x-coordinate of text, see rectMode() for more info * @param x2 by default, the width of the text box, see rectMode() for more info * @param y2 by default, the height of the text box, see rectMode() for more info */ public void text(String str, float x1, float y1, float x2, float y2) { if (recorder != null) recorder.text(str, x1, y1, x2, y2); g.text(str, x1, y1, x2, y2); } public void text(String s, float x1, float y1, float x2, float y2, float z) { if (recorder != null) recorder.text(s, x1, y1, x2, y2, z); g.text(s, x1, y1, x2, y2, z); } public void text(int num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(int num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * This does a basic number formatting, to avoid the * generally ugly appearance of printing floats. * Users who want more control should use their own nf() cmmand, * or if they want the long, ugly version of float, * use String.valueOf() to convert the float to a String first. * * @param num the alphanumeric symbols to be displayed */ public void text(float num, float x, float y) { if (recorder != null) recorder.text(num, x, y); g.text(num, x, y); } public void text(float num, float x, float y, float z) { if (recorder != null) recorder.text(num, x, y, z); g.text(num, x, y, z); } /** * ( begin auto-generated from pushMatrix.xml ) * * Pushes the current transformation matrix onto the matrix stack. * Understanding <b>pushMatrix()</b> and <b>popMatrix()</b> requires * understanding the concept of a matrix stack. The <b>pushMatrix()</b> * function saves the current coordinate system to the stack and * <b>popMatrix()</b> restores the prior coordinate system. * <b>pushMatrix()</b> and <b>popMatrix()</b> are used in conjuction with * the other transformation functions and may be embedded to control the * scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#popMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) */ public void pushMatrix() { if (recorder != null) recorder.pushMatrix(); g.pushMatrix(); } /** * ( begin auto-generated from popMatrix.xml ) * * Pops the current transformation matrix off the matrix stack. * Understanding pushing and popping requires understanding the concept of * a matrix stack. The <b>pushMatrix()</b> function saves the current * coordinate system to the stack and <b>popMatrix()</b> restores the prior * coordinate system. <b>pushMatrix()</b> and <b>popMatrix()</b> are used * in conjuction with the other transformation functions and may be * embedded to control the scope of the transformations. * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() */ public void popMatrix() { if (recorder != null) recorder.popMatrix(); g.popMatrix(); } /** * ( begin auto-generated from translate.xml ) * * Specifies an amount to displace objects within the display window. The * <b>x</b> parameter specifies left/right translation, the <b>y</b> * parameter specifies up/down translation, and the <b>z</b> parameter * specifies translations toward/away from the screen. Using this function * with the <b>z</b> parameter requires using P3D as a parameter in * combination with size as shown in the above example. Transformations * apply to everything that happens after and subsequent calls to the * function accumulates the effect. For example, calling <b>translate(50, * 0)</b> and then <b>translate(20, 0)</b> is the same as <b>translate(70, * 0)</b>. If <b>translate()</b> is called within <b>draw()</b>, the * transformation is reset when the loop begins again. This function can be * further controlled by the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param tx left/right translation * @param ty up/down translation * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) */ public void translate(float tx, float ty) { if (recorder != null) recorder.translate(tx, ty); g.translate(tx, ty); } /** * @param tz forward/backward translation */ public void translate(float tx, float ty, float tz) { if (recorder != null) recorder.translate(tx, ty, tz); g.translate(tx, ty, tz); } /** * ( begin auto-generated from rotate.xml ) * * Rotates a shape the amount specified by the <b>angle</b> parameter. * Angles should be specified in radians (values from 0 to TWO_PI) or * converted to radians with the <b>radians()</b> function. * <br/> <br/> * Objects are always rotated around their relative position to the origin * and positive numbers rotate objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>rotate(HALF_PI)</b> and then <b>rotate(HALF_PI)</b> is the same as * <b>rotate(PI)</b>. All tranformations are reset when <b>draw()</b> * begins again. * <br/> <br/> * Technically, <b>rotate()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PApplet#radians(float) */ public void rotate(float angle) { if (recorder != null) recorder.rotate(angle); g.rotate(angle); } /** * ( begin auto-generated from rotateX.xml ) * * Rotates a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateX(PI/2)</b> and then <b>rotateX(PI/2)</b> is the same * as <b>rotateX(PI)</b>. If <b>rotateX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the example above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateX(float angle) { if (recorder != null) recorder.rotateX(angle); g.rotateX(angle); } /** * ( begin auto-generated from rotateY.xml ) * * Rotates a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateY(PI/2)</b> and then <b>rotateY(PI/2)</b> is the same * as <b>rotateY(PI)</b>. If <b>rotateY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateZ(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateY(float angle) { if (recorder != null) recorder.rotateY(angle); g.rotateY(angle); } /** * ( begin auto-generated from rotateZ.xml ) * * Rotates a shape around the z-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always rotated around their relative position to * the origin and positive numbers rotate objects in a counterclockwise * direction. Transformations apply to everything that happens after and * subsequent calls to the function accumulates the effect. For example, * calling <b>rotateZ(PI/2)</b> and then <b>rotateZ(PI/2)</b> is the same * as <b>rotateZ(PI)</b>. If <b>rotateZ()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * This function requires using P3D as a third parameter to <b>size()</b> * as shown in the examples above. * * ( end auto-generated ) * * @webref transform * @param angle angle of rotation specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) */ public void rotateZ(float angle) { if (recorder != null) recorder.rotateZ(angle); g.rotateZ(angle); } /** * <h3>Advanced</h3> * Rotate about a vector in space. Same as the glRotatef() function. * @param vx * @param vy * @param vz */ public void rotate(float angle, float vx, float vy, float vz) { if (recorder != null) recorder.rotate(angle, vx, vy, vz); g.rotate(angle, vx, vy, vz); } /** * ( begin auto-generated from scale.xml ) * * Increases or decreases the size of a shape by expanding and contracting * vertices. Objects always scale from their relative origin to the * coordinate system. Scale values are specified as decimal percentages. * For example, the function call <b>scale(2.0)</b> increases the dimension * of a shape by 200%. Transformations apply to everything that happens * after and subsequent calls to the function multiply the effect. For * example, calling <b>scale(2.0)</b> and then <b>scale(1.5)</b> is the * same as <b>scale(3.0)</b>. If <b>scale()</b> is called within * <b>draw()</b>, the transformation is reset when the loop begins again. * Using this fuction with the <b>z</b> parameter requires using P3D as a * parameter for <b>size()</b> as shown in the example above. This function * can be further controlled by <b>pushMatrix()</b> and <b>popMatrix()</b>. * * ( end auto-generated ) * * @webref transform * @param s percentage to scale the object * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#rotate(float) * @see PGraphics#rotateX(float) * @see PGraphics#rotateY(float) * @see PGraphics#rotateZ(float) * @see PGraphics#translate(float, float, float) */ public void scale(float s) { if (recorder != null) recorder.scale(s); g.scale(s); } /** * <h3>Advanced</h3> * Scale in X and Y. Equivalent to scale(sx, sy, 1). * * Not recommended for use in 3D, because the z-dimension is just * scaled by 1, since there's no way to know what else to scale it by. * * @param sx percentage to scale the object in the x-axis * @param sy percentage to scale the objects in the y-axis */ public void scale(float sx, float sy) { if (recorder != null) recorder.scale(sx, sy); g.scale(sx, sy); } /** * @param x percentage to scale the object in the x-axis * @param y percentage to scale the objects in the y-axis * @param z percentage to scale the object in the z-axis */ public void scale(float x, float y, float z) { if (recorder != null) recorder.scale(x, y, z); g.scale(x, y, z); } /** * ( begin auto-generated from shearX.xml ) * * Shears a shape around the x-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearX(PI/2)</b> and then <b>shearX(PI/2)</b> is the same as * <b>shearX(PI)</b>. If <b>shearX()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearX()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearY(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearX(float angle) { if (recorder != null) recorder.shearX(angle); g.shearX(angle); } /** * ( begin auto-generated from shearY.xml ) * * Shears a shape around the y-axis the amount specified by the * <b>angle</b> parameter. Angles should be specified in radians (values * from 0 to PI*2) or converted to radians with the <b>radians()</b> * function. Objects are always sheared around their relative position to * the origin and positive numbers shear objects in a clockwise direction. * Transformations apply to everything that happens after and subsequent * calls to the function accumulates the effect. For example, calling * <b>shearY(PI/2)</b> and then <b>shearY(PI/2)</b> is the same as * <b>shearY(PI)</b>. If <b>shearY()</b> is called within the * <b>draw()</b>, the transformation is reset when the loop begins again. * <br/> <br/> * Technically, <b>shearY()</b> multiplies the current transformation * matrix by a rotation matrix. This function can be further controlled by * the <b>pushMatrix()</b> and <b>popMatrix()</b> functions. * * ( end auto-generated ) * * @webref transform * @param angle angle of shear specified in radians * @see PGraphics#popMatrix() * @see PGraphics#pushMatrix() * @see PGraphics#shearX(float) * @see PGraphics#scale(float, float, float) * @see PGraphics#translate(float, float, float) * @see PApplet#radians(float) */ public void shearY(float angle) { if (recorder != null) recorder.shearY(angle); g.shearY(angle); } /** * ( begin auto-generated from resetMatrix.xml ) * * Replaces the current matrix with the identity matrix. The equivalent * function in OpenGL is glLoadIdentity(). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#printMatrix() */ public void resetMatrix() { if (recorder != null) recorder.resetMatrix(); g.resetMatrix(); } /** * ( begin auto-generated from applyMatrix.xml ) * * Multiplies the current matrix by the one specified through the * parameters. This is very slow because it will try to calculate the * inverse of the transform, so avoid it whenever possible. The equivalent * function in OpenGL is glMultMatrix(). * * ( end auto-generated ) * * @webref transform * @source * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#printMatrix() */ public void applyMatrix(PMatrix source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } public void applyMatrix(PMatrix2D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n00 numbers which define the 4x4 matrix to be multiplied * @param n01 numbers which define the 4x4 matrix to be multiplied * @param n02 numbers which define the 4x4 matrix to be multiplied * @param n10 numbers which define the 4x4 matrix to be multiplied * @param n11 numbers which define the 4x4 matrix to be multiplied * @param n12 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n10, float n11, float n12) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n10, n11, n12); g.applyMatrix(n00, n01, n02, n10, n11, n12); } public void applyMatrix(PMatrix3D source) { if (recorder != null) recorder.applyMatrix(source); g.applyMatrix(source); } /** * @param n13 numbers which define the 4x4 matrix to be multiplied * @param n20 numbers which define the 4x4 matrix to be multiplied * @param n21 numbers which define the 4x4 matrix to be multiplied * @param n22 numbers which define the 4x4 matrix to be multiplied * @param n23 numbers which define the 4x4 matrix to be multiplied * @param n30 numbers which define the 4x4 matrix to be multiplied * @param n31 numbers which define the 4x4 matrix to be multiplied * @param n32 numbers which define the 4x4 matrix to be multiplied * @param n33 numbers which define the 4x4 matrix to be multiplied */ public void applyMatrix(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23, float n30, float n31, float n32, float n33) { if (recorder != null) recorder.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); g.applyMatrix(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23, n30, n31, n32, n33); } public PMatrix getMatrix() { return g.getMatrix(); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix2D getMatrix(PMatrix2D target) { return g.getMatrix(target); } /** * Copy the current transformation matrix into the specified target. * Pass in null to create a new matrix. */ public PMatrix3D getMatrix(PMatrix3D target) { return g.getMatrix(target); } /** * Set the current transformation matrix to the contents of another. */ public void setMatrix(PMatrix source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix2D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * Set the current transformation to the contents of the specified source. */ public void setMatrix(PMatrix3D source) { if (recorder != null) recorder.setMatrix(source); g.setMatrix(source); } /** * ( begin auto-generated from printMatrix.xml ) * * Prints the current matrix to the Console (the text window at the bottom * of Processing). * * ( end auto-generated ) * * @webref transform * @see PGraphics#pushMatrix() * @see PGraphics#popMatrix() * @see PGraphics#resetMatrix() * @see PGraphics#applyMatrix(PMatrix) */ public void printMatrix() { if (recorder != null) recorder.printMatrix(); g.printMatrix(); } /** * ( begin auto-generated from beginCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. The functions are useful if * you want to more control over camera movement, however for most users, * the <b>camera()</b> function will be sufficient.<br /><br />The camera * functions will replace any transformations (such as <b>rotate()</b> or * <b>translate()</b>) that occur before them in <b>draw()</b>, but they * will not automatically replace the camera transform itself. For this * reason, camera functions should be placed at the beginning of * <b>draw()</b> (so that transformations happen afterwards), and the * <b>camera()</b> function can be used after <b>beginCamera()</b> if you * want to reset the camera before applying transformations.<br /><br * />This function sets the matrix mode to the camera matrix so calls such * as <b>translate()</b>, <b>rotate()</b>, applyMatrix() and resetMatrix() * affect the camera. <b>beginCamera()</b> should always be used with a * following <b>endCamera()</b> and pairs of <b>beginCamera()</b> and * <b>endCamera()</b> cannot be nested. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera() * @see PGraphics#endCamera() * @see PGraphics#applyMatrix(PMatrix) * @see PGraphics#resetMatrix() * @see PGraphics#translate(float, float, float) * @see PGraphics#scale(float, float, float) */ public void beginCamera() { if (recorder != null) recorder.beginCamera(); g.beginCamera(); } /** * ( begin auto-generated from endCamera.xml ) * * The <b>beginCamera()</b> and <b>endCamera()</b> functions enable * advanced customization of the camera space. Please see the reference for * <b>beginCamera()</b> for a description of how the functions are used. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void endCamera() { if (recorder != null) recorder.endCamera(); g.endCamera(); } /** * ( begin auto-generated from camera.xml ) * * Sets the position of the camera through setting the eye position, the * center of the scene, and which axis is facing upward. Moving the eye * position and the direction it is pointing (the center of the scene) * allows the images to be seen from different angles. The version without * any parameters sets the camera to the default position, pointing to the * center of the display window with the Y axis as up. The default values * are <b>camera(width/2.0, height/2.0, (height/2.0) / tan(PI*30.0 / * 180.0), width/2.0, height/2.0, 0, 0, 1, 0)</b>. This function is similar * to <b>gluLookAt()</b> in OpenGL, but it first clears the current camera settings. * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#endCamera() * @see PGraphics#frustum(float, float, float, float, float, float) */ public void camera() { if (recorder != null) recorder.camera(); g.camera(); } /** * @param eyeX x-coordinate for the eye * @param eyeY y-coordinate for the eye * @param eyeZ z-coordinate for the eye * @param centerX x-coordinate for the center of the scene * @param centerY y-coordinate for the center of the scene * @param centerZ z-coordinate for the center of the scene * @param upX usually 0.0, 1.0, or -1.0 * @param upY usually 0.0, 1.0, or -1.0 * @param upZ usually 0.0, 1.0, or -1.0 */ public void camera(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ) { if (recorder != null) recorder.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); g.camera(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); } /** * ( begin auto-generated from printCamera.xml ) * * Prints the current camera matrix to the Console (the text window at the * bottom of Processing). * * ( end auto-generated ) * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printCamera() { if (recorder != null) recorder.printCamera(); g.printCamera(); } /** * ( begin auto-generated from ortho.xml ) * * Sets an orthographic projection and defines a parallel clipping volume. * All objects with the same dimension appear the same size, regardless of * whether they are near or far from the camera. The parameters to this * function specify the clipping volume where left and right are the * minimum and maximum x values, top and bottom are the minimum and maximum * y values, and near and far are the minimum and maximum z values. If no * parameters are given, the default is used: ortho(0, width, 0, height, * -10, 10). * * ( end auto-generated ) * * @webref lights_camera:camera */ public void ortho() { if (recorder != null) recorder.ortho(); g.ortho(); } /** * @param left left plane of the clipping volume * @param right right plane of the clipping volume * @param bottom bottom plane of the clipping volume * @param top top plane of the clipping volume */ public void ortho(float left, float right, float bottom, float top) { if (recorder != null) recorder.ortho(left, right, bottom, top); g.ortho(left, right, bottom, top); } /** * @param near maximum distance from the origin to the viewer * @param far maximum distance from the origin away from the viewer */ public void ortho(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.ortho(left, right, bottom, top, near, far); g.ortho(left, right, bottom, top, near, far); } /** * ( begin auto-generated from perspective.xml ) * * Sets a perspective projection applying foreshortening, making distant * objects appear smaller than closer ones. The parameters define a viewing * volume with the shape of truncated pyramid. Objects near to the front of * the volume appear their actual size, while farther objects appear * smaller. This projection simulates the perspective of the world more * accurately than orthographic projection. The version of perspective * without parameters sets the default perspective and the version with * four parameters allows the programmer to set the area precisely. The * default values are: perspective(PI/3.0, width/height, cameraZ/10.0, * cameraZ*10.0) where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)); * * ( end auto-generated ) * * @webref lights_camera:camera */ public void perspective() { if (recorder != null) recorder.perspective(); g.perspective(); } /** * @param fovy field-of-view angle (in radians) for vertical direction * @param aspect ratio of width to height * @param zNear z-position of nearest clipping plane * @param zFar z-position of nearest farthest plane */ public void perspective(float fovy, float aspect, float zNear, float zFar) { if (recorder != null) recorder.perspective(fovy, aspect, zNear, zFar); g.perspective(fovy, aspect, zNear, zFar); } /** * ( begin auto-generated from frustum.xml ) * * Sets a perspective matrix defined through the parameters. Works like * glFrustum, except it wipes out the current perspective matrix rather * than muliplying itself with it. * * ( end auto-generated ) * * @webref lights_camera:camera * @param left left coordinate of the clipping plane * @param right right coordinate of the clipping plane * @param bottom bottom coordinate of the clipping plane * @param top top coordinate of the clipping plane * @param near near component of the clipping plane * @param far far component of the clipping plane * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) * @see PGraphics#endCamera() * @see PGraphics#perspective(float, float, float, float) */ public void frustum(float left, float right, float bottom, float top, float near, float far) { if (recorder != null) recorder.frustum(left, right, bottom, top, near, far); g.frustum(left, right, bottom, top, near, far); } /** * ( begin auto-generated from printProjection.xml ) * * Prints the current projection matrix to the Console (the text window at * the bottom of Processing). * * ( end auto-generated ) * * @webref lights_camera:camera * @see PGraphics#camera(float, float, float, float, float, float, float, float, float) */ public void printProjection() { if (recorder != null) recorder.printProjection(); g.printProjection(); } /** * ( begin auto-generated from screenX.xml ) * * Takes a three-dimensional X, Y, Z position and returns the X value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenY(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenX(float x, float y) { return g.screenX(x, y); } /** * ( begin auto-generated from screenY.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Y value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenZ(float, float, float) */ public float screenY(float x, float y) { return g.screenY(x, y); } /** * @param z 3D z-coordinate to be mapped */ public float screenX(float x, float y, float z) { return g.screenX(x, y, z); } /** * @param z 3D z-coordinate to be mapped */ public float screenY(float x, float y, float z) { return g.screenY(x, y, z); } /** * ( begin auto-generated from screenZ.xml ) * * Takes a three-dimensional X, Y, Z position and returns the Z value for * where it will appear on a (two-dimensional) screen. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#screenX(float, float, float) * @see PGraphics#screenY(float, float, float) */ public float screenZ(float x, float y, float z) { return g.screenZ(x, y, z); } /** * ( begin auto-generated from modelX.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the X value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The X value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use. * <br/> <br/> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelY(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelX(float x, float y, float z) { return g.modelX(x, y, z); } /** * ( begin auto-generated from modelY.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Y value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Y value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelZ(float, float, float) */ public float modelY(float x, float y, float z) { return g.modelY(x, y, z); } /** * ( begin auto-generated from modelZ.xml ) * * Returns the three-dimensional X, Y, Z position in model space. This * returns the Z value for a given coordinate based on the current set of * transformations (scale, rotate, translate, etc.) The Z value can be used * to place an object in space relative to the location of the original * point once the transformations are no longer in use.<br /> * <br /> * In the example, the <b>modelX()</b>, <b>modelY()</b>, and * <b>modelZ()</b> functions record the location of a box in space after * being placed using a series of translate and rotate commands. After * popMatrix() is called, those transformations no longer apply, but the * (x, y, z) coordinate returned by the model functions is used to place * another box in the same location. * * ( end auto-generated ) * * @webref lights_camera:coordinates * @param x 3D x-coordinate to be mapped * @param y 3D y-coordinate to be mapped * @param z 3D z-coordinate to be mapped * @see PGraphics#modelX(float, float, float) * @see PGraphics#modelY(float, float, float) */ public float modelZ(float x, float y, float z) { return g.modelZ(x, y, z); } /** * ( begin auto-generated from pushStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings. Note that these functions * are always used together. They allow you to change the style settings * and later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * <br /><br /> * The style information controlled by the following functions are included * in the style: * fill(), stroke(), tint(), strokeWeight(), strokeCap(), strokeJoin(), * imageMode(), rectMode(), ellipseMode(), shapeMode(), colorMode(), * textAlign(), textFont(), textMode(), textSize(), textLeading(), * emissive(), specular(), shininess(), ambient() * * ( end auto-generated ) * * @webref structure * @see PGraphics#popStyle() */ public void pushStyle() { if (recorder != null) recorder.pushStyle(); g.pushStyle(); } /** * ( begin auto-generated from popStyle.xml ) * * The <b>pushStyle()</b> function saves the current style settings and * <b>popStyle()</b> restores the prior settings; these functions are * always used together. They allow you to change the style settings and * later return to what you had. When a new style is started with * <b>pushStyle()</b>, it builds on the current style information. The * <b>pushStyle()</b> and <b>popStyle()</b> functions can be embedded to * provide more control (see the second example above for a demonstration.) * * ( end auto-generated ) * * @webref structure * @see PGraphics#pushStyle() */ public void popStyle() { if (recorder != null) recorder.popStyle(); g.popStyle(); } public void style(PStyle s) { if (recorder != null) recorder.style(s); g.style(s); } /** * ( begin auto-generated from strokeWeight.xml ) * * Sets the width of the stroke used for lines, points, and the border * around shapes. All widths are set in units of pixels. * <br/> <br/> * When drawing with P3D, series of connected lines (such as the stroke * around a polygon, triangle, or ellipse) produce unattractive results * when a thick stroke weight is set (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). With P3D, the minimum and maximum values for * <b>strokeWeight()</b> are controlled by the graphics card and the * operating system's OpenGL implementation. For instance, the thickness * may not go higher than 10 pixels. * * ( end auto-generated ) * * @webref shape:attributes * @param weight the weight (in pixels) of the stroke * @see PGraphics#stroke(int, float) * @see PGraphics#strokeJoin(int) * @see PGraphics#strokeCap(int) */ public void strokeWeight(float weight) { if (recorder != null) recorder.strokeWeight(weight); g.strokeWeight(weight); } /** * ( begin auto-generated from strokeJoin.xml ) * * Sets the style of the joints which connect line segments. These joints * are either mitered, beveled, or rounded and specified with the * corresponding parameters MITER, BEVEL, and ROUND. The default joint is * MITER. * <br/> <br/> * This function is not available with the P3D renderer, (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param join either MITER, BEVEL, ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeCap(int) */ public void strokeJoin(int join) { if (recorder != null) recorder.strokeJoin(join); g.strokeJoin(join); } /** * ( begin auto-generated from strokeCap.xml ) * * Sets the style for rendering line endings. These ends are either * squared, extended, or rounded and specified with the corresponding * parameters SQUARE, PROJECT, and ROUND. The default cap is ROUND. * <br/> <br/> * This function is not available with the P3D renderer (<a * href="http://code.google.com/p/processing/issues/detail?id=123">see * Issue 123</a>). More information about the renderers can be found in the * <b>size()</b> reference. * * ( end auto-generated ) * * @webref shape:attributes * @param cap either SQUARE, PROJECT, or ROUND * @see PGraphics#stroke(int, float) * @see PGraphics#strokeWeight(float) * @see PGraphics#strokeJoin(int) * @see PApplet#size(int, int, String, String) */ public void strokeCap(int cap) { if (recorder != null) recorder.strokeCap(cap); g.strokeCap(cap); } /** * ( begin auto-generated from noStroke.xml ) * * Disables drawing the stroke (outline). If both <b>noStroke()</b> and * <b>noFill()</b> are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @see PGraphics#stroke(float, float, float, float) */ public void noStroke() { if (recorder != null) recorder.noStroke(); g.noStroke(); } /** * ( begin auto-generated from stroke.xml ) * * Sets the color used to draw lines and borders around shapes. This color * is either specified in terms of the RGB or HSB color depending on the * current <b>colorMode()</b> (the default color space is RGB, with each * value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * * ( end auto-generated ) * * @param rgb color value in hexadecimal notation * @see PGraphics#noStroke() * @see PGraphics#fill(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void stroke(int rgb) { if (recorder != null) recorder.stroke(rgb); g.stroke(rgb); } /** * @param alpha opacity of the stroke */ public void stroke(int rgb, float alpha) { if (recorder != null) recorder.stroke(rgb, alpha); g.stroke(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void stroke(float gray) { if (recorder != null) recorder.stroke(gray); g.stroke(gray); } public void stroke(float gray, float alpha) { if (recorder != null) recorder.stroke(gray, alpha); g.stroke(gray, alpha); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) * @webref color:setting */ public void stroke(float x, float y, float z) { if (recorder != null) recorder.stroke(x, y, z); g.stroke(x, y, z); } public void stroke(float x, float y, float z, float alpha) { if (recorder != null) recorder.stroke(x, y, z, alpha); g.stroke(x, y, z, alpha); } /** * ( begin auto-generated from noTint.xml ) * * Removes the current fill value for displaying images and reverts to * displaying images with their original hues. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @see PGraphics#tint(float, float, float, float) * @see PGraphics#image(PImage, float, float, float, float) */ public void noTint() { if (recorder != null) recorder.noTint(); g.noTint(); } /** * ( begin auto-generated from tint.xml ) * * Sets the fill value for displaying images. Images can be tinted to * specified colors or made transparent by setting the alpha.<br /> * <br /> * To make an image transparent, but not change it's color, use white as * the tint color and specify an alpha value. For instance, tint(255, 128) * will make an image 50% transparent (unless <b>colorMode()</b> has been * used).<br /> * <br /> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components.<br /> * <br /> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255.<br /> * <br /> * The <b>tint()</b> function is also used to control the coloring of * textures in 3D. * * ( end auto-generated ) * * @webref image:loading_displaying * @usage web_application * @param rgb color value in hexadecimal notation * @see PGraphics#noTint() * @see PGraphics#image(PImage, float, float, float, float) */ public void tint(int rgb) { if (recorder != null) recorder.tint(rgb); g.tint(rgb); } /** * @param rgb color value in hexadecimal notation * @param alpha opacity of the image */ public void tint(int rgb, float alpha) { if (recorder != null) recorder.tint(rgb, alpha); g.tint(rgb, alpha); } /** * @param gray any valid number */ public void tint(float gray) { if (recorder != null) recorder.tint(gray); g.tint(gray); } public void tint(float gray, float alpha) { if (recorder != null) recorder.tint(gray, alpha); g.tint(gray, alpha); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void tint(float x, float y, float z) { if (recorder != null) recorder.tint(x, y, z); g.tint(x, y, z); } /** * @param z opacity of the image */ public void tint(float x, float y, float z, float a) { if (recorder != null) recorder.tint(x, y, z, a); g.tint(x, y, z, a); } /** * ( begin auto-generated from noFill.xml ) * * Disables filling geometry. If both <b>noStroke()</b> and <b>noFill()</b> * are called, nothing will be drawn to the screen. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @see PGraphics#fill(float, float, float, float) */ public void noFill() { if (recorder != null) recorder.noFill(); g.noFill(); } /** * ( begin auto-generated from fill.xml ) * * Sets the color used to fill shapes. For example, if you run <b>fill(204, * 102, 0)</b>, all subsequent shapes will be filled with orange. This * color is either specified in terms of the RGB or HSB color depending on * the current <b>colorMode()</b> (the default color space is RGB, with * each value in the range from 0 to 255). * <br/> <br/> * When using hexadecimal notation to specify a color, use "#" or "0x" * before the values (e.g. #CCFFAA, 0xFFCCFFAA). The # syntax uses six * digits to specify a color (the way colors are specified in HTML and * CSS). When using the hexadecimal notation starting with "0x", the * hexadecimal value must be specified with eight characters; the first two * characters define the alpha component and the remainder the red, green, * and blue components. * <br/> <br/> * The value for the parameter "gray" must be less than or equal to the * current maximum value as specified by <b>colorMode()</b>. The default * maximum value is 255. * <br/> <br/> * To change the color of an image (or a texture), use tint(). * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param rgb color variable or hex value * @see PGraphics#noFill() * @see PGraphics#stroke(int, float) * @see PGraphics#tint(int, float) * @see PGraphics#background(float, float, float, float) * @see PGraphics#colorMode(int, float, float, float, float) */ public void fill(int rgb) { if (recorder != null) recorder.fill(rgb); g.fill(rgb); } /** * @param alpha opacity of the fill */ public void fill(int rgb, float alpha) { if (recorder != null) recorder.fill(rgb, alpha); g.fill(rgb, alpha); } /** * @param gray number specifying value between white and black */ public void fill(float gray) { if (recorder != null) recorder.fill(gray); g.fill(gray); } public void fill(float gray, float alpha) { if (recorder != null) recorder.fill(gray, alpha); g.fill(gray, alpha); } public void fill(float x, float y, float z) { if (recorder != null) recorder.fill(x, y, z); g.fill(x, y, z); } /** * @param a opacity of the fill */ public void fill(float x, float y, float z, float a) { if (recorder != null) recorder.fill(x, y, z, a); g.fill(x, y, z, a); } /** * ( begin auto-generated from ambient.xml ) * * Sets the ambient reflectance for shapes drawn to the screen. This is * combined with the ambient light component of environment. The color * components set through the parameters define the reflectance. For * example in the default color mode, setting v1=255, v2=126, v3=0, would * cause all the red light to reflect and half of the green light to * reflect. Used in combination with <b>emissive()</b>, <b>specular()</b>, * and <b>shininess()</b> in setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#emissive(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void ambient(int rgb) { if (recorder != null) recorder.ambient(rgb); g.ambient(rgb); } /** * @param gray number specifying value between white and black */ public void ambient(float gray) { if (recorder != null) recorder.ambient(gray); g.ambient(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void ambient(float x, float y, float z) { if (recorder != null) recorder.ambient(x, y, z); g.ambient(x, y, z); } /** * ( begin auto-generated from specular.xml ) * * Sets the specular color of the materials used for shapes drawn to the * screen, which sets the color of hightlights. Specular refers to light * which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light). Used in combination * with <b>emissive()</b>, <b>ambient()</b>, and <b>shininess()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#lightSpecular(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#emissive(float, float, float) * @see PGraphics#shininess(float) */ public void specular(int rgb) { if (recorder != null) recorder.specular(rgb); g.specular(rgb); } /** * gray number specifying value between white and black */ public void specular(float gray) { if (recorder != null) recorder.specular(gray); g.specular(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void specular(float x, float y, float z) { if (recorder != null) recorder.specular(x, y, z); g.specular(x, y, z); } /** * ( begin auto-generated from shininess.xml ) * * Sets the amount of gloss in the surface of shapes. Used in combination * with <b>ambient()</b>, <b>specular()</b>, and <b>emissive()</b> in * setting the material properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param shine degree of shininess * @see PGraphics#emissive(float, float, float) * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) */ public void shininess(float shine) { if (recorder != null) recorder.shininess(shine); g.shininess(shine); } /** * ( begin auto-generated from emissive.xml ) * * Sets the emissive color of the material used for drawing shapes drawn to * the screen. Used in combination with <b>ambient()</b>, * <b>specular()</b>, and <b>shininess()</b> in setting the material * properties of shapes. * * ( end auto-generated ) * * @webref lights_camera:material_properties * @usage web_application * @param rgb color to set * @see PGraphics#ambient(float, float, float) * @see PGraphics#specular(float, float, float) * @see PGraphics#shininess(float) */ public void emissive(int rgb) { if (recorder != null) recorder.emissive(rgb); g.emissive(rgb); } /** * gray number specifying value between white and black */ public void emissive(float gray) { if (recorder != null) recorder.emissive(gray); g.emissive(gray); } /** * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) */ public void emissive(float x, float y, float z) { if (recorder != null) recorder.emissive(x, y, z); g.emissive(x, y, z); } /** * ( begin auto-generated from lights.xml ) * * Sets the default ambient light, directional light, falloff, and specular * values. The defaults are ambientLight(128, 128, 128) and * directionalLight(128, 128, 128, 0, 0, -1), lightFalloff(1, 0, 0), and * lightSpecular(0, 0, 0). Lights need to be included in the draw() to * remain persistent in a looping program. Placing them in the setup() of a * looping program will cause them to only have an effect the first time * through the loop. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#noLights() */ public void lights() { if (recorder != null) recorder.lights(); g.lights(); } /** * ( begin auto-generated from noLights.xml ) * * Disable all lighting. Lighting is turned off by default and enabled with * the <b>lights()</b> function. This function can be used to disable * lighting so that 2D geometry (which does not require lighting) can be * drawn after a set of lighted 3D geometry. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @see PGraphics#lights() */ public void noLights() { if (recorder != null) recorder.noLights(); g.noLights(); } /** * ( begin auto-generated from ambientLight.xml ) * * Adds an ambient light. Ambient light doesn't come from a specific * direction, the rays have light have bounced around so much that objects * are evenly lit from all sides. Ambient lights are almost always used in * combination with other types of lights. Lights need to be included in * the <b>draw()</b> to remain persistent in a looping program. Placing * them in the <b>setup()</b> of a looping program will cause them to only * have an effect the first time through the loop. The effect of the * parameters is determined by the current color mode. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void ambientLight(float red, float green, float blue) { if (recorder != null) recorder.ambientLight(red, green, blue); g.ambientLight(red, green, blue); } /** * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light */ public void ambientLight(float red, float green, float blue, float x, float y, float z) { if (recorder != null) recorder.ambientLight(red, green, blue, x, y, z); g.ambientLight(red, green, blue, x, y, z); } /** * ( begin auto-generated from directionalLight.xml ) * * Adds a directional light. Directional light comes from one direction and * is stronger when hitting a surface squarely and weaker if it hits at a a * gentle angle. After hitting a surface, a directional lights scatters in * all directions. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>nx</b>, <b>ny</b>, and <b>nz</b> parameters specify the * direction the light is facing. For example, setting <b>ny</b> to -1 will * cause the geometry to be lit from below (the light is facing directly upward). * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param nx direction along the x-axis * @param ny direction along the y-axis * @param nz direction along the z-axis * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void directionalLight(float red, float green, float blue, float nx, float ny, float nz) { if (recorder != null) recorder.directionalLight(red, green, blue, nx, ny, nz); g.directionalLight(red, green, blue, nx, ny, nz); } /** * ( begin auto-generated from pointLight.xml ) * * Adds a point light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters set the position * of the light. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void pointLight(float red, float green, float blue, float x, float y, float z) { if (recorder != null) recorder.pointLight(red, green, blue, x, y, z); g.pointLight(red, green, blue, x, y, z); } /** * ( begin auto-generated from spotLight.xml ) * * Adds a spot light. Lights need to be included in the <b>draw()</b> to * remain persistent in a looping program. Placing them in the * <b>setup()</b> of a looping program will cause them to only have an * effect the first time through the loop. The affect of the <b>v1</b>, * <b>v2</b>, and <b>v3</b> parameters is determined by the current color * mode. The <b>x</b>, <b>y</b>, and <b>z</b> parameters specify the * position of the light and <b>nx</b>, <b>ny</b>, <b>nz</b> specify the * direction or light. The <b>angle</b> parameter affects angle of the * spotlight cone. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param red red or hue value (depending on current color mode) * @param green green or saturation value (depending on current color mode) * @param blue blue or brightness value (depending on current color mode) * @param x x-coordinate of the light * @param y y-coordinate of the light * @param z z-coordinate of the light * @param nx direction along the x axis * @param ny direction along the y axis * @param nz direction along the z axis * @param angle angle of the spotlight cone * @param concentration exponent determining the center bias of the cone * @see PGraphics#lights() * @see PGraphics#directionalLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#ambientLight(float, float, float, float, float, float) */ public void spotLight(float red, float green, float blue, float x, float y, float z, float nx, float ny, float nz, float angle, float concentration) { if (recorder != null) recorder.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); g.spotLight(red, green, blue, x, y, z, nx, ny, nz, angle, concentration); } /** * ( begin auto-generated from lightFalloff.xml ) * * Sets the falloff rates for point lights, spot lights, and ambient * lights. The parameters are used to determine the falloff with the * following equation:<br /><br />d = distance from light position to * vertex position<br />falloff = 1 / (CONSTANT + d * LINEAR + (d*d) * * QUADRATIC)<br /><br />Like <b>fill()</b>, it affects only the elements * which are created after it in the code. The default value if * <b>LightFalloff(1.0, 0.0, 0.0)</b>. Thinking about an ambient light with * a falloff can be tricky. It is used, for example, if you wanted a region * of your scene to be lit ambiently one color and another region to be lit * ambiently by another color, you would use an ambient light with location * and falloff. You can think of it as a point light that doesn't care * which direction a surface is facing. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param constant constant value or determining falloff * @param linear linear value for determining falloff * @param quadratic quadratic value for determining falloff * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) * @see PGraphics#lightSpecular(float, float, float) */ public void lightFalloff(float constant, float linear, float quadratic) { if (recorder != null) recorder.lightFalloff(constant, linear, quadratic); g.lightFalloff(constant, linear, quadratic); } /** * ( begin auto-generated from lightSpecular.xml ) * * Sets the specular color for lights. Like <b>fill()</b>, it affects only * the elements which are created after it in the code. Specular refers to * light which bounces off a surface in a perferred direction (rather than * bouncing in all directions like a diffuse light) and is used for * creating highlights. The specular quality of a light interacts with the * specular material qualities set through the <b>specular()</b> and * <b>shininess()</b> functions. * * ( end auto-generated ) * * @webref lights_camera:lights * @usage web_application * @param x red or hue value (depending on current color mode) * @param y green or saturation value (depending on current color mode) * @param z blue or brightness value (depending on current color mode) * @see PGraphics#specular(float, float, float) * @see PGraphics#lights() * @see PGraphics#ambientLight(float, float, float, float, float, float) * @see PGraphics#pointLight(float, float, float, float, float, float) * @see PGraphics#spotLight(float, float, float, float, float, float, float, float, float, float, float) */ public void lightSpecular(float x, float y, float z) { if (recorder != null) recorder.lightSpecular(x, y, z); g.lightSpecular(x, y, z); } /** * ( begin auto-generated from background.xml ) * * The <b>background()</b> function sets the color used for the background * of the Processing window. The default background is light gray. In the * <b>draw()</b> function, the background color is used to clear the * display window at the beginning of each frame. * <br/> <br/> * An image can also be used as the background for a sketch, however its * width and height must be the same size as the sketch window. To resize * an image 'b' to the size of the sketch window, use b.resize(width, height). * <br/> <br/> * Images used as background will ignore the current <b>tint()</b> setting. * <br/> <br/> * It is not possible to use transparency (alpha) in background colors with * the main drawing surface, however they will work properly with <b>createGraphics()</b>. * * ( end auto-generated ) * * <h3>Advanced</h3> * <p>Clear the background with a color that includes an alpha value. This can * only be used with objects created by createGraphics(), because the main * drawing surface cannot be set transparent.</p> * <p>It might be tempting to use this function to partially clear the screen * on each frame, however that's not how this function works. When calling * background(), the pixels will be replaced with pixels that have that level * of transparency. To do a semi-transparent overlay, use fill() with alpha * and draw a rectangle.</p> * * @webref color:setting * @usage web_application * @param rgb any value of the color datatype * @see PGraphics#stroke(float) * @see PGraphics#fill(float) * @see PGraphics#tint(float) * @see PGraphics#colorMode(int) */ public void background(int rgb) { if (recorder != null) recorder.background(rgb); g.background(rgb); } /** * @param alpha opacity of the background */ public void background(int rgb, float alpha) { if (recorder != null) recorder.background(rgb, alpha); g.background(rgb, alpha); } /** * @param gray specifies a value between white and black */ public void background(float gray) { if (recorder != null) recorder.background(gray); g.background(gray); } public void background(float gray, float alpha) { if (recorder != null) recorder.background(gray, alpha); g.background(gray, alpha); } /** * @param x red or hue value (depending on the current color mode) * @param y green or saturation value (depending on the current color mode) * @param z blue or brightness value (depending on the current color mode) */ public void background(float x, float y, float z) { if (recorder != null) recorder.background(x, y, z); g.background(x, y, z); } /** * @param a opacity of the background */ public void background(float x, float y, float z, float a) { if (recorder != null) recorder.background(x, y, z, a); g.background(x, y, z, a); } /** * @param image PImage to set as background (must be same size as the program) * Takes an RGB or ARGB image and sets it as the background. * The width and height of the image must be the same size as the sketch. * Use image.resize(width, height) to make short work of such a task. * <P> * Note that even if the image is set as RGB, the high 8 bits of each pixel * should be set opaque (0xFF000000), because the image data will be copied * directly to the screen, and non-opaque background images may have strange * behavior. Using image.filter(OPAQUE) will handle this easily. * <P> * When using 3D, this will also clear the zbuffer (if it exists). */ public void background(PImage image) { if (recorder != null) recorder.background(image); g.background(image); } /** * ( begin auto-generated from colorMode.xml ) * * Changes the way Processing interprets color data. By default, the * parameters for <b>fill()</b>, <b>stroke()</b>, <b>background()</b>, and * <b>color()</b> are defined by values between 0 and 255 using the RGB * color model. The <b>colorMode()</b> function is used to change the * numerical range used for specifying colors and to switch color systems. * For example, calling <b>colorMode(RGB, 1.0)</b> will specify that values * are specified between 0 and 1. The limits for defining colors are * altered by setting the parameters range1, range2, range3, and range 4. * * ( end auto-generated ) * * @webref color:setting * @usage web_application * @param mode Either RGB or HSB, corresponding to Red/Green/Blue and Hue/Saturation/Brightness * @see PGraphics#background(float) * @see PGraphics#fill(float) * @see PGraphics#stroke(float) */ public void colorMode(int mode) { if (recorder != null) recorder.colorMode(mode); g.colorMode(mode); } /** * @param max range for all color elements */ public void colorMode(int mode, float max) { if (recorder != null) recorder.colorMode(mode, max); g.colorMode(mode, max); } /** * @param maxX range for the red or hue depending on the current color mode * @param maxY range for the green or saturation depending on the current color mode * @param maxZ range for the blue or brightness depending on the current color mode */ public void colorMode(int mode, float maxX, float maxY, float maxZ) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ); g.colorMode(mode, maxX, maxY, maxZ); } /** * @param maxA range for the alpha */ public void colorMode(int mode, float maxX, float maxY, float maxZ, float maxA) { if (recorder != null) recorder.colorMode(mode, maxX, maxY, maxZ, maxA); g.colorMode(mode, maxX, maxY, maxZ, maxA); } /** * ( begin auto-generated from alpha.xml ) * * Extracts the alpha value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float alpha(int what) { return g.alpha(what); } /** * ( begin auto-generated from red.xml ) * * Extracts the red value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The red() function * is easy to use and undestand, but is slower than another technique. To * achieve the same results when working in <b>colorMode(RGB, 255)</b>, but * with greater speed, use the &gt;&gt; (right shift) operator with a bit * mask. For example, the following two lines of code are equivalent:<br * /><pre>float r1 = red(myColor);<br />float r2 = myColor &gt;&gt; 16 * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float red(int what) { return g.red(what); } /** * ( begin auto-generated from green.xml ) * * Extracts the green value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>green()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use the &gt;&gt; (right shift) * operator with a bit mask. For example, the following two lines of code * are equivalent:<br /><pre>float r1 = green(myColor);<br />float r2 = * myColor &gt;&gt; 8 &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float green(int what) { return g.green(what); } /** * ( begin auto-generated from blue.xml ) * * Extracts the blue value from a color, scaled to match current * <b>colorMode()</b>. This value is always returned as a float so be * careful not to assign it to an int value.<br /><br />The <b>blue()</b> * function is easy to use and undestand, but is slower than another * technique. To achieve the same results when working in <b>colorMode(RGB, * 255)</b>, but with greater speed, use a bit mask to remove the other * color components. For example, the following two lines of code are * equivalent:<br /><pre>float r1 = blue(myColor);<br />float r2 = myColor * &amp; 0xFF;</pre> * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) * @see_external rightshift */ public final float blue(int what) { return g.blue(what); } /** * ( begin auto-generated from hue.xml ) * * Extracts the hue value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#saturation(int) * @see PGraphics#brightness(int) */ public final float hue(int what) { return g.hue(what); } /** * ( begin auto-generated from saturation.xml ) * * Extracts the saturation value from a color. * * ( end auto-generated ) * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#brightness(int) */ public final float saturation(int what) { return g.saturation(what); } /** * ( begin auto-generated from brightness.xml ) * * Extracts the brightness value from a color. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param what any value of the color datatype * @see PGraphics#red(int) * @see PGraphics#green(int) * @see PGraphics#blue(int) * @see PGraphics#alpha(int) * @see PGraphics#hue(int) * @see PGraphics#saturation(int) */ public final float brightness(int what) { return g.brightness(what); } /** * ( begin auto-generated from lerpColor.xml ) * * Calculates a color or colors between two color at a specific increment. * The <b>amt</b> parameter is the amount to interpolate between the two * values where 0.0 equal to the first point, 0.1 is very near the first * point, 0.5 is half-way in between, etc. * * ( end auto-generated ) * * @webref color:creating_reading * @usage web_application * @param c1 interpolate from this color * @param c2 interpolate to this color * @param amt between 0.0 and 1.0 * @see PImage#blendColor(int, int, int) * @see PGraphics#color(float, float, float, float) */ public int lerpColor(int c1, int c2, float amt) { return g.lerpColor(c1, c2, amt); } /** * @nowebref * Interpolate between two colors. Like lerp(), but for the * individual color components of a color supplied as an int value. */ static public int lerpColor(int c1, int c2, float amt, int mode) { return PGraphics.lerpColor(c1, c2, amt, mode); } /** * Display a warning that the specified method is only available with 3D. * @param method The method name (no parentheses) */ static public void showDepthWarning(String method) { PGraphics.showDepthWarning(method); } /** * Display a warning that the specified method that takes x, y, z parameters * can only be used with x and y parameters in this renderer. * @param method The method name (no parentheses) */ static public void showDepthWarningXYZ(String method) { PGraphics.showDepthWarningXYZ(method); } /** * Display a warning that the specified method is simply unavailable. */ static public void showMethodWarning(String method) { PGraphics.showMethodWarning(method); } /** * Error that a particular variation of a method is unavailable (even though * other variations are). For instance, if vertex(x, y, u, v) is not * available, but vertex(x, y) is just fine. */ static public void showVariationWarning(String str) { PGraphics.showVariationWarning(str); } /** * Display a warning that the specified method is not implemented, meaning * that it could be either a completely missing function, although other * variations of it may still work properly. */ static public void showMissingWarning(String method) { PGraphics.showMissingWarning(method); } /** * Return true if this renderer should be drawn to the screen. Defaults to * returning true, since nearly all renderers are on-screen beasts. But can * be overridden for subclasses like PDF so that a window doesn't open up. * <br/> <br/> * A better name? showFrame, displayable, isVisible, visible, shouldDisplay, * what to call this? */ public boolean displayable() { return g.displayable(); } /** * Return true if this renderer does rendering through OpenGL. Defaults to false. */ public boolean isGL() { return g.isGL(); } public PShape createShape() { return g.createShape(); } public PShape createShape(int type) { return g.createShape(type); } public PShape createShape(int kind, float... p) { return g.createShape(kind, p); } public void blendMode(int mode) { if (recorder != null) recorder.blendMode(mode); g.blendMode(mode); } public void delete() { if (recorder != null) recorder.delete(); g.delete(); } /** * Store data of some kind for a renderer that requires extra metadata of * some kind. Usually this is a renderer-specific representation of the * image data, for instance a BufferedImage with tint() settings applied for * PGraphicsJava2D, or resized image data and OpenGL texture indices for * PGraphicsOpenGL. * @param renderer The PGraphics renderer associated to the image * @param storage The metadata required by the renderer */ public void setCache(PGraphics renderer, Object storage) { if (recorder != null) recorder.setCache(renderer, storage); g.setCache(renderer, storage); } /** * Get cache storage data for the specified renderer. Because each renderer * will cache data in different formats, it's necessary to store cache data * keyed by the renderer object. Otherwise, attempting to draw the same * image to both a PGraphicsJava2D and a PGraphicsOpenGL will cause errors. * @param renderer The PGraphics renderer associated to the image * @return metadata stored for the specified renderer */ public Object getCache(PGraphics renderer) { return g.getCache(renderer); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose cache data should be removed */ public void removeCache(PGraphics renderer) { if (recorder != null) recorder.removeCache(renderer); g.removeCache(renderer); } /** * Store parameters for a renderer that requires extra metadata of * some kind. * @param renderer The PGraphics renderer associated to the image * @param storage The parameters required by the renderer */ public void setParams(PGraphics renderer, Object params) { if (recorder != null) recorder.setParams(renderer, params); g.setParams(renderer, params); } /** * Get the parameters for the specified renderer. * @param renderer The PGraphics renderer associated to the image * @return parameters stored for the specified renderer */ public Object getParams(PGraphics renderer) { return g.getParams(renderer); } /** * Remove information associated with this renderer from the cache, if any. * @param renderer The PGraphics renderer whose parameters should be removed */ public void removeParams(PGraphics renderer) { if (recorder != null) recorder.removeParams(renderer); g.removeParams(renderer); } /** * ( begin auto-generated from PImage_get.xml ) * * Reads the color of any pixel or grabs a section of an image. If no * parameters are specified, the entire image is returned. Use the <b>x</b> * and <b>y</b> parameters to get the value of one pixel. Get a section of * the display window by specifying an additional <b>width</b> and * <b>height</b> parameter. When getting an image, the <b>x</b> and * <b>y</b> parameters define the coordinates for the upper-left corner of * the image, regardless of the current <b>imageMode()</b>.<br /> * <br /> * If the pixel requested is outside of the image window, black is * returned. The numbers returned are scaled according to the current color * ranges, but only RGB values are returned by this function. For example, * even though you may have drawn a shape with <b>colorMode(HSB)</b>, the * numbers returned will be in RGB format.<br /> * <br /> * Getting the color of a single pixel with <b>get(x, y)</b> is easy, but * not as fast as grabbing the data directly from <b>pixels[]</b>. The * equivalent statement to <b>get(x, y)</b> using <b>pixels[]</b> is * <b>pixels[y*width+x]</b>. See the reference for <b>pixels[]</b> for more information. * * ( end auto-generated ) * * <h3>Advanced</h3> * Returns an ARGB "color" type (a packed 32 bit int with the color. * If the coordinate is outside the image, zero is returned * (black, but completely transparent). * <P> * If the image is in RGB format (i.e. on a PVideo object), * the value will get its high bits set, just to avoid cases where * they haven't been set already. * <P> * If the image is in ALPHA format, this returns a white with its * alpha value set. * <P> * This function is included primarily for beginners. It is quite * slow because it has to check to see if the x, y that was provided * is inside the bounds, and then has to check to see what image * type it is. If you want things to be more efficient, access the * pixels[] array directly. * * @webref image:pixels * @brief Reads the color of any pixel or grabs a rectangle of pixels * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @see PApplet#set(int, int, int) * @see PApplet#pixels * @see PApplet#copy(PImage, int, int, int, int, int, int, int, int) */ public int get(int x, int y) { return g.get(x, y); } /** * @param w width of pixel rectangle to get * @param h height of pixel rectangle to get */ public PImage get(int x, int y, int w, int h) { return g.get(x, y, w, h); } /** * Returns a copy of this PImage. Equivalent to get(0, 0, width, height). */ public PImage get() { return g.get(); } /** * ( begin auto-generated from PImage_set.xml ) * * Changes the color of any pixel or writes an image directly into the * display window.<br /> * <br /> * The <b>x</b> and <b>y</b> parameters specify the pixel to change and the * <b>color</b> parameter specifies the color value. The color parameter is * affected by the current color mode (the default is RGB values from 0 to * 255). When setting an image, the <b>x</b> and <b>y</b> parameters define * the coordinates for the upper-left corner of the image, regardless of * the current <b>imageMode()</b>. * <br /><br /> * Setting the color of a single pixel with <b>set(x, y)</b> is easy, but * not as fast as putting the data directly into <b>pixels[]</b>. The * equivalent statement to <b>set(x, y, #000000)</b> using <b>pixels[]</b> * is <b>pixels[y*width+x] = #000000</b>. See the reference for * <b>pixels[]</b> for more information. * * ( end auto-generated ) * * @webref image:pixels * @brief writes a color to any pixel or writes an image into another * @usage web_application * @param x x-coordinate of the pixel * @param y y-coordinate of the pixel * @param c any value of the color datatype * @see PImage#get(int, int, int, int) * @see PImage#pixels * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) */ public void set(int x, int y, int c) { if (recorder != null) recorder.set(x, y, c); g.set(x, y, c); } /** * <h3>Advanced</h3> * Efficient method of drawing an image's pixels directly to this surface. * No variations are employed, meaning that any scale, tint, or imageMode * settings will be ignored. * * @param src image to draw on screen */ public void set(int x, int y, PImage src) { if (recorder != null) recorder.set(x, y, src); g.set(x, y, src); } /** * ( begin auto-generated from PImage_mask.xml ) * * Masks part of an image from displaying by loading another image and * using it as an alpha channel. This mask image should only contain * grayscale data, but only the blue color channel is used. The mask image * needs to be the same size as the image to which it is applied.<br /> * <br /> * In addition to using a mask image, an integer array containing the alpha * channel data can be specified directly. This method is useful for * creating dynamically generated alpha masks. This array must be of the * same length as the target image's pixels array and should contain only * grayscale data of values between 0-255. * * ( end auto-generated ) * * <h3>Advanced</h3> * * Set alpha channel for an image. Black colors in the source * image will make the destination image completely transparent, * and white will make things fully opaque. Gray values will * be in-between steps. * <P> * Strictly speaking the "blue" value from the source image is * used as the alpha color. For a fully grayscale image, this * is correct, but for a color image it's not 100% accurate. * For a more accurate conversion, first use filter(GRAY) * which will make the image into a "correct" grayscale by * performing a proper luminance-based conversion. * * @webref pimage:method * @usage web_application * @brief Masks part of an image with another image as an alpha channel * @param maskArray array of integers used as the alpha channel, needs to be the same length as the image's pixel array */ public void mask(int maskArray[]) { if (recorder != null) recorder.mask(maskArray); g.mask(maskArray); } /** * @param maskImg a PImage object used as the alpha channel for "img", must be same dimensions as "img" */ public void mask(PImage maskImg) { if (recorder != null) recorder.mask(maskImg); g.mask(maskImg); } public void filter(int kind) { if (recorder != null) recorder.filter(kind); g.filter(kind); } /** * ( begin auto-generated from PImage_filter.xml ) * * Filters an image as defined by one of the following modes:<br /><br * />THRESHOLD - converts the image to black and white pixels depending if * they are above or below the threshold defined by the level parameter. * The level must be between 0.0 (black) and 1.0(white). If no level is * specified, 0.5 is used.<br /> * <br /> * GRAY - converts any colors in the image to grayscale equivalents<br /> * <br /> * INVERT - sets each pixel to its inverse value<br /> * <br /> * POSTERIZE - limits each channel of the image to the number of colors * specified as the level parameter<br /> * <br /> * BLUR - executes a Guassian blur with the level parameter specifying the * extent of the blurring. If no level parameter is used, the blur is * equivalent to Guassian blur of radius 1<br /> * <br /> * OPAQUE - sets the alpha channel to entirely opaque<br /> * <br /> * ERODE - reduces the light areas with the amount defined by the level * parameter<br /> * <br /> * DILATE - increases the light areas with the amount defined by the level parameter * * ( end auto-generated ) * * <h3>Advanced</h3> * Method to apply a variety of basic filters to this image. * <P> * <UL> * <LI>filter(BLUR) provides a basic blur. * <LI>filter(GRAY) converts the image to grayscale based on luminance. * <LI>filter(INVERT) will invert the color components in the image. * <LI>filter(OPAQUE) set all the high bits in the image to opaque * <LI>filter(THRESHOLD) converts the image to black and white. * <LI>filter(DILATE) grow white/light areas * <LI>filter(ERODE) shrink white/light areas * </UL> * Luminance conversion code contributed by * <A HREF="http://www.toxi.co.uk">toxi</A> * <P/> * Gaussian blur code contributed by * <A HREF="http://incubator.quasimondo.com">Mario Klingemann</A> * * @webref image:pixels * @brief Converts the image to grayscale or black and white * @usage web_application * @param kind Either THRESHOLD, GRAY, INVERT, POSTERIZE, BLUR, OPAQUE, ERODE, or DILATE * @param param unique for each, see above */ public void filter(int kind, float param) { if (recorder != null) recorder.filter(kind, param); g.filter(kind, param); } /** * ( begin auto-generated from PImage_copy.xml ) * * Copies a region of pixels from one image into another. If the source and * destination regions aren't the same size, it will automatically resize * source pixels to fit the specified target region. No alpha information * is used in the process, however if the source image has an alpha channel * set, it will be copied as well. * <br /><br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies the entire image * @usage web_application * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destination's upper left corner * @param dy Y coordinate of the destination's upper left corner * @param dw destination image width * @param dh destination image height * @see PGraphics#alpha(int) * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) */ public void copy(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(sx, sy, sw, sh, dx, dy, dw, dh); g.copy(sx, sy, sw, sh, dx, dy, dw, dh); } /** * @param src an image variable referring to the source image. */ public void copy(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh) { if (recorder != null) recorder.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); g.copy(src, sx, sy, sw, sh, dx, dy, dw, dh); } /** * ( begin auto-generated from blendColor.xml ) * * Blends two color values together based on the blending mode given as the * <b>MODE</b> parameter. The possible modes are described in the reference * for the <b>blend()</b> function. * * ( end auto-generated ) * <h3>Advanced</h3> * <UL> * <LI>REPLACE - destination colour equals colour of source pixel: C = A. * Sometimes called "Normal" or "Copy" in other software. * * <LI>BLEND - linear interpolation of colours: * <TT>C = A*factor + B</TT> * * <LI>ADD - additive blending with white clip: * <TT>C = min(A*factor + B, 255)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Burn", * and Director calls it "Add Pin". * * <LI>SUBTRACT - substractive blend with black clip: * <TT>C = max(B - A*factor, 0)</TT>. * Clipped to 0..255, Photoshop calls this "Linear Dodge", * and Director calls it "Subtract Pin". * * <LI>DARKEST - only the darkest colour succeeds: * <TT>C = min(A*factor, B)</TT>. * Illustrator calls this "Darken". * * <LI>LIGHTEST - only the lightest colour succeeds: * <TT>C = max(A*factor, B)</TT>. * Illustrator calls this "Lighten". * * <LI>DIFFERENCE - subtract colors from underlying image. * * <LI>EXCLUSION - similar to DIFFERENCE, but less extreme. * * <LI>MULTIPLY - Multiply the colors, result will always be darker. * * <LI>SCREEN - Opposite multiply, uses inverse values of the colors. * * <LI>OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values. * * <LI>HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower. * * <LI>SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh. * * <LI>DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop. * * <LI>BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop. * </UL> * <P>A useful reference for blending modes and their algorithms can be * found in the <A HREF="http://www.w3.org/TR/SVG12/rendering.html">SVG</A> * specification.</P> * <P>It is important to note that Processing uses "fast" code, not * necessarily "correct" code. No biggie, most software does. A nitpicker * can find numerous "off by 1 division" problems in the blend code where * <TT>&gt;&gt;8</TT> or <TT>&gt;&gt;7</TT> is used when strictly speaking * <TT>/255.0</T> or <TT>/127.0</TT> should have been used.</P> * <P>For instance, exclusion (not intended for real-time use) reads * <TT>r1 + r2 - ((2 * r1 * r2) / 255)</TT> because <TT>255 == 1.0</TT> * not <TT>256 == 1.0</TT>. In other words, <TT>(255*255)>>8</TT> is not * the same as <TT>(255*255)/255</TT>. But for real-time use the shifts * are preferrable, and the difference is insignificant for applications * built with Processing.</P> * * @webref color:creating_reading * @usage web_application * @param c1 the first color to blend * @param c2 the second color to blend * @param mode either BLEND, ADD, SUBTRACT, DARKEST, LIGHTEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, or BURN * @see PImage#blend(PImage, int, int, int, int, int, int, int, int, int) * @see PApplet#color(float, float, float, float) */ static public int blendColor(int c1, int c2, int mode) { return PGraphics.blendColor(c1, c2, mode); } public void blend(int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(sx, sy, sw, sh, dx, dy, dw, dh, mode); } /** * ( begin auto-generated from PImage_blend.xml ) * * Blends a region of pixels into the image specified by the <b>img</b> * parameter. These copies utilize full alpha channel support and a choice * of the following modes to blend the colors of source pixels (A) with the * ones of pixels in the destination image (B):<br /> * <br /> * BLEND - linear interpolation of colours: C = A*factor + B<br /> * <br /> * ADD - additive blending with white clip: C = min(A*factor + B, 255)<br /> * <br /> * SUBTRACT - subtractive blending with black clip: C = max(B - A*factor, * 0)<br /> * <br /> * DARKEST - only the darkest colour succeeds: C = min(A*factor, B)<br /> * <br /> * LIGHTEST - only the lightest colour succeeds: C = max(A*factor, B)<br /> * <br /> * DIFFERENCE - subtract colors from underlying image.<br /> * <br /> * EXCLUSION - similar to DIFFERENCE, but less extreme.<br /> * <br /> * MULTIPLY - Multiply the colors, result will always be darker.<br /> * <br /> * SCREEN - Opposite multiply, uses inverse values of the colors.<br /> * <br /> * OVERLAY - A mix of MULTIPLY and SCREEN. Multiplies dark values, * and screens light values.<br /> * <br /> * HARD_LIGHT - SCREEN when greater than 50% gray, MULTIPLY when lower.<br /> * <br /> * SOFT_LIGHT - Mix of DARKEST and LIGHTEST. * Works like OVERLAY, but not as harsh.<br /> * <br /> * DODGE - Lightens light tones and increases contrast, ignores darks. * Called "Color Dodge" in Illustrator and Photoshop.<br /> * <br /> * BURN - Darker areas are applied, increasing contrast, ignores lights. * Called "Color Burn" in Illustrator and Photoshop.<br /> * <br /> * All modes use the alpha information (highest byte) of source image * pixels as the blending factor. If the source and destination regions are * different sizes, the image will be automatically resized to match the * destination size. If the <b>srcImg</b> parameter is not used, the * display window is used as the source image.<br /> * <br /> * As of release 0149, this function ignores <b>imageMode()</b>. * * ( end auto-generated ) * * @webref image:pixels * @brief Copies a pixel or rectangle of pixels using different blending modes * @param src an image variable referring to the source image * @param sx X coordinate of the source's upper left corner * @param sy Y coordinate of the source's upper left corner * @param sw source image width * @param sh source image height * @param dx X coordinate of the destinations's upper left corner * @param dy Y coordinate of the destinations's upper left corner * @param dw destination image width * @param dh destination image height * @param mode Either BLEND, ADD, SUBTRACT, LIGHTEST, DARKEST, DIFFERENCE, EXCLUSION, MULTIPLY, SCREEN, OVERLAY, HARD_LIGHT, SOFT_LIGHT, DODGE, BURN * * @see PApplet#alpha(int) * @see PImage#copy(PImage, int, int, int, int, int, int, int, int) * @see PImage#blendColor(int,int,int) */ public void blend(PImage src, int sx, int sy, int sw, int sh, int dx, int dy, int dw, int dh, int mode) { if (recorder != null) recorder.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); g.blend(src, sx, sy, sw, sh, dx, dy, dw, dh, mode); } }
diff --git a/INF101/studieprogresjon/Entity.java b/INF101/studieprogresjon/Entity.java index 629378e..52619d6 100644 --- a/INF101/studieprogresjon/Entity.java +++ b/INF101/studieprogresjon/Entity.java @@ -1,112 +1,114 @@ package studieprogresjon; import studieprogresjon.Position; /** * Abstract Entity class. * Common stuff for game entities * * @package studieprogresjon * @author Raymond Julin */ public abstract class Entity { Position pos; boolean collided = false; Entity collidedWith; public abstract char getSymbol(); public Entity(Position p) { this.pos = p; } /** * Set position for Entity * * @return void * @param Position p */ public void setPosition(Position p) { this.pos = p; } /** * Return position for Entity * * @return Position */ public Position getPosition() { return this.pos; } /** * Return x position for Entity * * @return int */ public int getX() { return pos.getX(); } /** * Return y position for Entity * * @return int */ public int getY() { return pos.getY(); } /** * State whether Entity is collided or not * * @return boolean */ public boolean isCollided() { return this.collided; } /** * Set Entity to be collided * * @return void * @param boolean state */ public void setCollided(boolean state) { this.collided = state; } /** * Set Entity to be collided with following entity * * @return void * @param Entity e */ public void setCollidedWith(Entity e) { this.collidedWith = e; } public Entity getCollidedWith() { return this.collidedWith; } /** * Check for collision against table of other Entities * * @return boolean * @param Entity[] entities */ public boolean checkCollision(Entity[] entities) { for (Entity e: entities) { - if (this.getPosition().equals(e.getPosition())) { - if (this != e) { - this.setCollidedWith(e); - this.setCollided(true); - return true; + if (e instanceof studieprogresjon.Entity) { + if (this.getPosition().equals(e.getPosition())) { + if (this != e) { + this.setCollidedWith(e); + this.setCollided(true); + return true; + } } } } return false; } }
true
true
public boolean checkCollision(Entity[] entities) { for (Entity e: entities) { if (this.getPosition().equals(e.getPosition())) { if (this != e) { this.setCollidedWith(e); this.setCollided(true); return true; } } } return false; }
public boolean checkCollision(Entity[] entities) { for (Entity e: entities) { if (e instanceof studieprogresjon.Entity) { if (this.getPosition().equals(e.getPosition())) { if (this != e) { this.setCollidedWith(e); this.setCollided(true); return true; } } } } return false; }
diff --git a/src/test/java/functional/com/thoughtworks/twu/TalksHomePage.java b/src/test/java/functional/com/thoughtworks/twu/TalksHomePage.java index 91b00e1..f3f09db 100644 --- a/src/test/java/functional/com/thoughtworks/twu/TalksHomePage.java +++ b/src/test/java/functional/com/thoughtworks/twu/TalksHomePage.java @@ -1,152 +1,152 @@ package functional.com.thoughtworks.twu; import com.thoughtworks.twu.utils.CasLoginLogout; import com.thoughtworks.twu.utils.Talk; import com.thoughtworks.twu.utils.WaitForAjax; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.UUID; import java.util.concurrent.TimeUnit; import static com.thoughtworks.twu.utils.WaitForAjax.*; import static org.hamcrest.CoreMatchers.is; import static org.joda.time.DateTime.now; import static org.junit.Assert.assertThat; import static org.testng.Assert.assertTrue; public class TalksHomePage { public static final int HTTP_PORT = 9191; public static final String HTTP_BASE_URL = "http://localhost:" + HTTP_PORT + "/twu/"; private WebDriver webDriver; private String failMessage; private String successMessage; private String errorCssValue; @Before public void setUp() { webDriver = new FirefoxDriver(); webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); webDriver.get(HTTP_BASE_URL); failMessage = "Please Supply Valid Entries For All Fields"; successMessage="New Talk Successfully Created"; errorCssValue = "rgb(255, 0, 0) 0px 0px 12px 0px"; CasLoginLogout.login(webDriver); } @Test - public void shouldBeAbleToCreateNewTalk() throws InterruptedException { + public void shouldBeAbleToCreateNewTalkWithDescription() throws InterruptedException { JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#my_talks_button').click();"); assertTrue(webDriver.findElement(By.id("new_talk")).isDisplayed()); webDriver.findElement(By.id("new_talk")).click(); assertTrue(webDriver.findElement(By.id("title")).isDisplayed()); webDriver.findElement(By.id("title")).sendKeys(now().toString()); - //webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); + webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); webDriver.findElement(By.id("venue")).sendKeys("Ajanta Ellora"); javascriptExecutor.executeScript("$('#datepicker').val('28/09/2012')"); javascriptExecutor.executeScript("$('#timepicker').val('11:42 AM')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); WaitForAjax(webDriver); WebElement text = webDriver.findElement(By.id("message_box_success")); assertThat(text.getText(), is(successMessage)); } @Test public void shouldBeAbleToCreateNewTalkWithoutDescription() throws Exception { WebElement myTalksButton = webDriver.findElement(By.id("my_talks_button")); myTalksButton.click(); assertTrue(webDriver.findElement(By.id("new_talk")).isDisplayed()); webDriver.findElement(By.id("new_talk")).click(); assertTrue(webDriver.findElement(By.id("title")).isDisplayed()); webDriver.findElement(By.id("title")).sendKeys(now().toString()); webDriver.findElement(By.id("venue")).sendKeys("Ajanta Ellora"); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#datepicker').val('28/09/2012')"); javascriptExecutor.executeScript("$('#timepicker').val('11:42 AM')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); WaitForAjax(webDriver); WebElement text = webDriver.findElement(By.id("message_box_success")); assertThat(text.getText(), is(successMessage)); } @Test public void shouldNotBeAbleToCreateNewTalkWithoutTitle() throws Exception { WebElement myTalksButton = webDriver.findElement(By.id("my_talks_button")); myTalksButton.click(); webDriver.findElement(By.id("new_talk")).click(); webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); webDriver.findElement(By.id("venue")).sendKeys("Ajanta Ellora"); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#datepicker').val('28/09/2012')"); javascriptExecutor.executeScript("$('#timepicker').val('11:42 AM')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); assertThat(webDriver.findElement(By.id("title")).getCssValue("box-shadow"), is(errorCssValue)); } @Test public void shouldNotBeAbleToCreateNewTalkWithoutVenue() throws Exception { WebElement myTalksButton = webDriver.findElement(By.id("my_talks_button")); myTalksButton.click(); webDriver.findElement(By.id("new_talk")).click(); webDriver.findElement(By.id("title")).sendKeys(now().toString()); webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#datepicker').val('28/09/2012')"); javascriptExecutor.executeScript("$('#timepicker').val('11:42 AM')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); assertThat(webDriver.findElement(By.id("venue")).getCssValue("box-shadow"), is(errorCssValue)); } @Test public void shouldNotBeAbleToCreateNewTalkWithoutDate() throws Exception { WebElement myTalksButton = webDriver.findElement(By.id("my_talks_button")); myTalksButton.click(); webDriver.findElement(By.id("new_talk")).click(); webDriver.findElement(By.id("title")).sendKeys(now().toString()); webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); webDriver.findElement(By.id("venue")).sendKeys("Ajanta Ellora"); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#timepicker').val('11:42 AM')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); assertThat(webDriver.findElement(By.id("datepicker")).getCssValue("box-shadow"), is(errorCssValue)); } @Test public void shouldNotBeAbleToCreateNewTalkWithoutTime() throws Exception { WebElement myTalksButton = webDriver.findElement(By.id("my_talks_button")); myTalksButton.click(); webDriver.findElement(By.id("new_talk")).click(); webDriver.findElement(By.id("title")).sendKeys(now().toString()); webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); webDriver.findElement(By.id("venue")).sendKeys("Ajanta Ellora"); JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#datepicker').val('28/09/2012')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); assertThat(webDriver.findElement(By.id("timepicker")).getCssValue("box-shadow"), is(errorCssValue)); } @After public void tearDown() { CasLoginLogout.logout(webDriver); webDriver.close(); } }
false
true
public void shouldBeAbleToCreateNewTalk() throws InterruptedException { JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#my_talks_button').click();"); assertTrue(webDriver.findElement(By.id("new_talk")).isDisplayed()); webDriver.findElement(By.id("new_talk")).click(); assertTrue(webDriver.findElement(By.id("title")).isDisplayed()); webDriver.findElement(By.id("title")).sendKeys(now().toString()); //webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); webDriver.findElement(By.id("venue")).sendKeys("Ajanta Ellora"); javascriptExecutor.executeScript("$('#datepicker').val('28/09/2012')"); javascriptExecutor.executeScript("$('#timepicker').val('11:42 AM')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); WaitForAjax(webDriver); WebElement text = webDriver.findElement(By.id("message_box_success")); assertThat(text.getText(), is(successMessage)); }
public void shouldBeAbleToCreateNewTalkWithDescription() throws InterruptedException { JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver; javascriptExecutor.executeScript("$('#my_talks_button').click();"); assertTrue(webDriver.findElement(By.id("new_talk")).isDisplayed()); webDriver.findElement(By.id("new_talk")).click(); assertTrue(webDriver.findElement(By.id("title")).isDisplayed()); webDriver.findElement(By.id("title")).sendKeys(now().toString()); webDriver.findElement(By.id("description")).sendKeys("Seven wise men"); webDriver.findElement(By.id("venue")).sendKeys("Ajanta Ellora"); javascriptExecutor.executeScript("$('#datepicker').val('28/09/2012')"); javascriptExecutor.executeScript("$('#timepicker').val('11:42 AM')"); javascriptExecutor.executeScript("$('#new_talk_submit').click()"); WaitForAjax(webDriver); WebElement text = webDriver.findElement(By.id("message_box_success")); assertThat(text.getText(), is(successMessage)); }
diff --git a/spring-xd-hadoop/src/test/java/org/springframework/xd/integration/hadoop/config/HdfsOutboundChannelAdapterIntegrationTests.java b/spring-xd-hadoop/src/test/java/org/springframework/xd/integration/hadoop/config/HdfsOutboundChannelAdapterIntegrationTests.java index 5aef01a1b..7efe3f2d2 100644 --- a/spring-xd-hadoop/src/test/java/org/springframework/xd/integration/hadoop/config/HdfsOutboundChannelAdapterIntegrationTests.java +++ b/spring-xd-hadoop/src/test/java/org/springframework/xd/integration/hadoop/config/HdfsOutboundChannelAdapterIntegrationTests.java @@ -1,64 +1,64 @@ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.xd.integration.hadoop.config; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.MessageChannel; /** * @author Mark Fisher * @author Thomas Risberg */ public class HdfsOutboundChannelAdapterIntegrationTests { @Test public void test() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/xd/integration/hadoop/config/HdfsOutboundChannelAdapterIntegrationTests.xml"); MessageChannel channel = context.getBean("hdfsOut", MessageChannel.class); channel.send(MessageBuilder.withPayload("foo").build()); channel.send(MessageBuilder.withPayload("bar").build()); FileSystem fileSystem = context.getBean("hadoopFs", FileSystem.class); String path = context.getBean("path", String.class); context.close(); Path basepath = new Path(path + "/testdir/"); - Path filepath0 = new Path(basepath, "testfile0"); - Path filepath1 = new Path(basepath, "testfile1"); + Path filepath0 = new Path(basepath, "testfile-0"); + Path filepath1 = new Path(basepath, "testfile-1"); assertTrue(fileSystem.exists(basepath)); assertTrue(fileSystem.exists(filepath0)); assertTrue(fileSystem.exists(filepath1)); BufferedReader reader0 = new BufferedReader(new InputStreamReader(fileSystem.open(filepath0))); assertEquals("foo", reader0.readLine()); BufferedReader reader1 = new BufferedReader(new InputStreamReader(fileSystem.open(filepath1))); assertEquals("bar", reader1.readLine()); reader0.close(); reader1.close(); assertTrue(fileSystem.delete(basepath, true)); } }
true
true
public void test() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/xd/integration/hadoop/config/HdfsOutboundChannelAdapterIntegrationTests.xml"); MessageChannel channel = context.getBean("hdfsOut", MessageChannel.class); channel.send(MessageBuilder.withPayload("foo").build()); channel.send(MessageBuilder.withPayload("bar").build()); FileSystem fileSystem = context.getBean("hadoopFs", FileSystem.class); String path = context.getBean("path", String.class); context.close(); Path basepath = new Path(path + "/testdir/"); Path filepath0 = new Path(basepath, "testfile0"); Path filepath1 = new Path(basepath, "testfile1"); assertTrue(fileSystem.exists(basepath)); assertTrue(fileSystem.exists(filepath0)); assertTrue(fileSystem.exists(filepath1)); BufferedReader reader0 = new BufferedReader(new InputStreamReader(fileSystem.open(filepath0))); assertEquals("foo", reader0.readLine()); BufferedReader reader1 = new BufferedReader(new InputStreamReader(fileSystem.open(filepath1))); assertEquals("bar", reader1.readLine()); reader0.close(); reader1.close(); assertTrue(fileSystem.delete(basepath, true)); }
public void test() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "org/springframework/xd/integration/hadoop/config/HdfsOutboundChannelAdapterIntegrationTests.xml"); MessageChannel channel = context.getBean("hdfsOut", MessageChannel.class); channel.send(MessageBuilder.withPayload("foo").build()); channel.send(MessageBuilder.withPayload("bar").build()); FileSystem fileSystem = context.getBean("hadoopFs", FileSystem.class); String path = context.getBean("path", String.class); context.close(); Path basepath = new Path(path + "/testdir/"); Path filepath0 = new Path(basepath, "testfile-0"); Path filepath1 = new Path(basepath, "testfile-1"); assertTrue(fileSystem.exists(basepath)); assertTrue(fileSystem.exists(filepath0)); assertTrue(fileSystem.exists(filepath1)); BufferedReader reader0 = new BufferedReader(new InputStreamReader(fileSystem.open(filepath0))); assertEquals("foo", reader0.readLine()); BufferedReader reader1 = new BufferedReader(new InputStreamReader(fileSystem.open(filepath1))); assertEquals("bar", reader1.readLine()); reader0.close(); reader1.close(); assertTrue(fileSystem.delete(basepath, true)); }
diff --git a/deegree-datastores/deegree-tilestores/deegree-tilestore-commons/src/main/java/org/deegree/tile/tilematrixset/DefaultTileMatrixSetProvider.java b/deegree-datastores/deegree-tilestores/deegree-tilestore-commons/src/main/java/org/deegree/tile/tilematrixset/DefaultTileMatrixSetProvider.java index ced867ed10..2b6e3f20b1 100644 --- a/deegree-datastores/deegree-tilestores/deegree-tilestore-commons/src/main/java/org/deegree/tile/tilematrixset/DefaultTileMatrixSetProvider.java +++ b/deegree-datastores/deegree-tilestores/deegree-tilestore-commons/src/main/java/org/deegree/tile/tilematrixset/DefaultTileMatrixSetProvider.java @@ -1,132 +1,133 @@ //$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ Occam Labs UG (haftungsbeschränkt) Godesberger Allee 139, 53175 Bonn Germany http://www.occamlabs.de/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.tile.tilematrixset; import static org.deegree.commons.utils.MapUtils.DEFAULT_PIXEL_SIZE; import static org.deegree.commons.xml.jaxb.JAXBUtils.unmarshall; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.deegree.commons.config.DeegreeWorkspace; import org.deegree.commons.config.ResourceInitException; import org.deegree.commons.config.ResourceManager; import org.deegree.cs.coordinatesystems.ICRS; import org.deegree.cs.persistence.CRSManager; import org.deegree.geometry.Envelope; import org.deegree.geometry.GeometryFactory; import org.deegree.geometry.metadata.SpatialMetadata; import org.deegree.tile.TileMatrix; import org.deegree.tile.TileMatrixSet; import org.deegree.tile.tilematrixset.jaxb.TileMatrixSetConfig; /** * <code>DefaultTileMatrixSetProvider</code> * * @author <a href="mailto:[email protected]">Andreas Schmitz</a> * @author last edited by: $Author: mschneider $ * * @version $Revision: 31882 $, $Date: 2011-09-15 02:05:04 +0200 (Thu, 15 Sep 2011) $ */ public class DefaultTileMatrixSetProvider implements TileMatrixSetProvider { private static final String CONFIG_NAMESPACE = "http://www.deegree.org/datasource/tile/tilematrixset"; private static final String JAXB_PACKAGE = "org.deegree.tile.tilematrixset.jaxb"; private static final URL SCHEMA_URL = DefaultTileMatrixSetProvider.class.getResource( "/META-INF/schemas/datasource/tile/tilematrixset/3.2.0/tilematrixset.xsd" ); private DeegreeWorkspace workspace; @Override public void init( DeegreeWorkspace workspace ) { this.workspace = workspace; } @Override public TileMatrixSet create( URL configUrl ) throws ResourceInitException { try { TileMatrixSetConfig cfg = (TileMatrixSetConfig) unmarshall( JAXB_PACKAGE, SCHEMA_URL, configUrl, workspace ); ICRS crs = CRSManager.getCRSRef( cfg.getCRS() ); List<TileMatrix> matrices = new ArrayList<TileMatrix>(); for ( TileMatrixSetConfig.TileMatrix tm : cfg.getTileMatrix() ) { double res = tm.getScaleDenominator() * DEFAULT_PIXEL_SIZE; double minx = tm.getTopLeftCorner().get( 0 ); double maxy = tm.getTopLeftCorner().get( 1 ); double maxx = tm.getTileWidth().longValue() * tm.getMatrixWidth().longValue() * res + minx; double miny = maxy - tm.getTileHeight().longValue() * tm.getMatrixHeight().longValue() * res; Envelope env = new GeometryFactory().createEnvelope( minx, miny, maxx, maxy, crs ); SpatialMetadata smd = new SpatialMetadata( env, Collections.singletonList( crs ) ); TileMatrix md = new TileMatrix( tm.getIdentifier(), smd, tm.getTileWidth(), tm.getTileHeight(), res, tm.getMatrixWidth(), tm.getMatrixHeight() ); matrices.add( md ); } String identifier = new File( configUrl.getPath() ).getName(); + identifier = identifier.substring( 0, identifier.length() - 4 ).toLowerCase(); String wknScaleSet = cfg.getWellKnownScaleSet(); return new TileMatrixSet( identifier, wknScaleSet, matrices, matrices.get( 0 ).getSpatialMetadata() ); } catch ( Throwable e ) { throw new ResourceInitException( "Could not create tile matrix set. Reason: " + e.getLocalizedMessage(), e ); } } @SuppressWarnings("unchecked") @Override public Class<? extends ResourceManager>[] getDependencies() { return new Class[] {}; } @Override public String getConfigNamespace() { return CONFIG_NAMESPACE; } @Override public URL getConfigSchema() { return SCHEMA_URL; } }
true
true
public TileMatrixSet create( URL configUrl ) throws ResourceInitException { try { TileMatrixSetConfig cfg = (TileMatrixSetConfig) unmarshall( JAXB_PACKAGE, SCHEMA_URL, configUrl, workspace ); ICRS crs = CRSManager.getCRSRef( cfg.getCRS() ); List<TileMatrix> matrices = new ArrayList<TileMatrix>(); for ( TileMatrixSetConfig.TileMatrix tm : cfg.getTileMatrix() ) { double res = tm.getScaleDenominator() * DEFAULT_PIXEL_SIZE; double minx = tm.getTopLeftCorner().get( 0 ); double maxy = tm.getTopLeftCorner().get( 1 ); double maxx = tm.getTileWidth().longValue() * tm.getMatrixWidth().longValue() * res + minx; double miny = maxy - tm.getTileHeight().longValue() * tm.getMatrixHeight().longValue() * res; Envelope env = new GeometryFactory().createEnvelope( minx, miny, maxx, maxy, crs ); SpatialMetadata smd = new SpatialMetadata( env, Collections.singletonList( crs ) ); TileMatrix md = new TileMatrix( tm.getIdentifier(), smd, tm.getTileWidth(), tm.getTileHeight(), res, tm.getMatrixWidth(), tm.getMatrixHeight() ); matrices.add( md ); } String identifier = new File( configUrl.getPath() ).getName(); String wknScaleSet = cfg.getWellKnownScaleSet(); return new TileMatrixSet( identifier, wknScaleSet, matrices, matrices.get( 0 ).getSpatialMetadata() ); } catch ( Throwable e ) { throw new ResourceInitException( "Could not create tile matrix set. Reason: " + e.getLocalizedMessage(), e ); } }
public TileMatrixSet create( URL configUrl ) throws ResourceInitException { try { TileMatrixSetConfig cfg = (TileMatrixSetConfig) unmarshall( JAXB_PACKAGE, SCHEMA_URL, configUrl, workspace ); ICRS crs = CRSManager.getCRSRef( cfg.getCRS() ); List<TileMatrix> matrices = new ArrayList<TileMatrix>(); for ( TileMatrixSetConfig.TileMatrix tm : cfg.getTileMatrix() ) { double res = tm.getScaleDenominator() * DEFAULT_PIXEL_SIZE; double minx = tm.getTopLeftCorner().get( 0 ); double maxy = tm.getTopLeftCorner().get( 1 ); double maxx = tm.getTileWidth().longValue() * tm.getMatrixWidth().longValue() * res + minx; double miny = maxy - tm.getTileHeight().longValue() * tm.getMatrixHeight().longValue() * res; Envelope env = new GeometryFactory().createEnvelope( minx, miny, maxx, maxy, crs ); SpatialMetadata smd = new SpatialMetadata( env, Collections.singletonList( crs ) ); TileMatrix md = new TileMatrix( tm.getIdentifier(), smd, tm.getTileWidth(), tm.getTileHeight(), res, tm.getMatrixWidth(), tm.getMatrixHeight() ); matrices.add( md ); } String identifier = new File( configUrl.getPath() ).getName(); identifier = identifier.substring( 0, identifier.length() - 4 ).toLowerCase(); String wknScaleSet = cfg.getWellKnownScaleSet(); return new TileMatrixSet( identifier, wknScaleSet, matrices, matrices.get( 0 ).getSpatialMetadata() ); } catch ( Throwable e ) { throw new ResourceInitException( "Could not create tile matrix set. Reason: " + e.getLocalizedMessage(), e ); } }
diff --git a/cogroo-ann/src/main/java/br/ccsl/cogroo/text/tree/TreeUtil.java b/cogroo-ann/src/main/java/br/ccsl/cogroo/text/tree/TreeUtil.java index 7c4fff4..e3117c9 100644 --- a/cogroo-ann/src/main/java/br/ccsl/cogroo/text/tree/TreeUtil.java +++ b/cogroo-ann/src/main/java/br/ccsl/cogroo/text/tree/TreeUtil.java @@ -1,106 +1,113 @@ package br.ccsl.cogroo.text.tree; import java.util.ArrayList; import java.util.List; import br.ccsl.cogroo.text.Chunk; import br.ccsl.cogroo.text.Sentence; import br.ccsl.cogroo.text.SyntacticChunk; import br.ccsl.cogroo.text.Token; public class TreeUtil { public static Node createTree(Sentence sent) { Node root = new Node(); root.setLevel(0); root.setSyntacticTag("S"); List<TreeElement> elements = createLeafsList(sent); TreeElement[] originalElements = elements.toArray(new TreeElement[elements .size()]); List<Chunk> chunks = sent.getChunks(); List<SyntacticChunk> syntChunks = sent.getSyntacticChunks(); for (int i = chunks.size() - 1; i >= 0; i--) { Node node = new Node(); node.setSyntacticTag(chunks.get(i).getTag()); node.setMorphologicalTag(null); node.setLevel(2); for (int j = chunks.get(i).getStart(); j < chunks.get(i).getEnd(); j++) { node.addElement(elements.get(j)); elements.get(j).setParent(node); } for (int j = chunks.get(i).getEnd() - 1; j >= chunks.get(i).getStart(); j--) { elements.remove(j); } elements.add(chunks.get(i).getStart(), node); } for (int i = 0; i < syntChunks.size(); i++) { Node node = new Node(); node.setSyntacticTag(syntChunks.get(i).getTag()); node.setMorphologicalTag(null); node.setLevel(1); List<TreeElement> toRemove = new ArrayList<TreeElement>(); List<TreeElement> sons = new ArrayList<TreeElement>(); for (int j = syntChunks.get(i).getEnd() - 1; j >= syntChunks.get(i) .getStart(); j--) { if (originalElements[j].getParent() == null) { sons.add(0, originalElements[j]); toRemove.add(originalElements[j]); originalElements[j].setParent(node); } else { if (sons.size() == 0 || sons.get(0) != originalElements[j].getParent()) { sons.add(0, originalElements[j].getParent()); toRemove.add(originalElements[j].getParent()); } } } for (TreeElement son : sons) node.addElement(son); int index = elements.indexOf(toRemove.get(toRemove.size() - 1)); + while(index == -1 && toRemove.size() > 1) { + toRemove.remove(toRemove.size() - 1); + index = elements.indexOf(toRemove.get(toRemove.size() - 1)); + } for (TreeElement element : toRemove) elements.remove(element); - elements.add(index, node); + if(index >= 0) + elements.add(index, node); + //else + // elements.add(0, node); node.setParent(root); } for (TreeElement element : elements) { root.addElement(element); } return root; } public static List<TreeElement> createLeafsList(Sentence sentence) { List<TreeElement> leafs = new ArrayList<TreeElement>(); List<Token> tokens = sentence.getTokens(); for (Token token : tokens) { Leaf leaf = new Leaf(token.getLexeme(), token.getLemmas()); leaf.setLevel(3); leaf.setMorphologicalTag(token.getPOSTag()); leaf.setFeatureTag(token.getFeatures()); leafs.add(leaf); } return leafs; } }
false
true
public static Node createTree(Sentence sent) { Node root = new Node(); root.setLevel(0); root.setSyntacticTag("S"); List<TreeElement> elements = createLeafsList(sent); TreeElement[] originalElements = elements.toArray(new TreeElement[elements .size()]); List<Chunk> chunks = sent.getChunks(); List<SyntacticChunk> syntChunks = sent.getSyntacticChunks(); for (int i = chunks.size() - 1; i >= 0; i--) { Node node = new Node(); node.setSyntacticTag(chunks.get(i).getTag()); node.setMorphologicalTag(null); node.setLevel(2); for (int j = chunks.get(i).getStart(); j < chunks.get(i).getEnd(); j++) { node.addElement(elements.get(j)); elements.get(j).setParent(node); } for (int j = chunks.get(i).getEnd() - 1; j >= chunks.get(i).getStart(); j--) { elements.remove(j); } elements.add(chunks.get(i).getStart(), node); } for (int i = 0; i < syntChunks.size(); i++) { Node node = new Node(); node.setSyntacticTag(syntChunks.get(i).getTag()); node.setMorphologicalTag(null); node.setLevel(1); List<TreeElement> toRemove = new ArrayList<TreeElement>(); List<TreeElement> sons = new ArrayList<TreeElement>(); for (int j = syntChunks.get(i).getEnd() - 1; j >= syntChunks.get(i) .getStart(); j--) { if (originalElements[j].getParent() == null) { sons.add(0, originalElements[j]); toRemove.add(originalElements[j]); originalElements[j].setParent(node); } else { if (sons.size() == 0 || sons.get(0) != originalElements[j].getParent()) { sons.add(0, originalElements[j].getParent()); toRemove.add(originalElements[j].getParent()); } } } for (TreeElement son : sons) node.addElement(son); int index = elements.indexOf(toRemove.get(toRemove.size() - 1)); for (TreeElement element : toRemove) elements.remove(element); elements.add(index, node); node.setParent(root); } for (TreeElement element : elements) { root.addElement(element); } return root; }
public static Node createTree(Sentence sent) { Node root = new Node(); root.setLevel(0); root.setSyntacticTag("S"); List<TreeElement> elements = createLeafsList(sent); TreeElement[] originalElements = elements.toArray(new TreeElement[elements .size()]); List<Chunk> chunks = sent.getChunks(); List<SyntacticChunk> syntChunks = sent.getSyntacticChunks(); for (int i = chunks.size() - 1; i >= 0; i--) { Node node = new Node(); node.setSyntacticTag(chunks.get(i).getTag()); node.setMorphologicalTag(null); node.setLevel(2); for (int j = chunks.get(i).getStart(); j < chunks.get(i).getEnd(); j++) { node.addElement(elements.get(j)); elements.get(j).setParent(node); } for (int j = chunks.get(i).getEnd() - 1; j >= chunks.get(i).getStart(); j--) { elements.remove(j); } elements.add(chunks.get(i).getStart(), node); } for (int i = 0; i < syntChunks.size(); i++) { Node node = new Node(); node.setSyntacticTag(syntChunks.get(i).getTag()); node.setMorphologicalTag(null); node.setLevel(1); List<TreeElement> toRemove = new ArrayList<TreeElement>(); List<TreeElement> sons = new ArrayList<TreeElement>(); for (int j = syntChunks.get(i).getEnd() - 1; j >= syntChunks.get(i) .getStart(); j--) { if (originalElements[j].getParent() == null) { sons.add(0, originalElements[j]); toRemove.add(originalElements[j]); originalElements[j].setParent(node); } else { if (sons.size() == 0 || sons.get(0) != originalElements[j].getParent()) { sons.add(0, originalElements[j].getParent()); toRemove.add(originalElements[j].getParent()); } } } for (TreeElement son : sons) node.addElement(son); int index = elements.indexOf(toRemove.get(toRemove.size() - 1)); while(index == -1 && toRemove.size() > 1) { toRemove.remove(toRemove.size() - 1); index = elements.indexOf(toRemove.get(toRemove.size() - 1)); } for (TreeElement element : toRemove) elements.remove(element); if(index >= 0) elements.add(index, node); //else // elements.add(0, node); node.setParent(root); } for (TreeElement element : elements) { root.addElement(element); } return root; }
diff --git a/src/fr/pronoschallenge/PronosAdapter.java b/src/fr/pronoschallenge/PronosAdapter.java index 30c7739..85d3e53 100644 --- a/src/fr/pronoschallenge/PronosAdapter.java +++ b/src/fr/pronoschallenge/PronosAdapter.java @@ -1,162 +1,165 @@ package fr.pronoschallenge; import android.content.Context; import android.content.SharedPreferences; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import fr.pronoschallenge.rest.QueryBuilder; import fr.pronoschallenge.rest.RestClient; import org.apache.http.HttpResponse; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.InputStream; import java.net.ResponseCache; import java.text.DecimalFormat; import java.util.*; public class PronosAdapter extends ArrayAdapter<PronoEntry> { public PronosAdapter(Context context, int textViewResourceId, List<PronoEntry> objects) { super(context, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater li = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); //le layout représentant la ligne dans le listView view = li.inflate(R.layout.pronos_item, null); } PronoEntry pronoEntry = getItem(position); if (pronoEntry != null) { TextView pronoEntryClubDom = (TextView) view.findViewById(R.id.pronoEntryEquipeDom); pronoEntryClubDom.setText(pronoEntry.getEquipeDom()); int id = pronoEntry.getId(); Button buttonProno1 = (Button) view.findViewById(R.id.buttonProno1); + buttonProno1.setSelected(false); buttonProno1.setTag(R.id.idProno, id); buttonProno1.setTag(R.id.valueProno, "1"); Button buttonPronoN = (Button) view.findViewById(R.id.buttonPronoN); + buttonPronoN.setSelected(false); buttonPronoN.setTag(R.id.idProno, id); buttonPronoN.setTag(R.id.valueProno, "N"); Button buttonProno2 = (Button) view.findViewById(R.id.buttonProno2); + buttonProno2.setSelected(false); buttonProno2.setTag(R.id.idProno, id); buttonProno2.setTag(R.id.valueProno, "2"); // si le match a déjà été pronostiqué, on sélectionne le bouton correspondant String prono = pronoEntry.getProno(); if (prono.equals("1")) { buttonProno1.setSelected(true); } else if (prono.equals("N")) { buttonPronoN.setSelected(true); } else if (prono.equals("2")) { buttonProno2.setSelected(true); } if (false && pronoEntry.getDate().before(new Date())) { buttonProno1.setEnabled(false); buttonPronoN.setEnabled(false); buttonProno2.setEnabled(false); } else { buttonProno1.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonPronoN, buttonProno2)))); buttonPronoN.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonProno1, buttonProno2)))); buttonProno2.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonProno1, buttonPronoN)))); } TextView pronoEntryClubExt = (TextView) view.findViewById(R.id.pronoEntryEquipeExt); pronoEntryClubExt.setText(pronoEntry.getEquipeExt()); } return view; } class PronosButtonsOnClickListener implements View.OnClickListener { List<View> othersButtons = null; PronosButtonsOnClickListener(List<View> othersButtons) { this.othersButtons = othersButtons; } public void onClick(View button) { // mise à jour des éléments graphiques String valueProno = null; if (button.isSelected()) { button.setSelected(false); valueProno = "0"; } else { button.setSelected(true); valueProno = (String) button.getTag(R.id.valueProno); } for (View otherButton : othersButtons) { otherButton.setSelected(false); } // lancement de la tâche de mise à jour de pronos AsyncTask task = new PronosTask(button, othersButtons).execute(valueProno); } } class PronosTask extends AsyncTask<String, Void, Boolean> { private View button; private List<View> othersButtons; PronosTask(View button, List<View> othersButtons) { this.button = button; this.othersButtons = othersButtons; } @Override protected Boolean doInBackground(String... args) { String valueProno = args[0]; JSONObject jsonObject = new JSONObject(); try { jsonObject.put("id", button.getTag(R.id.idProno)); jsonObject.put("prono", valueProno); } catch (JSONException je) { je.printStackTrace(); } JSONArray jsonDataArray = new JSONArray(); jsonDataArray.put(jsonObject); String userName = PreferenceManager.getDefaultSharedPreferences(button.getContext()).getString("username", null); String password = PreferenceManager.getDefaultSharedPreferences(button.getContext()).getString("password", null); String url = new QueryBuilder(button.getContext().getAssets(), "/rest/pronos/" + userName).getUri(); HttpResponse response = RestClient.postData(url, jsonDataArray.toString(), userName, password); if (response.getStatusLine().getStatusCode() != 200) { Toast toast = Toast.makeText(button.getContext(), "Erreur lors de la mise à jour de vos pronostics : " + response.getStatusLine().getStatusCode(), 4); toast.show(); } else { try { String message = RestClient.convertStreamToString(response.getEntity().getContent()); if(message.length() > 0) { Toast toast = Toast.makeText(button.getContext(), "Erreur lors de la mise à jour de vos pronostics : " + message, 4); toast.show(); } } catch (Exception e) { e.printStackTrace(); } } return true; } } }
false
true
public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater li = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); //le layout représentant la ligne dans le listView view = li.inflate(R.layout.pronos_item, null); } PronoEntry pronoEntry = getItem(position); if (pronoEntry != null) { TextView pronoEntryClubDom = (TextView) view.findViewById(R.id.pronoEntryEquipeDom); pronoEntryClubDom.setText(pronoEntry.getEquipeDom()); int id = pronoEntry.getId(); Button buttonProno1 = (Button) view.findViewById(R.id.buttonProno1); buttonProno1.setTag(R.id.idProno, id); buttonProno1.setTag(R.id.valueProno, "1"); Button buttonPronoN = (Button) view.findViewById(R.id.buttonPronoN); buttonPronoN.setTag(R.id.idProno, id); buttonPronoN.setTag(R.id.valueProno, "N"); Button buttonProno2 = (Button) view.findViewById(R.id.buttonProno2); buttonProno2.setTag(R.id.idProno, id); buttonProno2.setTag(R.id.valueProno, "2"); // si le match a déjà été pronostiqué, on sélectionne le bouton correspondant String prono = pronoEntry.getProno(); if (prono.equals("1")) { buttonProno1.setSelected(true); } else if (prono.equals("N")) { buttonPronoN.setSelected(true); } else if (prono.equals("2")) { buttonProno2.setSelected(true); } if (false && pronoEntry.getDate().before(new Date())) { buttonProno1.setEnabled(false); buttonPronoN.setEnabled(false); buttonProno2.setEnabled(false); } else { buttonProno1.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonPronoN, buttonProno2)))); buttonPronoN.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonProno1, buttonProno2)))); buttonProno2.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonProno1, buttonPronoN)))); } TextView pronoEntryClubExt = (TextView) view.findViewById(R.id.pronoEntryEquipeExt); pronoEntryClubExt.setText(pronoEntry.getEquipeExt()); } return view; }
public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { LayoutInflater li = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); //le layout représentant la ligne dans le listView view = li.inflate(R.layout.pronos_item, null); } PronoEntry pronoEntry = getItem(position); if (pronoEntry != null) { TextView pronoEntryClubDom = (TextView) view.findViewById(R.id.pronoEntryEquipeDom); pronoEntryClubDom.setText(pronoEntry.getEquipeDom()); int id = pronoEntry.getId(); Button buttonProno1 = (Button) view.findViewById(R.id.buttonProno1); buttonProno1.setSelected(false); buttonProno1.setTag(R.id.idProno, id); buttonProno1.setTag(R.id.valueProno, "1"); Button buttonPronoN = (Button) view.findViewById(R.id.buttonPronoN); buttonPronoN.setSelected(false); buttonPronoN.setTag(R.id.idProno, id); buttonPronoN.setTag(R.id.valueProno, "N"); Button buttonProno2 = (Button) view.findViewById(R.id.buttonProno2); buttonProno2.setSelected(false); buttonProno2.setTag(R.id.idProno, id); buttonProno2.setTag(R.id.valueProno, "2"); // si le match a déjà été pronostiqué, on sélectionne le bouton correspondant String prono = pronoEntry.getProno(); if (prono.equals("1")) { buttonProno1.setSelected(true); } else if (prono.equals("N")) { buttonPronoN.setSelected(true); } else if (prono.equals("2")) { buttonProno2.setSelected(true); } if (false && pronoEntry.getDate().before(new Date())) { buttonProno1.setEnabled(false); buttonPronoN.setEnabled(false); buttonProno2.setEnabled(false); } else { buttonProno1.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonPronoN, buttonProno2)))); buttonPronoN.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonProno1, buttonProno2)))); buttonProno2.setOnClickListener(new PronosButtonsOnClickListener(new ArrayList<View>(Arrays.asList(buttonProno1, buttonPronoN)))); } TextView pronoEntryClubExt = (TextView) view.findViewById(R.id.pronoEntryEquipeExt); pronoEntryClubExt.setText(pronoEntry.getEquipeExt()); } return view; }
diff --git a/src/com/android/launcher3/LauncherModel.java b/src/com/android/launcher3/LauncherModel.java index cec446f04..8f486e78a 100644 --- a/src/com/android/launcher3/LauncherModel.java +++ b/src/com/android/launcher3/LauncherModel.java @@ -1,3074 +1,3086 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.launcher3; import android.app.SearchManager; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProviderInfo; import android.content.*; import android.content.Intent.ShortcutIconResource; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.os.Parcelable; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.util.Log; import android.util.Pair; import com.android.launcher3.InstallWidgetReceiver.WidgetMimeTypeHandlerData; import java.lang.ref.WeakReference; import java.net.URISyntaxException; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; /** * Maintains in-memory state of the Launcher. It is expected that there should be only one * LauncherModel object held in a static. Also provide APIs for updating the database state * for the Launcher. */ public class LauncherModel extends BroadcastReceiver { static final boolean DEBUG_LOADERS = false; static final String TAG = "Launcher.Model"; private static final int ITEMS_CHUNK = 6; // batch size for the workspace icons private final boolean mAppsCanBeOnRemoveableStorage; private final LauncherAppState mApp; private final Object mLock = new Object(); private DeferredHandler mHandler = new DeferredHandler(); private LoaderTask mLoaderTask; private boolean mIsLoaderTaskRunning; private volatile boolean mFlushingWorkerThread; // Specific runnable types that are run on the main thread deferred handler, this allows us to // clear all queued binding runnables when the Launcher activity is destroyed. private static final int MAIN_THREAD_NORMAL_RUNNABLE = 0; private static final int MAIN_THREAD_BINDING_RUNNABLE = 1; private static final HandlerThread sWorkerThread = new HandlerThread("launcher-loader"); static { sWorkerThread.start(); } private static final Handler sWorker = new Handler(sWorkerThread.getLooper()); // We start off with everything not loaded. After that, we assume that // our monitoring of the package manager provides all updates and we never // need to do a requery. These are only ever touched from the loader thread. private boolean mWorkspaceLoaded; private boolean mAllAppsLoaded; // When we are loading pages synchronously, we can't just post the binding of items on the side // pages as this delays the rotation process. Instead, we wait for a callback from the first // draw (in Workspace) to initiate the binding of the remaining side pages. Any time we start // a normal load, we also clear this set of Runnables. static final ArrayList<Runnable> mDeferredBindRunnables = new ArrayList<Runnable>(); private WeakReference<Callbacks> mCallbacks; // < only access in worker thread > private AllAppsList mBgAllAppsList; // The lock that must be acquired before referencing any static bg data structures. Unlike // other locks, this one can generally be held long-term because we never expect any of these // static data structures to be referenced outside of the worker thread except on the first // load after configuration change. static final Object sBgLock = new Object(); // sBgItemsIdMap maps *all* the ItemInfos (shortcuts, folders, and widgets) created by // LauncherModel to their ids static final HashMap<Long, ItemInfo> sBgItemsIdMap = new HashMap<Long, ItemInfo>(); // sBgWorkspaceItems is passed to bindItems, which expects a list of all folders and shortcuts // created by LauncherModel that are directly on the home screen (however, no widgets or // shortcuts within folders). static final ArrayList<ItemInfo> sBgWorkspaceItems = new ArrayList<ItemInfo>(); // sBgAppWidgets is all LauncherAppWidgetInfo created by LauncherModel. Passed to bindAppWidget() static final ArrayList<LauncherAppWidgetInfo> sBgAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); // sBgFolders is all FolderInfos created by LauncherModel. Passed to bindFolders() static final HashMap<Long, FolderInfo> sBgFolders = new HashMap<Long, FolderInfo>(); // sBgDbIconCache is the set of ItemInfos that need to have their icons updated in the database static final HashMap<Object, byte[]> sBgDbIconCache = new HashMap<Object, byte[]>(); // sBgWorkspaceScreens is the ordered set of workspace screens. static final ArrayList<Long> sBgWorkspaceScreens = new ArrayList<Long>(); // </ only access in worker thread > private IconCache mIconCache; private Bitmap mDefaultIcon; private static int mCellCountX; private static int mCellCountY; protected int mPreviousConfigMcc; public interface Callbacks { public boolean setLoadOnResume(); public int getCurrentWorkspaceScreen(); public void startBinding(); public void bindItems(ArrayList<ItemInfo> shortcuts, int start, int end, boolean forceAnimateIcons); public void bindScreens(ArrayList<Long> orderedScreenIds); public void bindAddScreens(ArrayList<Long> orderedScreenIds); public void bindFolders(HashMap<Long,FolderInfo> folders); public void finishBindingItems(boolean upgradePath); public void bindAppWidget(LauncherAppWidgetInfo info); public void bindAllApplications(ArrayList<ApplicationInfo> apps); public void bindAppsUpdated(ArrayList<ApplicationInfo> apps); public void bindComponentsRemoved(ArrayList<String> packageNames, ArrayList<ApplicationInfo> appInfos, boolean matchPackageNamesOnly); public void bindPackagesUpdated(ArrayList<Object> widgetsAndShortcuts); public void bindSearchablesChanged(); public void onPageBoundSynchronously(int page); } public interface ItemInfoFilter { public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn); } LauncherModel(LauncherAppState app, IconCache iconCache) { final Context context = app.getContext(); mAppsCanBeOnRemoveableStorage = Environment.isExternalStorageRemovable(); mApp = app; mBgAllAppsList = new AllAppsList(iconCache); mIconCache = iconCache; mDefaultIcon = Utilities.createIconBitmap( mIconCache.getFullResDefaultActivityIcon(), context); final Resources res = context.getResources(); Configuration config = res.getConfiguration(); mPreviousConfigMcc = config.mcc; } /** Runs the specified runnable immediately if called from the main thread, otherwise it is * posted on the main thread handler. */ private void runOnMainThread(Runnable r) { runOnMainThread(r, 0); } private void runOnMainThread(Runnable r, int type) { if (sWorkerThread.getThreadId() == Process.myTid()) { // If we are on the worker thread, post onto the main handler mHandler.post(r); } else { r.run(); } } /** Runs the specified runnable immediately if called from the worker thread, otherwise it is * posted on the worker thread handler. */ private static void runOnWorkerThread(Runnable r) { if (sWorkerThread.getThreadId() == Process.myTid()) { r.run(); } else { // If we are not on the worker thread, then post to the worker handler sWorker.post(r); } } static boolean findNextAvailableIconSpaceInScreen(ArrayList<ItemInfo> items, int[] xy, long screen) { final int xCount = LauncherModel.getCellCountX(); final int yCount = LauncherModel.getCellCountY(); boolean[][] occupied = new boolean[xCount][yCount]; int cellX, cellY, spanX, spanY; for (int i = 0; i < items.size(); ++i) { final ItemInfo item = items.get(i); if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (item.screenId == screen) { cellX = item.cellX; cellY = item.cellY; spanX = item.spanX; spanY = item.spanY; for (int x = cellX; 0 <= x && x < cellX + spanX && x < xCount; x++) { for (int y = cellY; 0 <= y && y < cellY + spanY && y < yCount; y++) { occupied[x][y] = true; } } } } } return CellLayout.findVacantCell(xy, 1, 1, xCount, yCount, occupied); } static Pair<Long, int[]> findNextAvailableIconSpace(Context context, String name, Intent launchIntent, int firstScreenIndex) { // Lock on the app so that we don't try and get the items while apps are being added LauncherAppState app = LauncherAppState.getInstance(); LauncherModel model = app.getModel(); boolean found = false; synchronized (app) { if (sWorkerThread.getThreadId() != Process.myTid()) { // Flush the LauncherModel worker thread, so that if we just did another // processInstallShortcut, we give it time for its shortcut to get added to the // database (getItemsInLocalCoordinates reads the database) model.flushWorkerThread(); } final ArrayList<ItemInfo> items = LauncherModel.getItemsInLocalCoordinates(context); // Try adding to the workspace screens incrementally, starting at the default or center // screen and alternating between +1, -1, +2, -2, etc. (using ~ ceil(i/2f)*(-1)^(i-1)) firstScreenIndex = Math.min(firstScreenIndex, sBgWorkspaceScreens.size()); int count = sBgWorkspaceScreens.size(); for (int screen = firstScreenIndex; screen < count && !found; screen++) { int[] tmpCoordinates = new int[2]; if (findNextAvailableIconSpaceInScreen(items, tmpCoordinates, sBgWorkspaceScreens.get(screen))) { // Update the Launcher db return new Pair<Long, int[]>(sBgWorkspaceScreens.get(screen), tmpCoordinates); } } } return null; } public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } public void addAndBindAddedApps(final Context context, final ArrayList<ItemInfo> added, final Callbacks callbacks) { if (added.isEmpty()) { throw new RuntimeException("EMPTY ADDED ARRAY?"); } // Process the newly added applications and add them to the database first Runnable r = new Runnable() { public void run() { final ArrayList<ItemInfo> addedShortcutsFinal = new ArrayList<ItemInfo>(); final ArrayList<Long> addedWorkspaceScreensFinal = new ArrayList<Long>(); synchronized(sBgLock) { Iterator<ItemInfo> iter = added.iterator(); while (iter.hasNext()) { ItemInfo a = iter.next(); final String name = a.title.toString(); final Intent launchIntent = a.getIntent(); // Short-circuit this logic if the icon exists somewhere on the workspace if (LauncherModel.shortcutExists(context, name, launchIntent)) { continue; } // Add this icon to the db, creating a new page if necessary int startSearchPageIndex = 1; Pair<Long, int[]> coords = LauncherModel.findNextAvailableIconSpace(context, name, launchIntent, startSearchPageIndex); if (coords == null) { LauncherAppState appState = LauncherAppState.getInstance(); LauncherProvider lp = appState.getLauncherProvider(); // If we can't find a valid position, then just add a new screen. // This takes time so we need to re-queue the add until the new // page is added. Create as many screens as necessary to satisfy // the startSearchPageIndex. int numPagesToAdd = Math.max(1, startSearchPageIndex + 1 - sBgWorkspaceScreens.size()); while (numPagesToAdd > 0) { long screenId = lp.generateNewScreenId(); // Update the model sBgWorkspaceScreens.add(screenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Save the screen id for binding in the workspace addedWorkspaceScreensFinal.add(screenId); numPagesToAdd--; } // Find the coordinate again coords = LauncherModel.findNextAvailableIconSpace(context, name, launchIntent, startSearchPageIndex); } if (coords == null) { throw new RuntimeException("Coordinates should not be null"); } ShortcutInfo shortcutInfo; if (a instanceof ShortcutInfo) { shortcutInfo = (ShortcutInfo) a; } else if (a instanceof ApplicationInfo) { shortcutInfo = ((ApplicationInfo) a).makeShortcut(); } else { throw new RuntimeException("Unexpected info type"); } // Add the shortcut to the db addItemToDatabase(context, shortcutInfo, LauncherSettings.Favorites.CONTAINER_DESKTOP, coords.first, coords.second[0], coords.second[1], false); // Save the ShortcutInfo for binding in the workspace addedShortcutsFinal.add(shortcutInfo); } } if (!addedShortcutsFinal.isEmpty()) { runOnMainThread(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAddScreens(addedWorkspaceScreensFinal); ItemInfo info = addedShortcutsFinal.get(addedShortcutsFinal.size() - 1); long lastScreenId = info.screenId; final ArrayList<ItemInfo> addAnimated = new ArrayList<ItemInfo>(); final ArrayList<ItemInfo> addNotAnimated = new ArrayList<ItemInfo>(); for (ItemInfo i : addedShortcutsFinal) { if (i.screenId == lastScreenId) { addAnimated.add(i); } else { addNotAnimated.add(i); } } // We add the items without animation on non-visible pages, and with // animations on the new page (which we will try and snap to). if (!addNotAnimated.isEmpty()) { callbacks.bindItems(addNotAnimated, 0, addNotAnimated.size(), false); } if (!addAnimated.isEmpty()) { callbacks.bindItems(addAnimated, 0, addAnimated.size(), true); } } } }); } } }; runOnWorkerThread(r); } public Bitmap getFallbackIcon() { return Bitmap.createBitmap(mDefaultIcon); } public void unbindItemInfosAndClearQueuedBindRunnables() { if (sWorkerThread.getThreadId() == Process.myTid()) { throw new RuntimeException("Expected unbindLauncherItemInfos() to be called from the " + "main thread"); } // Clear any deferred bind runnables mDeferredBindRunnables.clear(); // Remove any queued bind runnables mHandler.cancelAllRunnablesOfType(MAIN_THREAD_BINDING_RUNNABLE); // Unbind all the workspace items unbindWorkspaceItemsOnMainThread(); } /** Unbinds all the sBgWorkspaceItems and sBgAppWidgets on the main thread */ void unbindWorkspaceItemsOnMainThread() { // Ensure that we don't use the same workspace items data structure on the main thread // by making a copy of workspace items first. final ArrayList<ItemInfo> tmpWorkspaceItems = new ArrayList<ItemInfo>(); final ArrayList<ItemInfo> tmpAppWidgets = new ArrayList<ItemInfo>(); synchronized (sBgLock) { tmpWorkspaceItems.addAll(sBgWorkspaceItems); tmpAppWidgets.addAll(sBgAppWidgets); } Runnable r = new Runnable() { @Override public void run() { for (ItemInfo item : tmpWorkspaceItems) { item.unbind(); } for (ItemInfo item : tmpAppWidgets) { item.unbind(); } } }; runOnMainThread(r); } /** * Adds an item to the DB if it was not created previously, or move it to a new * <container, screen, cellX, cellY> */ static void addOrMoveItemInDatabase(Context context, ItemInfo item, long container, long screenId, int cellX, int cellY) { if (item.container == ItemInfo.NO_ID) { // From all apps addItemToDatabase(context, item, container, screenId, cellX, cellY, false); } else { // From somewhere else moveItemInDatabase(context, item, container, screenId, cellX, cellY); } } static void checkItemInfoLocked( final long itemId, final ItemInfo item, StackTraceElement[] stackTrace) { ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem != null && item != modelItem) { // check all the data is consistent if (modelItem instanceof ShortcutInfo && item instanceof ShortcutInfo) { ShortcutInfo modelShortcut = (ShortcutInfo) modelItem; ShortcutInfo shortcut = (ShortcutInfo) item; if (modelShortcut.title.toString().equals(shortcut.title.toString()) && modelShortcut.intent.filterEquals(shortcut.intent) && modelShortcut.id == shortcut.id && modelShortcut.itemType == shortcut.itemType && modelShortcut.container == shortcut.container && modelShortcut.screenId == shortcut.screenId && modelShortcut.cellX == shortcut.cellX && modelShortcut.cellY == shortcut.cellY && modelShortcut.spanX == shortcut.spanX && modelShortcut.spanY == shortcut.spanY && ((modelShortcut.dropPos == null && shortcut.dropPos == null) || (modelShortcut.dropPos != null && shortcut.dropPos != null && modelShortcut.dropPos[0] == shortcut.dropPos[0] && modelShortcut.dropPos[1] == shortcut.dropPos[1]))) { // For all intents and purposes, this is the same object return; } } // the modelItem needs to match up perfectly with item if our model is // to be consistent with the database-- for now, just require // modelItem == item or the equality check above String msg = "item: " + ((item != null) ? item.toString() : "null") + "modelItem: " + ((modelItem != null) ? modelItem.toString() : "null") + "Error: ItemInfo passed to checkItemInfo doesn't match original"; RuntimeException e = new RuntimeException(msg); if (stackTrace != null) { e.setStackTrace(stackTrace); } // TODO: something breaks this in the upgrade path //throw e; } } static void checkItemInfo(final ItemInfo item) { final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); final long itemId = item.id; Runnable r = new Runnable() { public void run() { synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); } } }; runOnWorkerThread(r); } static void updateItemInDatabaseHelper(Context context, final ContentValues values, final ItemInfo item, final String callingFunction) { final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { cr.update(uri, values, null, null); updateItemArrays(item, itemId, stackTrace); } }; runOnWorkerThread(r); } static void updateItemsInDatabaseHelper(Context context, final ArrayList<ContentValues> valuesList, final ArrayList<ItemInfo> items, final String callingFunction) { final ContentResolver cr = context.getContentResolver(); final StackTraceElement[] stackTrace = new Throwable().getStackTrace(); Runnable r = new Runnable() { public void run() { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); final long itemId = item.id; final Uri uri = LauncherSettings.Favorites.getContentUri(itemId, false); ContentValues values = valuesList.get(i); ops.add(ContentProviderOperation.newUpdate(uri).withValues(values).build()); updateItemArrays(item, itemId, stackTrace); } try { cr.applyBatch(LauncherProvider.AUTHORITY, ops); } catch (Exception e) { e.printStackTrace(); } } }; runOnWorkerThread(r); } static void updateItemArrays(ItemInfo item, long itemId, StackTraceElement[] stackTrace) { // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(itemId, item, stackTrace); if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP && item.container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { // Item is in a folder, make sure this folder exists if (!sBgFolders.containsKey(item.container)) { // An items container is being set to a that of an item which is not in // the list of Folders. String msg = "item: " + item + " container being set to: " + item.container + ", not in the list of folders"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } // Items are added/removed from the corresponding FolderInfo elsewhere, such // as in Workspace.onDrop. Here, we just add/remove them from the list of items // that are on the desktop, as appropriate ItemInfo modelItem = sBgItemsIdMap.get(itemId); if (modelItem.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || modelItem.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { switch (modelItem.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: if (!sBgWorkspaceItems.contains(modelItem)) { sBgWorkspaceItems.add(modelItem); } break; default: break; } } else { sBgWorkspaceItems.remove(modelItem); } } } public void flushWorkerThread() { mFlushingWorkerThread = true; Runnable waiter = new Runnable() { public void run() { synchronized (this) { notifyAll(); mFlushingWorkerThread = false; } } }; synchronized(waiter) { runOnWorkerThread(waiter); if (mLoaderTask != null) { synchronized(mLoaderTask) { mLoaderTask.notify(); } } boolean success = false; while (!success) { try { waiter.wait(); success = true; } catch (InterruptedException e) { } } } } /** * Move an item in the DB to a new <container, screen, cellX, cellY> */ static void moveItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY) { String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "moveItemInDatabase"); } /** * Move items in the DB to a new <container, screen, cellX, cellY>. We assume that the * cellX, cellY have already been updated on the ItemInfos. */ static void moveItemsInDatabase(Context context, final ArrayList<ItemInfo> items, final long container, final int screen) { ArrayList<ContentValues> contentValues = new ArrayList<ContentValues>(); int count = items.size(); for (int i = 0; i < count; i++) { ItemInfo item = items.get(i); String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screen + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); item.container = container; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screen < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(item.cellX, item.cellY); } else { item.screenId = screen; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); contentValues.add(values); } updateItemsInDatabaseHelper(context, contentValues, items, "moveItemInDatabase"); } /** * Move and/or resize item in the DB to a new <container, screen, cellX, cellY, spanX, spanY> */ static void modifyItemInDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final int spanX, final int spanY) { String transaction = "DbDebug Modify item (" + item.title + ") in db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ") --> " + "(" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); item.cellX = cellX; item.cellY = cellY; item.spanX = spanX; item.spanY = spanY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); values.put(LauncherSettings.Favorites.CONTAINER, item.container); values.put(LauncherSettings.Favorites.CELLX, item.cellX); values.put(LauncherSettings.Favorites.CELLY, item.cellY); values.put(LauncherSettings.Favorites.SPANX, item.spanX); values.put(LauncherSettings.Favorites.SPANY, item.spanY); values.put(LauncherSettings.Favorites.SCREEN, item.screenId); updateItemInDatabaseHelper(context, values, item, "modifyItemInDatabase"); } /** * Update an item to the database in a specified container. */ static void updateItemInDatabase(Context context, final ItemInfo item) { final ContentValues values = new ContentValues(); item.onAddToDatabase(values); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); updateItemInDatabaseHelper(context, values, item, "updateItemInDatabase"); } /** * Returns true if the shortcuts already exists in the database. * we identify a shortcut by its title and intent. */ static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Ensure that all the applications that are in the system are represented on the home // screen. if (!isUpgrade) { verifyApplications(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ApplicationInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); - if (!isValidPackage(manager, cn)) { + if (!isValidPackageComponent(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { - // Log the invalid package, and remove it from the database - Uri uri = LauncherSettings.Favorites.getContentUri(id, false); + // Log the invalid package, and remove it from the db + Uri uri = LauncherSettings.Favorites.getContentUri(id, + false); contentResolver.delete(uri, null, null); - Log.e(TAG, "Invalid package removed in loadWorkspace: " + cn); + Log.e(TAG, "Invalid package removed: " + cn); } else { - // If apps can be on external storage, then we just leave - // them for the user to remove (maybe add treatment to it) - Log.e(TAG, "Invalid package found in loadWorkspace: " + cn); + // If apps can be on external storage, then we just + // leave them for the user to remove (maybe add + // visual treatment to it) + Log.e(TAG, "Invalid package found: " + cn); } continue; } } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); + } else { + throw new RuntimeException("Unexpected null ShortcutInfo"); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { if (c != null) { c.close(); } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState app = LauncherAppState.getInstance(); app.getLauncherProvider().updateMaxItemId(maxItemId); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; for (int i = 0; i < apps.size(); i++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); } final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, addedInfos, cb); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (ApplicationInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } else { for (ApplicationInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } - private boolean isValidPackage(PackageManager pm, ComponentName cn) { + private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); - if (!isValidPackage(manager, componentName)) { + final ShortcutInfo info = new ShortcutInfo(); + if (!isValidPackageComponent(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; + } else { + try { + PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); + info.initFlagsAndFirstInstallTime(pi); + } catch (NameNotFoundException e) { + Log.d(TAG, "getPackInfo failed for package " + + componentName.getPackageName()); + } } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). - final ShortcutInfo info = new ShortcutInfo(); Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
false
true
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Ensure that all the applications that are in the system are represented on the home // screen. if (!isUpgrade) { verifyApplications(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ApplicationInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (!isValidPackage(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the database Uri uri = LauncherSettings.Favorites.getContentUri(id, false); contentResolver.delete(uri, null, null); Log.e(TAG, "Invalid package removed in loadWorkspace: " + cn); } else { // If apps can be on external storage, then we just leave // them for the user to remove (maybe add treatment to it) Log.e(TAG, "Invalid package found in loadWorkspace: " + cn); } continue; } } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { if (c != null) { c.close(); } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState app = LauncherAppState.getInstance(); app.getLauncherProvider().updateMaxItemId(maxItemId); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; for (int i = 0; i < apps.size(); i++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); } final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, addedInfos, cb); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (ApplicationInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } else { for (ApplicationInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackage(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); if (!isValidPackage(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). final ShortcutInfo info = new ShortcutInfo(); Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
static boolean shortcutExists(Context context, String title, Intent intent) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { "title", "intent" }, "title=? and intent=?", new String[] { title, intent.toUri(0) }, null); boolean result = false; try { result = c.moveToFirst(); } finally { c.close(); } return result; } /** * Returns an ItemInfo array containing all the items in the LauncherModel. * The ItemInfo.id is not set through this function. */ static ArrayList<ItemInfo> getItemsInLocalCoordinates(Context context) { ArrayList<ItemInfo> items = new ArrayList<ItemInfo>(); final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, new String[] { LauncherSettings.Favorites.ITEM_TYPE, LauncherSettings.Favorites.CONTAINER, LauncherSettings.Favorites.SCREEN, LauncherSettings.Favorites.CELLX, LauncherSettings.Favorites.CELLY, LauncherSettings.Favorites.SPANX, LauncherSettings.Favorites.SPANY }, null, null, null); final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SPANY); try { while (c.moveToNext()) { ItemInfo item = new ItemInfo(); item.cellX = c.getInt(cellXIndex); item.cellY = c.getInt(cellYIndex); item.spanX = c.getInt(spanXIndex); item.spanY = c.getInt(spanYIndex); item.container = c.getInt(containerIndex); item.itemType = c.getInt(itemTypeIndex); item.screenId = c.getInt(screenIndex); items.add(item); } } catch (Exception e) { items.clear(); } finally { c.close(); } return items; } /** * Find a folder in the db, creating the FolderInfo if necessary, and adding it to folderList. */ FolderInfo getFolderById(Context context, HashMap<Long,FolderInfo> folderList, long id) { final ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(LauncherSettings.Favorites.CONTENT_URI, null, "_id=? and (itemType=? or itemType=?)", new String[] { String.valueOf(id), String.valueOf(LauncherSettings.Favorites.ITEM_TYPE_FOLDER)}, null); try { if (c.moveToFirst()) { final int itemTypeIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ITEM_TYPE); final int titleIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE); final int containerIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CONTAINER); final int screenIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.CELLY); FolderInfo folderInfo = null; switch (c.getInt(itemTypeIndex)) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: folderInfo = findOrMakeFolder(folderList, id); break; } folderInfo.title = c.getString(titleIndex); folderInfo.id = id; folderInfo.container = c.getInt(containerIndex); folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); return folderInfo; } } finally { c.close(); } return null; } /** * Add an item to the database in a specified container. Sets the container, screen, cellX and * cellY fields of the item. Also assigns an ID to the item. */ static void addItemToDatabase(Context context, final ItemInfo item, final long container, final long screenId, final int cellX, final int cellY, final boolean notify) { item.container = container; item.cellX = cellX; item.cellY = cellY; // We store hotseat items in canonical form which is this orientation invariant position // in the hotseat if (context instanceof Launcher && screenId < 0 && container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { item.screenId = ((Launcher) context).getHotseat().getOrderInHotseat(cellX, cellY); } else { item.screenId = screenId; } final ContentValues values = new ContentValues(); final ContentResolver cr = context.getContentResolver(); item.onAddToDatabase(values); LauncherAppState app = LauncherAppState.getInstance(); item.id = app.getLauncherProvider().generateNewItemId(); values.put(LauncherSettings.Favorites._ID, item.id); item.updateValuesWithCoordinates(values, item.cellX, item.cellY); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Add item (" + item.title + ") to db, id: " + item.id + " (" + container + ", " + screenId + ", " + cellX + ", " + cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.insert(notify ? LauncherSettings.Favorites.CONTENT_URI : LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, values); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { checkItemInfoLocked(item.id, item, null); sBgItemsIdMap.put(item.id, item); switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.put(item.id, (FolderInfo) item); // Fall through case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP || item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { sBgWorkspaceItems.add(item); } else { if (!sBgFolders.containsKey(item.container)) { // Adding an item to a folder that doesn't exist. String msg = "adding item: " + item + " to a folder that " + " doesn't exist"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.add((LauncherAppWidgetInfo) item); break; } } } }; runOnWorkerThread(r); } /** * Creates a new unique child id, for a given cell span across all layouts. */ static int getCellLayoutChildId( long container, long screen, int localCellX, int localCellY, int spanX, int spanY) { return (((int) container & 0xFF) << 24) | ((int) screen & 0xFF) << 16 | (localCellX & 0xFF) << 8 | (localCellY & 0xFF); } static int getCellCountX() { return mCellCountX; } static int getCellCountY() { return mCellCountY; } /** * Updates the model orientation helper to take into account the current layout dimensions * when performing local/canonical coordinate transformations. */ static void updateWorkspaceLayoutCells(int shortAxisCellCount, int longAxisCellCount) { mCellCountX = shortAxisCellCount; mCellCountY = longAxisCellCount; } /** * Removes the specified item from the database * @param context * @param item */ static void deleteItemFromDatabase(Context context, final ItemInfo item) { final ContentResolver cr = context.getContentResolver(); final Uri uriToDelete = LauncherSettings.Favorites.getContentUri(item.id, false); Runnable r = new Runnable() { public void run() { String transaction = "DbDebug Delete item (" + item.title + ") from db, id: " + item.id + " (" + item.container + ", " + item.screenId + ", " + item.cellX + ", " + item.cellY + ")"; Launcher.sDumpLogs.add(transaction); Log.d(TAG, transaction); cr.delete(uriToDelete, null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { switch (item.itemType) { case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: sBgFolders.remove(item.id); for (ItemInfo info: sBgItemsIdMap.values()) { if (info.container == item.id) { // We are deleting a folder which still contains items that // think they are contained by that folder. String msg = "deleting a folder (" + item + ") which still " + "contains items (" + info + ")"; Log.e(TAG, msg); Launcher.dumpDebugLogsToConsole(); } } sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: sBgWorkspaceItems.remove(item); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: sBgAppWidgets.remove((LauncherAppWidgetInfo) item); break; } sBgItemsIdMap.remove(item.id); sBgDbIconCache.remove(item); } } }; runOnWorkerThread(r); } /** * Update the order of the workspace screens in the database. The array list contains * a list of screen ids in the order that they should appear. */ void updateWorkspaceScreenOrder(Context context, final ArrayList<Long> screens) { final ArrayList<Long> screensCopy = new ArrayList<Long>(screens); final ContentResolver cr = context.getContentResolver(); final Uri uri = LauncherSettings.WorkspaceScreens.CONTENT_URI; // Remove any negative screen ids -- these aren't persisted Iterator<Long> iter = screensCopy.iterator(); while (iter.hasNext()) { long id = iter.next(); if (id < 0) { iter.remove(); } } Runnable r = new Runnable() { @Override public void run() { // Clear the table cr.delete(uri, null, null); int count = screens.size(); ContentValues[] values = new ContentValues[count]; for (int i = 0; i < count; i++) { ContentValues v = new ContentValues(); long screenId = screens.get(i); v.put(LauncherSettings.WorkspaceScreens._ID, screenId); v.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i); values[i] = v; } cr.bulkInsert(uri, values); sBgWorkspaceScreens.clear(); sBgWorkspaceScreens.addAll(screensCopy); } }; runOnWorkerThread(r); } /** * Remove the contents of the specified folder from the database */ static void deleteFolderContentsFromDatabase(Context context, final FolderInfo info) { final ContentResolver cr = context.getContentResolver(); Runnable r = new Runnable() { public void run() { cr.delete(LauncherSettings.Favorites.getContentUri(info.id, false), null, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { sBgItemsIdMap.remove(info.id); sBgFolders.remove(info.id); sBgDbIconCache.remove(info); sBgWorkspaceItems.remove(info); } cr.delete(LauncherSettings.Favorites.CONTENT_URI_NO_NOTIFICATION, LauncherSettings.Favorites.CONTAINER + "=" + info.id, null); // Lock on mBgLock *after* the db operation synchronized (sBgLock) { for (ItemInfo childInfo : info.contents) { sBgItemsIdMap.remove(childInfo.id); sBgDbIconCache.remove(childInfo); } } } }; runOnWorkerThread(r); } /** * Set this as the current Launcher activity object for the loader. */ public void initialize(Callbacks callbacks) { synchronized (mLock) { mCallbacks = new WeakReference<Callbacks>(callbacks); } } /** * Call from the handler for ACTION_PACKAGE_ADDED, ACTION_PACKAGE_REMOVED and * ACTION_PACKAGE_CHANGED. */ @Override public void onReceive(Context context, Intent intent) { if (DEBUG_LOADERS) Log.d(TAG, "onReceive intent=" + intent); final String action = intent.getAction(); if (Intent.ACTION_PACKAGE_CHANGED.equals(action) || Intent.ACTION_PACKAGE_REMOVED.equals(action) || Intent.ACTION_PACKAGE_ADDED.equals(action)) { final String packageName = intent.getData().getSchemeSpecificPart(); final boolean replacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); int op = PackageUpdatedTask.OP_NONE; if (packageName == null || packageName.length() == 0) { // they sent us a bad intent return; } if (Intent.ACTION_PACKAGE_CHANGED.equals(action)) { op = PackageUpdatedTask.OP_UPDATE; } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_REMOVE; } // else, we are replacing the package, so a PACKAGE_ADDED will be sent // later, we will update the package at this time } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) { if (!replacing) { op = PackageUpdatedTask.OP_ADD; } else { op = PackageUpdatedTask.OP_UPDATE; } } if (op != PackageUpdatedTask.OP_NONE) { enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName })); } } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(action)) { // First, schedule to add these apps back in. String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask(PackageUpdatedTask.OP_ADD, packages)); // Then, rebind everything. startLoaderFromBackground(); } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) { String[] packages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); enqueuePackageUpdated(new PackageUpdatedTask( PackageUpdatedTask.OP_UNAVAILABLE, packages)); } else if (Intent.ACTION_LOCALE_CHANGED.equals(action)) { // If we have changed locale we need to clear out the labels in all apps/workspace. forceReload(); } else if (Intent.ACTION_CONFIGURATION_CHANGED.equals(action)) { // Check if configuration change was an mcc/mnc change which would affect app resources // and we would need to clear out the labels in all apps/workspace. Same handling as // above for ACTION_LOCALE_CHANGED Configuration currentConfig = context.getResources().getConfiguration(); if (mPreviousConfigMcc != currentConfig.mcc) { Log.d(TAG, "Reload apps on config change. curr_mcc:" + currentConfig.mcc + " prevmcc:" + mPreviousConfigMcc); forceReload(); } // Update previousConfig mPreviousConfigMcc = currentConfig.mcc; } else if (SearchManager.INTENT_GLOBAL_SEARCH_ACTIVITY_CHANGED.equals(action) || SearchManager.INTENT_ACTION_SEARCHABLES_CHANGED.equals(action)) { if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { callbacks.bindSearchablesChanged(); } } } } private void forceReload() { resetLoadedState(true, true); // Do this here because if the launcher activity is running it will be restarted. // If it's not running startLoaderFromBackground will merely tell it that it needs // to reload. startLoaderFromBackground(); } public void resetLoadedState(boolean resetAllAppsLoaded, boolean resetWorkspaceLoaded) { synchronized (mLock) { // Stop any existing loaders first, so they don't set mAllAppsLoaded or // mWorkspaceLoaded to true later stopLoaderLocked(); if (resetAllAppsLoaded) mAllAppsLoaded = false; if (resetWorkspaceLoaded) mWorkspaceLoaded = false; } } /** * When the launcher is in the background, it's possible for it to miss paired * configuration changes. So whenever we trigger the loader from the background * tell the launcher that it needs to re-run the loader when it comes back instead * of doing it now. */ public void startLoaderFromBackground() { boolean runLoader = false; if (mCallbacks != null) { Callbacks callbacks = mCallbacks.get(); if (callbacks != null) { // Only actually run the loader if they're not paused. if (!callbacks.setLoadOnResume()) { runLoader = true; } } } if (runLoader) { startLoader(false, -1); } } // If there is already a loader task running, tell it to stop. // returns true if isLaunching() was true on the old task private boolean stopLoaderLocked() { boolean isLaunching = false; LoaderTask oldTask = mLoaderTask; if (oldTask != null) { if (oldTask.isLaunching()) { isLaunching = true; } oldTask.stopLocked(); } return isLaunching; } public void startLoader(boolean isLaunching, int synchronousBindPage) { synchronized (mLock) { if (DEBUG_LOADERS) { Log.d(TAG, "startLoader isLaunching=" + isLaunching); } // Clear any deferred bind-runnables from the synchronized load process // We must do this before any loading/binding is scheduled below. mDeferredBindRunnables.clear(); // Don't bother to start the thread if we know it's not going to do anything if (mCallbacks != null && mCallbacks.get() != null) { // If there is already one running, tell it to stop. // also, don't downgrade isLaunching if we're already running isLaunching = isLaunching || stopLoaderLocked(); mLoaderTask = new LoaderTask(mApp.getContext(), isLaunching); if (synchronousBindPage > -1 && mAllAppsLoaded && mWorkspaceLoaded) { mLoaderTask.runBindSynchronousPage(synchronousBindPage); } else { sWorkerThread.setPriority(Thread.NORM_PRIORITY); sWorker.post(mLoaderTask); } } } } void bindRemainingSynchronousPages() { // Post the remaining side pages to be loaded if (!mDeferredBindRunnables.isEmpty()) { for (final Runnable r : mDeferredBindRunnables) { mHandler.post(r, MAIN_THREAD_BINDING_RUNNABLE); } mDeferredBindRunnables.clear(); } } public void stopLoader() { synchronized (mLock) { if (mLoaderTask != null) { mLoaderTask.stopLocked(); } } } public boolean isAllAppsLoaded() { return mAllAppsLoaded; } boolean isLoadingWorkspace() { synchronized (mLock) { if (mLoaderTask != null) { return mLoaderTask.isLoadingWorkspace(); } } return false; } /** * Runnable for the thread that loads the contents of the launcher: * - workspace icons * - widgets * - all apps icons */ private class LoaderTask implements Runnable { private Context mContext; private boolean mIsLaunching; private boolean mIsLoadingAndBindingWorkspace; private boolean mStopped; private boolean mLoadAndBindStepFinished; private HashMap<Object, CharSequence> mLabelCache; LoaderTask(Context context, boolean isLaunching) { mContext = context; mIsLaunching = isLaunching; mLabelCache = new HashMap<Object, CharSequence>(); } boolean isLaunching() { return mIsLaunching; } boolean isLoadingWorkspace() { return mIsLoadingAndBindingWorkspace; } /** Returns whether this is an upgrade path */ private boolean loadAndBindWorkspace() { mIsLoadingAndBindingWorkspace = true; // Load the workspace if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindWorkspace mWorkspaceLoaded=" + mWorkspaceLoaded); } boolean isUpgradePath = false; if (!mWorkspaceLoaded) { isUpgradePath = loadWorkspace(); synchronized (LoaderTask.this) { if (mStopped) { return isUpgradePath; } mWorkspaceLoaded = true; } } // Bind the workspace bindWorkspace(-1, isUpgradePath); return isUpgradePath; } private void waitForIdle() { // Wait until the either we're stopped or the other threads are done. // This way we don't start loading all apps until the workspace has settled // down. synchronized (LoaderTask.this) { final long workspaceWaitTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; mHandler.postIdle(new Runnable() { public void run() { synchronized (LoaderTask.this) { mLoadAndBindStepFinished = true; if (DEBUG_LOADERS) { Log.d(TAG, "done with previous binding step"); } LoaderTask.this.notify(); } } }); while (!mStopped && !mLoadAndBindStepFinished && !mFlushingWorkerThread) { try { // Just in case mFlushingWorkerThread changes but we aren't woken up, // wait no longer than 1sec at a time this.wait(1000); } catch (InterruptedException ex) { // Ignore } } if (DEBUG_LOADERS) { Log.d(TAG, "waited " + (SystemClock.uptimeMillis()-workspaceWaitTime) + "ms for previous step to finish binding"); } } } void runBindSynchronousPage(int synchronousBindPage) { if (synchronousBindPage < 0) { // Ensure that we have a valid page index to load synchronously throw new RuntimeException("Should not call runBindSynchronousPage() without " + "valid page index"); } if (!mAllAppsLoaded || !mWorkspaceLoaded) { // Ensure that we don't try and bind a specified page when the pages have not been // loaded already (we should load everything asynchronously in that case) throw new RuntimeException("Expecting AllApps and Workspace to be loaded"); } synchronized (mLock) { if (mIsLoaderTaskRunning) { // Ensure that we are never running the background loading at this point since // we also touch the background collections throw new RuntimeException("Error! Background loading is already running"); } } // XXX: Throw an exception if we are already loading (since we touch the worker thread // data structures, we can't allow any other thread to touch that data, but because // this call is synchronous, we can get away with not locking). // The LauncherModel is static in the LauncherAppState and mHandler may have queued // operations from the previous activity. We need to ensure that all queued operations // are executed before any synchronous binding work is done. mHandler.flush(); // Divide the set of loaded items into those that we are binding synchronously, and // everything else that is to be bound normally (asynchronously). bindWorkspace(synchronousBindPage, false); // XXX: For now, continue posting the binding of AllApps as there are other issues that // arise from that. onlyBindAllApps(); } public void run() { boolean isUpgrade = false; synchronized (mLock) { mIsLoaderTaskRunning = true; } // Optimize for end-user experience: if the Launcher is up and // running with the // All Apps interface in the foreground, load All Apps first. Otherwise, load the // workspace first (default). final Callbacks cbk = mCallbacks.get(); keep_running: { // Elevate priority when Home launches for the first time to avoid // starving at boot time. Staring at a blank home is not cool. synchronized (mLock) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to " + (mIsLaunching ? "DEFAULT" : "BACKGROUND")); android.os.Process.setThreadPriority(mIsLaunching ? Process.THREAD_PRIORITY_DEFAULT : Process.THREAD_PRIORITY_BACKGROUND); } if (DEBUG_LOADERS) Log.d(TAG, "step 1: loading workspace"); isUpgrade = loadAndBindWorkspace(); if (mStopped) { break keep_running; } // Whew! Hard work done. Slow us down, and wait until the UI thread has // settled down. synchronized (mLock) { if (mIsLaunching) { if (DEBUG_LOADERS) Log.d(TAG, "Setting thread priority to BACKGROUND"); android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); } } waitForIdle(); // second step if (DEBUG_LOADERS) Log.d(TAG, "step 2: loading all apps"); loadAndBindAllApps(); // Restore the default thread priority after we are done loading items synchronized (mLock) { android.os.Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); } } // Update the saved icons if necessary if (DEBUG_LOADERS) Log.d(TAG, "Comparing loaded icons to database icons"); synchronized (sBgLock) { for (Object key : sBgDbIconCache.keySet()) { updateSavedIcon(mContext, (ShortcutInfo) key, sBgDbIconCache.get(key)); } sBgDbIconCache.clear(); } // Ensure that all the applications that are in the system are represented on the home // screen. if (!isUpgrade) { verifyApplications(); } // Clear out this reference, otherwise we end up holding it until all of the // callback runnables are done. mContext = null; synchronized (mLock) { // If we are still the last one to be scheduled, remove ourselves. if (mLoaderTask == this) { mLoaderTask = null; } mIsLoaderTaskRunning = false; } } public void stopLocked() { synchronized (LoaderTask.this) { mStopped = true; this.notify(); } } /** * Gets the callbacks object. If we've been stopped, or if the launcher object * has somehow been garbage collected, return null instead. Pass in the Callbacks * object that was around when the deferred message was scheduled, and if there's * a new Callbacks object around then also return null. This will save us from * calling onto it with data that will be ignored. */ Callbacks tryGetCallbacks(Callbacks oldCallbacks) { synchronized (mLock) { if (mStopped) { return null; } if (mCallbacks == null) { return null; } final Callbacks callbacks = mCallbacks.get(); if (callbacks != oldCallbacks) { return null; } if (callbacks == null) { Log.w(TAG, "no mCallbacks"); return null; } return callbacks; } } private void verifyApplications() { final Context context = mApp.getContext(); // Cross reference all the applications in our apps list with items in the workspace ArrayList<ItemInfo> tmpInfos; ArrayList<ItemInfo> added = new ArrayList<ItemInfo>(); synchronized (sBgLock) { for (ApplicationInfo app : mBgAllAppsList.data) { tmpInfos = getItemInfoForComponentName(app.componentName); if (tmpInfos.isEmpty()) { // We are missing an application icon, so add this to the workspace added.add(app); // This is a rare event, so lets log it Log.e(TAG, "Missing Application on load: " + app); } } } if (!added.isEmpty()) { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, added, cb); } } // check & update map of what's occupied; used to discard overlapping/invalid items private boolean checkItemPlacement(HashMap<Long, ItemInfo[][]> occupied, ItemInfo item) { long containerIndex = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { if (occupied.containsKey(LauncherSettings.Favorites.CONTAINER_HOTSEAT)) { if (occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0] != null) { Log.e(TAG, "Error loading shortcut into hotseat " + item + " into position (" + item.screenId + ":" + item.cellX + "," + item.cellY + ") occupied by " + occupied.get(LauncherSettings.Favorites.CONTAINER_HOTSEAT) [(int) item.screenId][0]); return false; } } else { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; items[(int) item.screenId][0] = item; occupied.put((long) LauncherSettings.Favorites.CONTAINER_HOTSEAT, items); return true; } } else if (item.container != LauncherSettings.Favorites.CONTAINER_DESKTOP) { // Skip further checking if it is not the hotseat or workspace container return true; } if (!occupied.containsKey(item.screenId)) { ItemInfo[][] items = new ItemInfo[mCellCountX + 1][mCellCountY + 1]; occupied.put(item.screenId, items); } ItemInfo[][] screens = occupied.get(item.screenId); // Check if any workspace icons overlap with each other for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { if (screens[x][y] != null) { Log.e(TAG, "Error loading shortcut " + item + " into cell (" + containerIndex + "-" + item.screenId + ":" + x + "," + y + ") occupied by " + screens[x][y]); return false; } } } for (int x = item.cellX; x < (item.cellX+item.spanX); x++) { for (int y = item.cellY; y < (item.cellY+item.spanY); y++) { screens[x][y] = item; } } return true; } /** Returns whether this is an upgradge path */ private boolean loadWorkspace() { final long t = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; final Context context = mContext; final ContentResolver contentResolver = context.getContentResolver(); final PackageManager manager = context.getPackageManager(); final AppWidgetManager widgets = AppWidgetManager.getInstance(context); final boolean isSafeMode = manager.isSafeMode(); // Make sure the default workspace is loaded, if needed mApp.getLauncherProvider().loadDefaultFavoritesIfNecessary(0); // Check if we need to do any upgrade-path logic boolean loadedOldDb = mApp.getLauncherProvider().justLoadedOldDb(); synchronized (sBgLock) { sBgWorkspaceItems.clear(); sBgAppWidgets.clear(); sBgFolders.clear(); sBgItemsIdMap.clear(); sBgDbIconCache.clear(); sBgWorkspaceScreens.clear(); final ArrayList<Long> itemsToRemove = new ArrayList<Long>(); final Uri contentUri = LauncherSettings.Favorites.CONTENT_URI; final Cursor c = contentResolver.query(contentUri, null, null, null, null); // +1 for the hotseat (it can be larger than the workspace) // Load workspace in reverse order to ensure that latest items are loaded first (and // before any earlier duplicates) final HashMap<Long, ItemInfo[][]> occupied = new HashMap<Long, ItemInfo[][]>(); try { final int idIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites._ID); final int intentIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.INTENT); final int titleIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.TITLE); final int iconTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_TYPE); final int iconIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.ICON); final int iconPackageIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_PACKAGE); final int iconResourceIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ICON_RESOURCE); final int containerIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.CONTAINER); final int itemTypeIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.ITEM_TYPE); final int appWidgetIdIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.APPWIDGET_ID); final int screenIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SCREEN); final int cellXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLX); final int cellYIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.CELLY); final int spanXIndex = c.getColumnIndexOrThrow (LauncherSettings.Favorites.SPANX); final int spanYIndex = c.getColumnIndexOrThrow( LauncherSettings.Favorites.SPANY); //final int uriIndex = c.getColumnIndexOrThrow(LauncherSettings.Favorites.URI); //final int displayModeIndex = c.getColumnIndexOrThrow( // LauncherSettings.Favorites.DISPLAY_MODE); ShortcutInfo info; String intentDescription; LauncherAppWidgetInfo appWidgetInfo; int container; long id; Intent intent; while (!mStopped && c.moveToNext()) { try { int itemType = c.getInt(itemTypeIndex); switch (itemType) { case LauncherSettings.Favorites.ITEM_TYPE_APPLICATION: case LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT: id = c.getLong(idIndex); intentDescription = c.getString(intentIndex); try { intent = Intent.parseUri(intentDescription, 0); ComponentName cn = intent.getComponent(); if (!isValidPackageComponent(manager, cn)) { if (!mAppsCanBeOnRemoveableStorage) { // Log the invalid package, and remove it from the db Uri uri = LauncherSettings.Favorites.getContentUri(id, false); contentResolver.delete(uri, null, null); Log.e(TAG, "Invalid package removed: " + cn); } else { // If apps can be on external storage, then we just // leave them for the user to remove (maybe add // visual treatment to it) Log.e(TAG, "Invalid package found: " + cn); } continue; } } catch (URISyntaxException e) { continue; } if (itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION) { info = getShortcutInfo(manager, intent, context, c, iconIndex, titleIndex, mLabelCache); } else { info = getShortcutInfo(c, context, iconTypeIndex, iconPackageIndex, iconResourceIndex, iconIndex, titleIndex); // App shortcuts that used to be automatically added to Launcher // didn't always have the correct intent flags set, so do that // here if (intent.getAction() != null && intent.getCategories() != null && intent.getAction().equals(Intent.ACTION_MAIN) && intent.getCategories().contains(Intent.CATEGORY_LAUNCHER)) { intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } if (info != null) { info.id = id; info.intent = intent; container = c.getInt(containerIndex); info.container = container; info.screenId = c.getInt(screenIndex); info.cellX = c.getInt(cellXIndex); info.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, info)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(info); break; default: // Item is in a user folder FolderInfo folderInfo = findOrMakeFolder(sBgFolders, container); folderInfo.add(info); break; } sBgItemsIdMap.put(info.id, info); // now that we've loaded everthing re-save it with the // icon in case it disappears somehow. queueIconToBeChecked(sBgDbIconCache, info, c, iconIndex); } else { throw new RuntimeException("Unexpected null ShortcutInfo"); } break; case LauncherSettings.Favorites.ITEM_TYPE_FOLDER: id = c.getLong(idIndex); FolderInfo folderInfo = findOrMakeFolder(sBgFolders, id); folderInfo.title = c.getString(titleIndex); folderInfo.id = id; container = c.getInt(containerIndex); folderInfo.container = container; folderInfo.screenId = c.getInt(screenIndex); folderInfo.cellX = c.getInt(cellXIndex); folderInfo.cellY = c.getInt(cellYIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, folderInfo)) { break; } switch (container) { case LauncherSettings.Favorites.CONTAINER_DESKTOP: case LauncherSettings.Favorites.CONTAINER_HOTSEAT: sBgWorkspaceItems.add(folderInfo); break; } sBgItemsIdMap.put(folderInfo.id, folderInfo); sBgFolders.put(folderInfo.id, folderInfo); break; case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET: // Read all Launcher-specific widget details int appWidgetId = c.getInt(appWidgetIdIndex); id = c.getLong(idIndex); final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(appWidgetId); if (!isSafeMode && (provider == null || provider.provider == null || provider.provider.getPackageName() == null)) { String log = "Deleting widget that isn't installed anymore: id=" + id + " appWidgetId=" + appWidgetId; Log.e(TAG, log); Launcher.sDumpLogs.add(log); itemsToRemove.add(id); } else { appWidgetInfo = new LauncherAppWidgetInfo(appWidgetId, provider.provider); appWidgetInfo.id = id; appWidgetInfo.screenId = c.getInt(screenIndex); appWidgetInfo.cellX = c.getInt(cellXIndex); appWidgetInfo.cellY = c.getInt(cellYIndex); appWidgetInfo.spanX = c.getInt(spanXIndex); appWidgetInfo.spanY = c.getInt(spanYIndex); int[] minSpan = Launcher.getMinSpanForWidget(context, provider); appWidgetInfo.minSpanX = minSpan[0]; appWidgetInfo.minSpanY = minSpan[1]; container = c.getInt(containerIndex); if (container != LauncherSettings.Favorites.CONTAINER_DESKTOP && container != LauncherSettings.Favorites.CONTAINER_HOTSEAT) { Log.e(TAG, "Widget found where container != " + "CONTAINER_DESKTOP nor CONTAINER_HOTSEAT - ignoring!"); continue; } appWidgetInfo.container = c.getInt(containerIndex); // check & update map of what's occupied if (!checkItemPlacement(occupied, appWidgetInfo)) { break; } sBgItemsIdMap.put(appWidgetInfo.id, appWidgetInfo); sBgAppWidgets.add(appWidgetInfo); } break; } } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { if (c != null) { c.close(); } } if (itemsToRemove.size() > 0) { ContentProviderClient client = contentResolver.acquireContentProviderClient( LauncherSettings.Favorites.CONTENT_URI); // Remove dead items for (long id : itemsToRemove) { if (DEBUG_LOADERS) { Log.d(TAG, "Removed id = " + id); } // Don't notify content observers try { client.delete(LauncherSettings.Favorites.getContentUri(id, false), null, null); } catch (RemoteException e) { Log.w(TAG, "Could not remove id = " + id); } } } if (loadedOldDb) { long maxScreenId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && !sBgWorkspaceScreens.contains(screenId)) { sBgWorkspaceScreens.add(screenId); if (screenId > maxScreenId) { maxScreenId = screenId; } } } Collections.sort(sBgWorkspaceScreens); mApp.getLauncherProvider().updateMaxScreenId(maxScreenId); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); // Update the max item id after we load an old db long maxItemId = 0; // If we're importing we use the old screen order. for (ItemInfo item: sBgItemsIdMap.values()) { maxItemId = Math.max(maxItemId, item.id); } LauncherAppState app = LauncherAppState.getInstance(); app.getLauncherProvider().updateMaxItemId(maxItemId); } else { Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI; final Cursor sc = contentResolver.query(screensUri, null, null, null, null); TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>(); try { final int idIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens._ID); final int rankIndex = sc.getColumnIndexOrThrow( LauncherSettings.WorkspaceScreens.SCREEN_RANK); while (sc.moveToNext()) { try { long screenId = sc.getLong(idIndex); int rank = sc.getInt(rankIndex); orderedScreens.put(rank, screenId); } catch (Exception e) { Log.w(TAG, "Desktop items loading interrupted:", e); } } } finally { sc.close(); } Iterator<Integer> iter = orderedScreens.keySet().iterator(); while (iter.hasNext()) { sBgWorkspaceScreens.add(orderedScreens.get(iter.next())); } // Remove any empty screens ArrayList<Long> unusedScreens = new ArrayList<Long>(); unusedScreens.addAll(sBgWorkspaceScreens); for (ItemInfo item: sBgItemsIdMap.values()) { long screenId = item.screenId; if (item.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && unusedScreens.contains(screenId)) { unusedScreens.remove(screenId); } } // If there are any empty screens remove them, and update. if (unusedScreens.size() != 0) { sBgWorkspaceScreens.removeAll(unusedScreens); updateWorkspaceScreenOrder(context, sBgWorkspaceScreens); } } if (DEBUG_LOADERS) { Log.d(TAG, "loaded workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); Log.d(TAG, "workspace layout: "); int nScreens = occupied.size(); for (int y = 0; y < mCellCountY; y++) { String line = ""; Iterator<Long> iter = occupied.keySet().iterator(); while (iter.hasNext()) { long screenId = iter.next(); if (screenId > 0) { line += " | "; } for (int x = 0; x < mCellCountX; x++) { line += ((occupied.get(screenId)[x][y] != null) ? "#" : "."); } } Log.d(TAG, "[ " + line + " ]"); } } } return loadedOldDb; } /** Filters the set of items who are directly or indirectly (via another container) on the * specified screen. */ private void filterCurrentWorkspaceItems(int currentScreen, ArrayList<ItemInfo> allWorkspaceItems, ArrayList<ItemInfo> currentScreenItems, ArrayList<ItemInfo> otherScreenItems) { // Purge any null ItemInfos Iterator<ItemInfo> iter = allWorkspaceItems.iterator(); while (iter.hasNext()) { ItemInfo i = iter.next(); if (i == null) { iter.remove(); } } // If we aren't filtering on a screen, then the set of items to load is the full set of // items given. if (currentScreen < 0) { currentScreenItems.addAll(allWorkspaceItems); } // Order the set of items by their containers first, this allows use to walk through the // list sequentially, build up a list of containers that are in the specified screen, // as well as all items in those containers. Set<Long> itemsOnScreen = new HashSet<Long>(); Collections.sort(allWorkspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { return (int) (lhs.container - rhs.container); } }); for (ItemInfo info : allWorkspaceItems) { if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP) { if (info.screenId == currentScreen) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } else if (info.container == LauncherSettings.Favorites.CONTAINER_HOTSEAT) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { if (itemsOnScreen.contains(info.container)) { currentScreenItems.add(info); itemsOnScreen.add(info.id); } else { otherScreenItems.add(info); } } } } /** Filters the set of widgets which are on the specified screen. */ private void filterCurrentAppWidgets(int currentScreen, ArrayList<LauncherAppWidgetInfo> appWidgets, ArrayList<LauncherAppWidgetInfo> currentScreenWidgets, ArrayList<LauncherAppWidgetInfo> otherScreenWidgets) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenWidgets.addAll(appWidgets); } for (LauncherAppWidgetInfo widget : appWidgets) { if (widget == null) continue; if (widget.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && widget.screenId == currentScreen) { currentScreenWidgets.add(widget); } else { otherScreenWidgets.add(widget); } } } /** Filters the set of folders which are on the specified screen. */ private void filterCurrentFolders(int currentScreen, HashMap<Long, ItemInfo> itemsIdMap, HashMap<Long, FolderInfo> folders, HashMap<Long, FolderInfo> currentScreenFolders, HashMap<Long, FolderInfo> otherScreenFolders) { // If we aren't filtering on a screen, then the set of items to load is the full set of // widgets given. if (currentScreen < 0) { currentScreenFolders.putAll(folders); } for (long id : folders.keySet()) { ItemInfo info = itemsIdMap.get(id); FolderInfo folder = folders.get(id); if (info == null || folder == null) continue; if (info.container == LauncherSettings.Favorites.CONTAINER_DESKTOP && info.screenId == currentScreen) { currentScreenFolders.put(id, folder); } else { otherScreenFolders.put(id, folder); } } } /** Sorts the set of items by hotseat, workspace (spatially from top to bottom, left to * right) */ private void sortWorkspaceItemsSpatially(ArrayList<ItemInfo> workspaceItems) { // XXX: review this Collections.sort(workspaceItems, new Comparator<ItemInfo>() { @Override public int compare(ItemInfo lhs, ItemInfo rhs) { int cellCountX = LauncherModel.getCellCountX(); int cellCountY = LauncherModel.getCellCountY(); int screenOffset = cellCountX * cellCountY; int containerOffset = screenOffset * (Launcher.SCREEN_COUNT + 1); // +1 hotseat long lr = (lhs.container * containerOffset + lhs.screenId * screenOffset + lhs.cellY * cellCountX + lhs.cellX); long rr = (rhs.container * containerOffset + rhs.screenId * screenOffset + rhs.cellY * cellCountX + rhs.cellX); return (int) (lr - rr); } }); } private void bindWorkspaceScreens(final Callbacks oldCallbacks, final ArrayList<Long> orderedScreens) { final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindScreens(orderedScreens); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } private void bindWorkspaceItems(final Callbacks oldCallbacks, final ArrayList<ItemInfo> workspaceItems, final ArrayList<LauncherAppWidgetInfo> appWidgets, final HashMap<Long, FolderInfo> folders, ArrayList<Runnable> deferredBindRunnables) { final boolean postOnMainThread = (deferredBindRunnables != null); // Bind the workspace items int N = workspaceItems.size(); for (int i = 0; i < N; i += ITEMS_CHUNK) { final int start = i; final int chunkSize = (i+ITEMS_CHUNK <= N) ? ITEMS_CHUNK : (N-i); final Runnable r = new Runnable() { @Override public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindItems(workspaceItems, start, start+chunkSize, false); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the folders if (!folders.isEmpty()) { final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindFolders(folders); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } // Bind the widgets, one at a time N = appWidgets.size(); for (int i = 0; i < N; i++) { final LauncherAppWidgetInfo widget = appWidgets.get(i); final Runnable r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAppWidget(widget); } } }; if (postOnMainThread) { deferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } } /** * Binds all loaded data to actual views on the main thread. */ private void bindWorkspace(int synchronizeBindPage, final boolean isUpgradePath) { final long t = SystemClock.uptimeMillis(); Runnable r; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher"); return; } final boolean isLoadingSynchronously = (synchronizeBindPage > -1); final int currentScreen = isLoadingSynchronously ? synchronizeBindPage : oldCallbacks.getCurrentWorkspaceScreen(); // Load all the items that are on the current page first (and in the process, unbind // all the existing workspace items before we call startBinding() below. unbindWorkspaceItemsOnMainThread(); ArrayList<ItemInfo> workspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> appWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> folders = new HashMap<Long, FolderInfo>(); HashMap<Long, ItemInfo> itemsIdMap = new HashMap<Long, ItemInfo>(); ArrayList<Long> orderedScreenIds = new ArrayList<Long>(); synchronized (sBgLock) { workspaceItems.addAll(sBgWorkspaceItems); appWidgets.addAll(sBgAppWidgets); folders.putAll(sBgFolders); itemsIdMap.putAll(sBgItemsIdMap); orderedScreenIds.addAll(sBgWorkspaceScreens); } ArrayList<ItemInfo> currentWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<ItemInfo> otherWorkspaceItems = new ArrayList<ItemInfo>(); ArrayList<LauncherAppWidgetInfo> currentAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); ArrayList<LauncherAppWidgetInfo> otherAppWidgets = new ArrayList<LauncherAppWidgetInfo>(); HashMap<Long, FolderInfo> currentFolders = new HashMap<Long, FolderInfo>(); HashMap<Long, FolderInfo> otherFolders = new HashMap<Long, FolderInfo>(); // Separate the items that are on the current screen, and all the other remaining items filterCurrentWorkspaceItems(currentScreen, workspaceItems, currentWorkspaceItems, otherWorkspaceItems); filterCurrentAppWidgets(currentScreen, appWidgets, currentAppWidgets, otherAppWidgets); filterCurrentFolders(currentScreen, itemsIdMap, folders, currentFolders, otherFolders); sortWorkspaceItemsSpatially(currentWorkspaceItems); sortWorkspaceItemsSpatially(otherWorkspaceItems); // Tell the workspace that we're about to start binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.startBinding(); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); bindWorkspaceScreens(oldCallbacks, orderedScreenIds); // Load items on the current page bindWorkspaceItems(oldCallbacks, currentWorkspaceItems, currentAppWidgets, currentFolders, null); if (isLoadingSynchronously) { r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.onPageBoundSynchronously(currentScreen); } } }; runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } // Load all the remaining pages (if we are loading synchronously, we want to defer this // work until after the first render) mDeferredBindRunnables.clear(); bindWorkspaceItems(oldCallbacks, otherWorkspaceItems, otherAppWidgets, otherFolders, (isLoadingSynchronously ? mDeferredBindRunnables : null)); // Tell the workspace that we're done binding items r = new Runnable() { public void run() { Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.finishBindingItems(isUpgradePath); } // If we're profiling, ensure this is the last thing in the queue. if (DEBUG_LOADERS) { Log.d(TAG, "bound workspace in " + (SystemClock.uptimeMillis()-t) + "ms"); } mIsLoadingAndBindingWorkspace = false; } }; if (isLoadingSynchronously) { mDeferredBindRunnables.add(r); } else { runOnMainThread(r, MAIN_THREAD_BINDING_RUNNABLE); } } private void loadAndBindAllApps() { if (DEBUG_LOADERS) { Log.d(TAG, "loadAndBindAllApps mAllAppsLoaded=" + mAllAppsLoaded); } if (!mAllAppsLoaded) { loadAllApps(); synchronized (LoaderTask.this) { if (mStopped) { return; } mAllAppsLoaded = true; } } else { onlyBindAllApps(); } } private void onlyBindAllApps() { final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (onlyBindAllApps)"); return; } // shallow copy @SuppressWarnings("unchecked") final ArrayList<ApplicationInfo> list = (ArrayList<ApplicationInfo>) mBgAllAppsList.data.clone(); Runnable r = new Runnable() { public void run() { final long t = SystemClock.uptimeMillis(); final Callbacks callbacks = tryGetCallbacks(oldCallbacks); if (callbacks != null) { callbacks.bindAllApplications(list); } if (DEBUG_LOADERS) { Log.d(TAG, "bound all " + list.size() + " apps from cache in " + (SystemClock.uptimeMillis()-t) + "ms"); } } }; boolean isRunningOnMainThread = !(sWorkerThread.getThreadId() == Process.myTid()); if (isRunningOnMainThread) { r.run(); } else { mHandler.post(r); } } private void loadAllApps() { final long loadTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; // Don't use these two variables in any of the callback runnables. // Otherwise we hold a reference to them. final Callbacks oldCallbacks = mCallbacks.get(); if (oldCallbacks == null) { // This launcher has exited and nobody bothered to tell us. Just bail. Log.w(TAG, "LoaderTask running with no launcher (loadAllApps)"); return; } final PackageManager packageManager = mContext.getPackageManager(); final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null); mainIntent.addCategory(Intent.CATEGORY_LAUNCHER); // Clear the list of apps mBgAllAppsList.clear(); // Query for the set of apps final long qiaTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0); if (DEBUG_LOADERS) { Log.d(TAG, "queryIntentActivities took " + (SystemClock.uptimeMillis()-qiaTime) + "ms"); Log.d(TAG, "queryIntentActivities got " + apps.size() + " apps"); } // Fail if we don't have any apps if (apps == null || apps.isEmpty()) { return; } // Sort the applications by name final long sortTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; Collections.sort(apps, new LauncherModel.ShortcutNameComparator(packageManager, mLabelCache)); if (DEBUG_LOADERS) { Log.d(TAG, "sort took " + (SystemClock.uptimeMillis()-sortTime) + "ms"); } // Create the ApplicationInfos final long addTime = DEBUG_LOADERS ? SystemClock.uptimeMillis() : 0; for (int i = 0; i < apps.size(); i++) { // This builds the icon bitmaps. mBgAllAppsList.add(new ApplicationInfo(packageManager, apps.get(i), mIconCache, mLabelCache)); } final Callbacks callbacks = tryGetCallbacks(oldCallbacks); final ArrayList<ApplicationInfo> added = mBgAllAppsList.added; mBgAllAppsList.added = new ArrayList<ApplicationInfo>(); // Post callback on main thread mHandler.post(new Runnable() { public void run() { final long bindTime = SystemClock.uptimeMillis(); if (callbacks != null) { callbacks.bindAllApplications(added); if (DEBUG_LOADERS) { Log.d(TAG, "bound " + added.size() + " apps in " + (SystemClock.uptimeMillis() - bindTime) + "ms"); } } else { Log.i(TAG, "not binding apps: no Launcher activity"); } } }); if (DEBUG_LOADERS) { Log.d(TAG, "Icons processed in " + (SystemClock.uptimeMillis() - loadTime) + "ms"); } } public void dumpState() { synchronized (sBgLock) { Log.d(TAG, "mLoaderTask.mContext=" + mContext); Log.d(TAG, "mLoaderTask.mIsLaunching=" + mIsLaunching); Log.d(TAG, "mLoaderTask.mStopped=" + mStopped); Log.d(TAG, "mLoaderTask.mLoadAndBindStepFinished=" + mLoadAndBindStepFinished); Log.d(TAG, "mItems size=" + sBgWorkspaceItems.size()); } } } void enqueuePackageUpdated(PackageUpdatedTask task) { sWorker.post(task); } private class PackageUpdatedTask implements Runnable { int mOp; String[] mPackages; public static final int OP_NONE = 0; public static final int OP_ADD = 1; public static final int OP_UPDATE = 2; public static final int OP_REMOVE = 3; // uninstlled public static final int OP_UNAVAILABLE = 4; // external media unmounted public PackageUpdatedTask(int op, String[] packages) { mOp = op; mPackages = packages; } public void run() { final Context context = mApp.getContext(); final String[] packages = mPackages; final int N = packages.length; switch (mOp) { case OP_ADD: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.addPackage " + packages[i]); mBgAllAppsList.addPackage(context, packages[i]); } break; case OP_UPDATE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.updatePackage " + packages[i]); mBgAllAppsList.updatePackage(context, packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; case OP_REMOVE: case OP_UNAVAILABLE: for (int i=0; i<N; i++) { if (DEBUG_LOADERS) Log.d(TAG, "mAllAppsList.removePackage " + packages[i]); mBgAllAppsList.removePackage(packages[i]); WidgetPreviewLoader.removeFromDb( mApp.getWidgetPreviewCacheDb(), packages[i]); } break; } ArrayList<ApplicationInfo> added = null; ArrayList<ApplicationInfo> modified = null; final ArrayList<ApplicationInfo> removedApps = new ArrayList<ApplicationInfo>(); if (mBgAllAppsList.added.size() > 0) { added = new ArrayList<ApplicationInfo>(mBgAllAppsList.added); mBgAllAppsList.added.clear(); } if (mBgAllAppsList.modified.size() > 0) { modified = new ArrayList<ApplicationInfo>(mBgAllAppsList.modified); mBgAllAppsList.modified.clear(); } if (mBgAllAppsList.removed.size() > 0) { removedApps.addAll(mBgAllAppsList.removed); mBgAllAppsList.removed.clear(); } final Callbacks callbacks = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == null) { Log.w(TAG, "Nobody to tell about the new app. Launcher is probably loading."); return; } if (added != null) { // Ensure that we add all the workspace applications to the db final ArrayList<ItemInfo> addedInfos = new ArrayList<ItemInfo>(added); Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; addAndBindAddedApps(context, addedInfos, cb); } if (modified != null) { final ArrayList<ApplicationInfo> modifiedFinal = modified; // Update the launcher db to reflect the changes for (ApplicationInfo a : modifiedFinal) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { if (isShortcutInfoUpdateable(i)) { ShortcutInfo info = (ShortcutInfo) i; info.title = a.title.toString(); updateItemInDatabase(context, info); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindAppsUpdated(modifiedFinal); } } }); } // If a package has been removed, or an app has been removed as a result of // an update (for example), make the removed callback. if (mOp == OP_REMOVE || !removedApps.isEmpty()) { final boolean packageRemoved = (mOp == OP_REMOVE); final ArrayList<String> removedPackageNames = new ArrayList<String>(Arrays.asList(packages)); // Update the launcher db to reflect the removal of apps if (packageRemoved) { for (String pn : removedPackageNames) { ArrayList<ItemInfo> infos = getItemInfoForPackageName(pn); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } else { for (ApplicationInfo a : removedApps) { ArrayList<ItemInfo> infos = getItemInfoForComponentName(a.componentName); for (ItemInfo i : infos) { deleteItemFromDatabase(context, i); } } } mHandler.post(new Runnable() { public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindComponentsRemoved(removedPackageNames, removedApps, packageRemoved); } } }); } final ArrayList<Object> widgetsAndShortcuts = getSortedWidgetsAndShortcuts(context); mHandler.post(new Runnable() { @Override public void run() { Callbacks cb = mCallbacks != null ? mCallbacks.get() : null; if (callbacks == cb && cb != null) { callbacks.bindPackagesUpdated(widgetsAndShortcuts); } } }); } } // Returns a list of ResolveInfos/AppWindowInfos in sorted order public static ArrayList<Object> getSortedWidgetsAndShortcuts(Context context) { PackageManager packageManager = context.getPackageManager(); final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>(); widgetsAndShortcuts.addAll(AppWidgetManager.getInstance(context).getInstalledProviders()); Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT); widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0)); Collections.sort(widgetsAndShortcuts, new LauncherModel.WidgetAndShortcutNameComparator(packageManager)); return widgetsAndShortcuts; } private boolean isValidPackageComponent(PackageManager pm, ComponentName cn) { if (cn == null) { return false; } try { return (pm.getActivityInfo(cn, 0) != null); } catch (NameNotFoundException e) { return false; } } /** * This is called from the code that adds shortcuts from the intent receiver. This * doesn't have a Cursor, but */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context) { return getShortcutInfo(manager, intent, context, null, -1, -1, null); } /** * Make an ShortcutInfo object for a shortcut that is an application. * * If c is not null, then it will be used to fill in missing data like the title and icon. */ public ShortcutInfo getShortcutInfo(PackageManager manager, Intent intent, Context context, Cursor c, int iconIndex, int titleIndex, HashMap<Object, CharSequence> labelCache) { ComponentName componentName = intent.getComponent(); final ShortcutInfo info = new ShortcutInfo(); if (!isValidPackageComponent(manager, componentName)) { Log.d(TAG, "Invalid package found in getShortcutInfo: " + componentName); return null; } else { try { PackageInfo pi = manager.getPackageInfo(componentName.getPackageName(), 0); info.initFlagsAndFirstInstallTime(pi); } catch (NameNotFoundException e) { Log.d(TAG, "getPackInfo failed for package " + componentName.getPackageName()); } } // TODO: See if the PackageManager knows about this case. If it doesn't // then return null & delete this. // the resource -- This may implicitly give us back the fallback icon, // but don't worry about that. All we're doing with usingFallbackIcon is // to avoid saving lots of copies of that in the database, and most apps // have icons anyway. // Attempt to use queryIntentActivities to get the ResolveInfo (with IntentFilter info) and // if that fails, or is ambiguious, fallback to the standard way of getting the resolve info // via resolveActivity(). Bitmap icon = null; ResolveInfo resolveInfo = null; ComponentName oldComponent = intent.getComponent(); Intent newIntent = new Intent(intent.getAction(), null); newIntent.addCategory(Intent.CATEGORY_LAUNCHER); newIntent.setPackage(oldComponent.getPackageName()); List<ResolveInfo> infos = manager.queryIntentActivities(newIntent, 0); for (ResolveInfo i : infos) { ComponentName cn = new ComponentName(i.activityInfo.packageName, i.activityInfo.name); if (cn.equals(oldComponent)) { resolveInfo = i; } } if (resolveInfo == null) { resolveInfo = manager.resolveActivity(intent, 0); } if (resolveInfo != null) { icon = mIconCache.getIcon(componentName, resolveInfo, labelCache); } // the db if (icon == null) { if (c != null) { icon = getIconFromCursor(c, iconIndex, context); } } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } info.setIcon(icon); // from the resource if (resolveInfo != null) { ComponentName key = LauncherModel.getComponentNameFromResolveInfo(resolveInfo); if (labelCache != null && labelCache.containsKey(key)) { info.title = labelCache.get(key); } else { info.title = resolveInfo.activityInfo.loadLabel(manager); if (labelCache != null) { labelCache.put(key, info.title); } } } // from the db if (info.title == null) { if (c != null) { info.title = c.getString(titleIndex); } } // fall back to the class name of the activity if (info.title == null) { info.title = componentName.getClassName(); } info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION; return info; } static ArrayList<ItemInfo> filterItemInfos(Collection<ItemInfo> infos, ItemInfoFilter f) { HashSet<ItemInfo> filtered = new HashSet<ItemInfo>(); for (ItemInfo i : infos) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; ComponentName cn = info.intent.getComponent(); if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } else if (i instanceof FolderInfo) { FolderInfo info = (FolderInfo) i; for (ShortcutInfo s : info.contents) { ComponentName cn = s.intent.getComponent(); if (cn != null && f.filterItem(info, s, cn)) { filtered.add(s); } } } else if (i instanceof LauncherAppWidgetInfo) { LauncherAppWidgetInfo info = (LauncherAppWidgetInfo) i; ComponentName cn = info.providerName; if (cn != null && f.filterItem(null, info, cn)) { filtered.add(info); } } } return new ArrayList<ItemInfo>(filtered); } private ArrayList<ItemInfo> getItemInfoForPackageName(final String pn) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.getPackageName().equals(pn); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } private ArrayList<ItemInfo> getItemInfoForComponentName(final ComponentName cname) { HashSet<ItemInfo> infos = new HashSet<ItemInfo>(); ItemInfoFilter filter = new ItemInfoFilter() { @Override public boolean filterItem(ItemInfo parent, ItemInfo info, ComponentName cn) { return cn.equals(cname); } }; return filterItemInfos(sBgItemsIdMap.values(), filter); } public static boolean isShortcutInfoUpdateable(ItemInfo i) { if (i instanceof ShortcutInfo) { ShortcutInfo info = (ShortcutInfo) i; // We need to check for ACTION_MAIN otherwise getComponent() might // return null for some shortcuts (for instance, for shortcuts to // web pages.) Intent intent = info.intent; ComponentName name = intent.getComponent(); if (info.itemType == LauncherSettings.Favorites.ITEM_TYPE_APPLICATION && Intent.ACTION_MAIN.equals(intent.getAction()) && name != null) { return true; } } return false; } /** * Make an ShortcutInfo object for a shortcut that isn't an application. */ private ShortcutInfo getShortcutInfo(Cursor c, Context context, int iconTypeIndex, int iconPackageIndex, int iconResourceIndex, int iconIndex, int titleIndex) { Bitmap icon = null; final ShortcutInfo info = new ShortcutInfo(); info.itemType = LauncherSettings.Favorites.ITEM_TYPE_SHORTCUT; // TODO: If there's an explicit component and we can't install that, delete it. info.title = c.getString(titleIndex); int iconType = c.getInt(iconTypeIndex); switch (iconType) { case LauncherSettings.Favorites.ICON_TYPE_RESOURCE: String packageName = c.getString(iconPackageIndex); String resourceName = c.getString(iconResourceIndex); PackageManager packageManager = context.getPackageManager(); info.customIcon = false; // the resource try { Resources resources = packageManager.getResourcesForApplication(packageName); if (resources != null) { final int id = resources.getIdentifier(resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } } catch (Exception e) { // drop this. we have other places to look for icons } // the db if (icon == null) { icon = getIconFromCursor(c, iconIndex, context); } // the fallback icon if (icon == null) { icon = getFallbackIcon(); info.usingFallbackIcon = true; } break; case LauncherSettings.Favorites.ICON_TYPE_BITMAP: icon = getIconFromCursor(c, iconIndex, context); if (icon == null) { icon = getFallbackIcon(); info.customIcon = false; info.usingFallbackIcon = true; } else { info.customIcon = true; } break; default: icon = getFallbackIcon(); info.usingFallbackIcon = true; info.customIcon = false; break; } info.setIcon(icon); return info; } Bitmap getIconFromCursor(Cursor c, int iconIndex, Context context) { @SuppressWarnings("all") // suppress dead code warning final boolean debug = false; if (debug) { Log.d(TAG, "getIconFromCursor app=" + c.getString(c.getColumnIndexOrThrow(LauncherSettings.Favorites.TITLE))); } byte[] data = c.getBlob(iconIndex); try { return Utilities.createIconBitmap( BitmapFactory.decodeByteArray(data, 0, data.length), context); } catch (Exception e) { return null; } } ShortcutInfo addShortcut(Context context, Intent data, long container, int screen, int cellX, int cellY, boolean notify) { final ShortcutInfo info = infoFromShortcutIntent(context, data, null); if (info == null) { return null; } addItemToDatabase(context, info, container, screen, cellX, cellY, notify); return info; } /** * Attempts to find an AppWidgetProviderInfo that matches the given component. */ AppWidgetProviderInfo findAppWidgetProviderInfoWithComponent(Context context, ComponentName component) { List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); for (AppWidgetProviderInfo info : widgets) { if (info.provider.equals(component)) { return info; } } return null; } /** * Returns a list of all the widgets that can handle configuration with a particular mimeType. */ List<WidgetMimeTypeHandlerData> resolveWidgetsForMimeType(Context context, String mimeType) { final PackageManager packageManager = context.getPackageManager(); final List<WidgetMimeTypeHandlerData> supportedConfigurationActivities = new ArrayList<WidgetMimeTypeHandlerData>(); final Intent supportsIntent = new Intent(InstallWidgetReceiver.ACTION_SUPPORTS_CLIPDATA_MIMETYPE); supportsIntent.setType(mimeType); // Create a set of widget configuration components that we can test against final List<AppWidgetProviderInfo> widgets = AppWidgetManager.getInstance(context).getInstalledProviders(); final HashMap<ComponentName, AppWidgetProviderInfo> configurationComponentToWidget = new HashMap<ComponentName, AppWidgetProviderInfo>(); for (AppWidgetProviderInfo info : widgets) { configurationComponentToWidget.put(info.configure, info); } // Run through each of the intents that can handle this type of clip data, and cross // reference them with the components that are actual configuration components final List<ResolveInfo> activities = packageManager.queryIntentActivities(supportsIntent, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo info : activities) { final ActivityInfo activityInfo = info.activityInfo; final ComponentName infoComponent = new ComponentName(activityInfo.packageName, activityInfo.name); if (configurationComponentToWidget.containsKey(infoComponent)) { supportedConfigurationActivities.add( new InstallWidgetReceiver.WidgetMimeTypeHandlerData(info, configurationComponentToWidget.get(infoComponent))); } } return supportedConfigurationActivities; } ShortcutInfo infoFromShortcutIntent(Context context, Intent data, Bitmap fallbackIcon) { Intent intent = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_INTENT); String name = data.getStringExtra(Intent.EXTRA_SHORTCUT_NAME); Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { // If the intent is null, we can't construct a valid ShortcutInfo, so we return null Log.e(TAG, "Can't construct ShorcutInfo with null intent"); return null; } Bitmap icon = null; boolean customIcon = false; ShortcutIconResource iconResource = null; if (bitmap != null && bitmap instanceof Bitmap) { icon = Utilities.createIconBitmap(new FastBitmapDrawable((Bitmap)bitmap), context); customIcon = true; } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra != null && extra instanceof ShortcutIconResource) { try { iconResource = (ShortcutIconResource) extra; final PackageManager packageManager = context.getPackageManager(); Resources resources = packageManager.getResourcesForApplication( iconResource.packageName); final int id = resources.getIdentifier(iconResource.resourceName, null, null); icon = Utilities.createIconBitmap( mIconCache.getFullResIcon(resources, id), context); } catch (Exception e) { Log.w(TAG, "Could not load shortcut icon: " + extra); } } } final ShortcutInfo info = new ShortcutInfo(); if (icon == null) { if (fallbackIcon != null) { icon = fallbackIcon; } else { icon = getFallbackIcon(); info.usingFallbackIcon = true; } } info.setIcon(icon); info.title = name; info.intent = intent; info.customIcon = customIcon; info.iconResource = iconResource; return info; } boolean queueIconToBeChecked(HashMap<Object, byte[]> cache, ShortcutInfo info, Cursor c, int iconIndex) { // If apps can't be on SD, don't even bother. if (!mAppsCanBeOnRemoveableStorage) { return false; } // If this icon doesn't have a custom icon, check to see // what's stored in the DB, and if it doesn't match what // we're going to show, store what we are going to show back // into the DB. We do this so when we're loading, if the // package manager can't find an icon (for example because // the app is on SD) then we can use that instead. if (!info.customIcon && !info.usingFallbackIcon) { cache.put(info, c.getBlob(iconIndex)); return true; } return false; } void updateSavedIcon(Context context, ShortcutInfo info, byte[] data) { boolean needSave = false; try { if (data != null) { Bitmap saved = BitmapFactory.decodeByteArray(data, 0, data.length); Bitmap loaded = info.getIcon(mIconCache); needSave = !saved.sameAs(loaded); } else { needSave = true; } } catch (Exception e) { needSave = true; } if (needSave) { Log.d(TAG, "going to save icon bitmap for info=" + info); // This is slower than is ideal, but this only happens once // or when the app is updated with a new icon. updateItemInDatabase(context, info); } } /** * Return an existing FolderInfo object if we have encountered this ID previously, * or make a new one. */ private static FolderInfo findOrMakeFolder(HashMap<Long, FolderInfo> folders, long id) { // See if a placeholder was created for us already FolderInfo folderInfo = folders.get(id); if (folderInfo == null) { // No placeholder -- create a new instance folderInfo = new FolderInfo(); folders.put(id, folderInfo); } return folderInfo; } public static final Comparator<ApplicationInfo> getAppNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { int result = collator.compare(a.title.toString(), b.title.toString()); if (result == 0) { result = a.componentName.compareTo(b.componentName); } return result; } }; } public static final Comparator<ApplicationInfo> APP_INSTALL_TIME_COMPARATOR = new Comparator<ApplicationInfo>() { public final int compare(ApplicationInfo a, ApplicationInfo b) { if (a.firstInstallTime < b.firstInstallTime) return 1; if (a.firstInstallTime > b.firstInstallTime) return -1; return 0; } }; public static final Comparator<AppWidgetProviderInfo> getWidgetNameComparator() { final Collator collator = Collator.getInstance(); return new Comparator<AppWidgetProviderInfo>() { public final int compare(AppWidgetProviderInfo a, AppWidgetProviderInfo b) { return collator.compare(a.label.toString(), b.label.toString()); } }; } static ComponentName getComponentNameFromResolveInfo(ResolveInfo info) { if (info.activityInfo != null) { return new ComponentName(info.activityInfo.packageName, info.activityInfo.name); } else { return new ComponentName(info.serviceInfo.packageName, info.serviceInfo.name); } } public static class ShortcutNameComparator implements Comparator<ResolveInfo> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, CharSequence> mLabelCache; ShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, CharSequence>(); mCollator = Collator.getInstance(); } ShortcutNameComparator(PackageManager pm, HashMap<Object, CharSequence> labelCache) { mPackageManager = pm; mLabelCache = labelCache; mCollator = Collator.getInstance(); } public final int compare(ResolveInfo a, ResolveInfo b) { CharSequence labelA, labelB; ComponentName keyA = LauncherModel.getComponentNameFromResolveInfo(a); ComponentName keyB = LauncherModel.getComponentNameFromResolveInfo(b); if (mLabelCache.containsKey(keyA)) { labelA = mLabelCache.get(keyA); } else { labelA = a.loadLabel(mPackageManager).toString(); mLabelCache.put(keyA, labelA); } if (mLabelCache.containsKey(keyB)) { labelB = mLabelCache.get(keyB); } else { labelB = b.loadLabel(mPackageManager).toString(); mLabelCache.put(keyB, labelB); } return mCollator.compare(labelA, labelB); } }; public static class WidgetAndShortcutNameComparator implements Comparator<Object> { private Collator mCollator; private PackageManager mPackageManager; private HashMap<Object, String> mLabelCache; WidgetAndShortcutNameComparator(PackageManager pm) { mPackageManager = pm; mLabelCache = new HashMap<Object, String>(); mCollator = Collator.getInstance(); } public final int compare(Object a, Object b) { String labelA, labelB; if (mLabelCache.containsKey(a)) { labelA = mLabelCache.get(a); } else { labelA = (a instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) a).label : ((ResolveInfo) a).loadLabel(mPackageManager).toString(); mLabelCache.put(a, labelA); } if (mLabelCache.containsKey(b)) { labelB = mLabelCache.get(b); } else { labelB = (b instanceof AppWidgetProviderInfo) ? ((AppWidgetProviderInfo) b).label : ((ResolveInfo) b).loadLabel(mPackageManager).toString(); mLabelCache.put(b, labelB); } return mCollator.compare(labelA, labelB); } }; public void dumpState() { Log.d(TAG, "mCallbacks=" + mCallbacks); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.data", mBgAllAppsList.data); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.added", mBgAllAppsList.added); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.removed", mBgAllAppsList.removed); ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList.modified", mBgAllAppsList.modified); if (mLoaderTask != null) { mLoaderTask.dumpState(); } else { Log.d(TAG, "mLoaderTask=null"); } } }
diff --git a/src/org/yaoha/OsmNode.java b/src/org/yaoha/OsmNode.java index 9601d3e..6a31af8 100644 --- a/src/org/yaoha/OsmNode.java +++ b/src/org/yaoha/OsmNode.java @@ -1,238 +1,238 @@ package org.yaoha; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.util.Log; public class OsmNode { public enum shopStatus {OPEN, CLOSED, UNSET, MAYBE}; private int ID; private int latitudeE6; private int longitudeE6; private Date lastUpdated; private HashMap<String, String> attributes; private HashMap<Integer, ArrayList<HourRange>> weekDayMap = new HashMap<Integer, ArrayList<HourRange>>(); private static HashMap<String, Integer> weekDayToInt = new HashMap<String, Integer>(); private static Pattern openingHoursPattern = Pattern.compile("[0-9]{1,2}:[0-9]{2}[-|+][0-9]{0,2}[:]{0,1}[0-9]{0,2}"); private int parseError; static { weekDayToInt.put("mo", Calendar.MONDAY); weekDayToInt.put("tu", Calendar.TUESDAY); weekDayToInt.put("we", Calendar.WEDNESDAY); weekDayToInt.put("th", Calendar.THURSDAY); weekDayToInt.put("do", Calendar.THURSDAY); weekDayToInt.put("fr", Calendar.FRIDAY); weekDayToInt.put("sa", Calendar.SATURDAY); weekDayToInt.put("su", Calendar.SUNDAY); } public OsmNode(String ID, String latitude, String longitude) { this.ID = Integer.parseInt(ID); this.latitudeE6 = new Double(Double.parseDouble(latitude)*1e6).intValue(); this.longitudeE6 = new Double(Double.parseDouble(longitude)*1e6).intValue(); this.attributes = new HashMap<String, String>(); } public OsmNode(int ID, int latitudeE6, int longitudeE6) { this.ID = ID; this.latitudeE6 = latitudeE6; this.longitudeE6 = longitudeE6; this.attributes = new HashMap<String, String>(); } public void putAttribute(String key, String value) { attributes.put(key, value); } public String getAttribute(String key) { return attributes.get(key); } public Set<String> getKeys() { return attributes.keySet(); } public int getID() { return ID; } public int getLatitudeE6() { return latitudeE6; } public int getLongitudeE6() { return longitudeE6; } public String getName() { return getAttribute("name"); } public void setName(String name) { putAttribute("name", name); } public String getAmenity() { return getAttribute("amenity"); } public void setAmenity(String amenity) { putAttribute("amenity", amenity); } public String getOpening_hours() { return getAttribute("opening_hours"); } public void setOpening_hours(String opening_hours) { putAttribute("opening_hours", opening_hours); } public Date getLastUpdated() { return lastUpdated; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated; } public void parseOpeningHours() throws java.text.ParseException { parseError = 0; String openingHoursString = this.getOpening_hours().toLowerCase(); if (openingHoursString.equals("24/7")) { ArrayList<HourRange> hours = new ArrayList<HourRange>(); HourRange hr = new HourRange(0, 0, 23, 59); hours.add(hr); weekDayMap.put(Calendar.MONDAY, hours); weekDayMap.put(Calendar.TUESDAY, hours); weekDayMap.put(Calendar.WEDNESDAY, hours); weekDayMap.put(Calendar.THURSDAY, hours); weekDayMap.put(Calendar.FRIDAY, hours); weekDayMap.put(Calendar.SATURDAY, hours); weekDayMap.put(Calendar.SUNDAY, hours); } else { String[] components = openingHoursString.split("[;][ ]{0,1}"); for (String part : components) { parseComponent(part); parseError += part.length(); } } } private void parseComponent(String part) throws java.text.ParseException { if (part.substring(0, 1).matches("[mtwfs]")) { parseWeekDayRange(part); } else if (part.substring(0, 1).matches("[0-9]")) { parseHourDayRange(part); } else { throw new java.text.ParseException("Part " + part + " not parsable: Doesn't start with a weekday nor with a time.", parseError); } } private void parseHourDayRange(String part) throws java.text.ParseException { ArrayList<HourRange> hours = parseHours(part); weekDayMap.put(Calendar.MONDAY, hours); weekDayMap.put(Calendar.TUESDAY, hours); weekDayMap.put(Calendar.WEDNESDAY, hours); weekDayMap.put(Calendar.THURSDAY, hours); weekDayMap.put(Calendar.FRIDAY, hours); weekDayMap.put(Calendar.SATURDAY, hours); weekDayMap.put(Calendar.SUNDAY, hours); } private void parseWeekDayRange(String part) throws java.text.ParseException { String[] weekDayComponents = part.split(" "); if (weekDayComponents.length != 2) { throw new java.text.ParseException("Week day range " + part + " not parsable: Should contain 2 parts divided by a space.", parseError); } ArrayList<Integer> weekDays = parseDays(weekDayComponents[0]); ArrayList<HourRange> hours = parseHours(weekDayComponents[1]); for (int i = 0; i < weekDays.size(); i++) { weekDayMap.put(weekDays.get(i), hours); } } private ArrayList<HourRange> parseHours(String rawHourRange) throws java.text.ParseException { ArrayList<HourRange> hours = new ArrayList<HourRange>(); String[] hourRanges = rawHourRange.split(","); for (String hourRange : hourRanges) { Matcher regularOpeningHoursMatcher = openingHoursPattern.matcher(hourRange); if (!regularOpeningHoursMatcher.matches()) throw new java.text.ParseException("Hour range " + hourRange + " not parsable: Doesn't match regular expression.", parseError); hours.add(new HourRange(hourRange)); } return hours; } private ArrayList<Integer> parseDays(String rawDayRange) throws java.text.ParseException { ArrayList<Integer> weekDays = new ArrayList<Integer>(); String[] commaSeparatedDays = rawDayRange.split(","); for (String commaDay : commaSeparatedDays) { if (commaDay.contains("-")) { String[] dashSeparatedDays = commaDay.split("-"); if (dashSeparatedDays.length != 2) throw new java.text.ParseException("Week day range " + commaDay + " not parsable: Should contain exactly two weekdays separated by a dash.", parseError); Integer firstIntWeekDay = weekDayToInt.get(dashSeparatedDays[0]); if (firstIntWeekDay == null) throw new java.text.ParseException("Week day " + dashSeparatedDays[0] + " not parsable: Doesn't exist.", parseError); Integer secondIntWeekDay = weekDayToInt.get(dashSeparatedDays[1]); if (secondIntWeekDay == null) throw new java.text.ParseException("Week day " + dashSeparatedDays[1] + " not parsable: Doesn't exist.", parseError); int i = firstIntWeekDay; while (i != secondIntWeekDay) { weekDays.add(i); i++; if (i>7) i=1; } weekDays.add(secondIntWeekDay); } else { Integer weekDay = weekDayToInt.get(commaDay); if (weekDay == null) throw new java.text.ParseException("Week day " + commaDay + " not parsable: Doesn't exist.", parseError); weekDays.add(weekDay); } } return weekDays; } public shopStatus isOpenNow() { // return values (for now): // 0 - closed // 1 - open // 2 - maybe (open end) // -1 not set if (weekDayMap == null) return shopStatus.UNSET; shopStatus result = shopStatus.CLOSED; Calendar now = Calendar.getInstance(); ArrayList<HourRange> today = weekDayMap.get(now.get(Calendar.DAY_OF_WEEK)); if (today == null) return shopStatus.CLOSED; for (int i = 0; i < today.size(); i++) { int nowHour = now.get(Calendar.HOUR_OF_DAY); int nowMinute = now.get(Calendar.MINUTE); HourRange curRange = today.get(i); - if (nowHour >= curRange.getStartingHour() && nowMinute >= curRange.getStartingMinute()) { - if (nowHour <= curRange.getEndingHour() && nowMinute <= curRange.getEndingMinute()) { + if (nowHour > curRange.getStartingHour() || (nowHour == curRange.getStartingHour() && nowMinute >= curRange.getStartingMinute())) { + if (nowHour < curRange.getEndingHour() || (nowHour == curRange.getEndingHour() && nowMinute <= curRange.getEndingMinute())) { result = shopStatus.OPEN; } else if (curRange.getEndingHour() == -1) { result = shopStatus.MAYBE; } } } return result; } }
true
true
public shopStatus isOpenNow() { // return values (for now): // 0 - closed // 1 - open // 2 - maybe (open end) // -1 not set if (weekDayMap == null) return shopStatus.UNSET; shopStatus result = shopStatus.CLOSED; Calendar now = Calendar.getInstance(); ArrayList<HourRange> today = weekDayMap.get(now.get(Calendar.DAY_OF_WEEK)); if (today == null) return shopStatus.CLOSED; for (int i = 0; i < today.size(); i++) { int nowHour = now.get(Calendar.HOUR_OF_DAY); int nowMinute = now.get(Calendar.MINUTE); HourRange curRange = today.get(i); if (nowHour >= curRange.getStartingHour() && nowMinute >= curRange.getStartingMinute()) { if (nowHour <= curRange.getEndingHour() && nowMinute <= curRange.getEndingMinute()) { result = shopStatus.OPEN; } else if (curRange.getEndingHour() == -1) { result = shopStatus.MAYBE; } } } return result; }
public shopStatus isOpenNow() { // return values (for now): // 0 - closed // 1 - open // 2 - maybe (open end) // -1 not set if (weekDayMap == null) return shopStatus.UNSET; shopStatus result = shopStatus.CLOSED; Calendar now = Calendar.getInstance(); ArrayList<HourRange> today = weekDayMap.get(now.get(Calendar.DAY_OF_WEEK)); if (today == null) return shopStatus.CLOSED; for (int i = 0; i < today.size(); i++) { int nowHour = now.get(Calendar.HOUR_OF_DAY); int nowMinute = now.get(Calendar.MINUTE); HourRange curRange = today.get(i); if (nowHour > curRange.getStartingHour() || (nowHour == curRange.getStartingHour() && nowMinute >= curRange.getStartingMinute())) { if (nowHour < curRange.getEndingHour() || (nowHour == curRange.getEndingHour() && nowMinute <= curRange.getEndingMinute())) { result = shopStatus.OPEN; } else if (curRange.getEndingHour() == -1) { result = shopStatus.MAYBE; } } } return result; }
diff --git a/target_explorer/plugins/org.eclipse.tcf.te.ui.views.workingsets/src/org/eclipse/tcf/te/ui/views/workingsets/WorkingSetsContentProvider.java b/target_explorer/plugins/org.eclipse.tcf.te.ui.views.workingsets/src/org/eclipse/tcf/te/ui/views/workingsets/WorkingSetsContentProvider.java index 39ba569eb..6158fb6fe 100644 --- a/target_explorer/plugins/org.eclipse.tcf.te.ui.views.workingsets/src/org/eclipse/tcf/te/ui/views/workingsets/WorkingSetsContentProvider.java +++ b/target_explorer/plugins/org.eclipse.tcf.te.ui.views.workingsets/src/org/eclipse/tcf/te/ui/views/workingsets/WorkingSetsContentProvider.java @@ -1,346 +1,346 @@ /******************************************************************************* * Copyright (c) 2011 Wind River Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the terms * of the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Wind River Systems - initial API and implementation *******************************************************************************/ package org.eclipse.tcf.te.ui.views.workingsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.tcf.te.runtime.events.EventManager; import org.eclipse.tcf.te.runtime.interfaces.workingsets.IWorkingSetElement; import org.eclipse.tcf.te.ui.views.events.ViewerContentChangeEvent; import org.eclipse.tcf.te.ui.views.interfaces.ICategory; import org.eclipse.tcf.te.ui.views.interfaces.IUIConstants; import org.eclipse.tcf.te.ui.views.interfaces.workingsets.IWorkingSetIDs; import org.eclipse.tcf.te.ui.views.internal.ViewRoot; import org.eclipse.tcf.te.ui.views.workingsets.activator.UIPlugin; import org.eclipse.tcf.te.ui.views.workingsets.nls.Messages; import org.eclipse.ui.ILocalWorkingSetManager; import org.eclipse.ui.IMemento; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.navigator.NavigatorContentService; import org.eclipse.ui.internal.navigator.NavigatorFilterService; import org.eclipse.ui.navigator.CommonNavigator; import org.eclipse.ui.navigator.CommonViewer; import org.eclipse.ui.navigator.ICommonContentExtensionSite; import org.eclipse.ui.navigator.ICommonContentProvider; import org.eclipse.ui.navigator.IExtensionStateModel; import org.eclipse.ui.navigator.INavigatorFilterService; /** * Provides children and parents for IWorkingSets. * <p> * Copied and adapted from <code>org.eclipse.ui.internal.navigator.workingsets.WorkingSetContentProvider</code>. */ @SuppressWarnings("restriction") public class WorkingSetsContentProvider implements ICommonContentProvider { /** * The extension id for the WorkingSet extension. */ public static final String EXTENSION_ID = "org.eclipse.tcf.te.ui.views.navigator.content.workingSets"; //$NON-NLS-1$ /** * A key used by the Extension State Model to keep track of whether top level Working Sets or * Elements should be shown in the viewer. */ public static final String SHOW_TOP_LEVEL_WORKING_SETS = EXTENSION_ID + ".showTopLevelWorkingSets"; //$NON-NLS-1$ /** * Working set filter extension id. */ private static final String WORKING_SET_FILTER_ID = "org.eclipse.tcf.te.ui.views.navigator.filters.workingSet"; //$NON-NLS-1$ /** * Child elements returned by this content provider in case there * are no children. */ private static final Object[] NO_CHILDREN = new Object[0]; // The common navigator working set content extension state model. private IExtensionStateModel extensionStateModel; // The parent viewer object private CommonViewer viewer; // The working set filter instance private WorkingSetFilter filter; /** * The root mode listener listens to property changes of the working set content * extension state model to update the viewer root mode if the user changes the * top level element type. */ private IPropertyChangeListener rootModeListener = new IPropertyChangeListener() { /* (non-Javadoc) * @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ @SuppressWarnings("synthetic-access") @Override public void propertyChange(PropertyChangeEvent event) { if (SHOW_TOP_LEVEL_WORKING_SETS.equals(event.getProperty())) { updateRootMode(true); } } }; /* (non-Javadoc) * @see org.eclipse.ui.navigator.ICommonContentProvider#init(org.eclipse.ui.navigator.ICommonContentExtensionSite) */ @Override public void init(ICommonContentExtensionSite config) { NavigatorContentService cs = (NavigatorContentService) config.getService(); if (!(cs.getViewer() instanceof CommonViewer)) return; viewer = (CommonViewer) cs.getViewer(); // Get the filter service to activate the working set viewer filter INavigatorFilterService filterService = cs.getFilterService(); // The working set filter should be among the visible filters ViewerFilter[] filters = filterService.getVisibleFilters(false); for (ViewerFilter candidate : filters) { if (candidate instanceof WorkingSetFilter) { filter = (WorkingSetFilter)candidate; } } if (filter != null && !filterService.isActive(WORKING_SET_FILTER_ID)) { if (filterService instanceof NavigatorFilterService) { NavigatorFilterService navFilterService = (NavigatorFilterService)filterService; navFilterService.addActiveFilterIds(new String[] { WORKING_SET_FILTER_ID }); navFilterService.updateViewer(); } } else if (filter == null) { IStatus status = new Status(IStatus.ERROR, UIPlugin.getUniqueIdentifier(), "Required filter " + WORKING_SET_FILTER_ID //$NON-NLS-1$ + " is not present. Working set support will not function correctly."); //$NON-NLS-1$ UIPlugin.getDefault().getLog().log(status); } extensionStateModel = config.getExtensionStateModel(); extensionStateModel.addPropertyChangeListener(rootModeListener); updateRootMode(false); } /* (non-Javadoc) * @see org.eclipse.ui.navigator.IMementoAware#restoreState(org.eclipse.ui.IMemento) */ @Override public void restoreState(IMemento memento) { // Determine the view local working set manager instance WorkingSetViewStateManager mng = (WorkingSetViewStateManager)Platform.getAdapterManager().getAdapter(viewer.getCommonNavigator(), WorkingSetViewStateManager.class); ILocalWorkingSetManager manager = mng != null ? mng.getLocalWorkingSetManager() : null; // Recreate the local automatic working sets if (manager != null) { // Create the "Others" working set if not restored from the memento IWorkingSet others = manager.getWorkingSet(Messages.ViewStateManager_others_name); if (others == null) { others = manager.createWorkingSet(Messages.ViewStateManager_others_name, new IAdaptable[0]); others.setId(IWorkingSetIDs.ID_WS_OTHERS); manager.addWorkingSet(others); } else { others.setId(IWorkingSetIDs.ID_WS_OTHERS); } } // Trigger an update of the "Others" working set ViewerContentChangeEvent event = new ViewerContentChangeEvent(viewer, ViewerContentChangeEvent.REFRESH); EventManager.getInstance().fireEvent(event); } /* (non-Javadoc) * @see org.eclipse.ui.navigator.IMementoAware#saveState(org.eclipse.ui.IMemento) */ @Override public void saveState(IMemento memento) { } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object) */ @Override public Object[] getChildren(Object parentElement) { if (parentElement instanceof IWorkingSet) { // Return the working set elements return getWorkingSetElements((IWorkingSet)parentElement); } else if (parentElement instanceof WorkingSetViewStateManager) { List<IWorkingSet> workingSets = ((WorkingSetViewStateManager)parentElement).getVisibleWorkingSets(); if (workingSets != null && !workingSets.isEmpty()) { return workingSets.toArray(); } } return NO_CHILDREN; } /* default */ IAdaptable[] getWorkingSetElements(IWorkingSet workingSet) { Assert.isNotNull(workingSet); List<IAdaptable> elements = new ArrayList<IAdaptable>(); for (IAdaptable candidate : workingSet.getElements()) { if (candidate instanceof WorkingSetElementHolder) { WorkingSetElementHolder holder = (WorkingSetElementHolder)candidate; IWorkingSetElement element = holder.getElement(); // If the element is null, try to look up the element through the content provider if (element == null) { List<Object> elementCandidates = new ArrayList<Object>(); ITreeContentProvider provider = (ITreeContentProvider)viewer.getContentProvider(); Object[] viewElements = provider.getElements(ViewRoot.getInstance()); for (Object viewElement : viewElements) { if (viewElement instanceof ICategory) { elementCandidates.addAll(Arrays.asList(provider.getChildren(viewElement))); } else { elementCandidates.add(viewElement); } } provider.dispose(); for (Object elementCandidate : elementCandidates) { if (elementCandidate instanceof IWorkingSetElement && ((IWorkingSetElement)elementCandidate).getElementId().equals(holder.getElementId())) { holder.setElement((IWorkingSetElement)elementCandidate); element = holder.getElement(); break; } } } if (element != null) elements.add(element); } else { elements.add(candidate); } } return elements.toArray(new IAdaptable[elements.size()]); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object) */ @Override public Object getParent(Object element) { - CommonNavigator navigator = viewer.getCommonNavigator(); + CommonNavigator navigator = viewer != null ? viewer.getCommonNavigator() : null; WorkingSetViewStateManager manager = navigator != null ? (WorkingSetViewStateManager)Platform.getAdapterManager().getAdapter(navigator, WorkingSetViewStateManager.class) : null; if (element instanceof IWorkingSet) { List<IWorkingSet> allWorkingSets = manager != null ? Arrays.asList(manager.getAllWorkingSets()) : new ArrayList<IWorkingSet>(); if (allWorkingSets.contains(element)) { return manager; } } else if (element instanceof WorkingSetElementHolder) { String wsName = ((WorkingSetElementHolder)element).getWorkingSetName(); if (wsName != null) { IWorkingSet ws = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(wsName); if (ws == null && manager != null) { ws = manager.getLocalWorkingSetManager().getWorkingSet(wsName); } return ws; } } else if (element instanceof IWorkingSetElement) { if (navigator != null) { if (navigator.getRootMode() == IUIConstants.MODE_WORKING_SETS) { IWorkingSet[] workingSets = PlatformUI.getWorkbench().getWorkingSetManager().getAllWorkingSets(); List<IWorkingSet> list = new ArrayList<IWorkingSet>(); list.addAll(Arrays.asList(workingSets)); ILocalWorkingSetManager wsManager = manager != null ? manager.getLocalWorkingSetManager() : null; workingSets = wsManager != null ? wsManager.getAllWorkingSets() : new IWorkingSet[0]; list.addAll(Arrays.asList(workingSets)); for (IWorkingSet workingSet : list) { IAdaptable[] wsElements = getWorkingSetElements(workingSet); for (IAdaptable wsElement : wsElements) { if (wsElement == element) return workingSet; } } } } } return null; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object) */ @Override public boolean hasChildren(Object element) { if (element instanceof IWorkingSet) { return ((IWorkingSet)element).getElements().length > 0; } return true; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITreeContentProvider#getElements(java.lang.Object) */ @Override public Object[] getElements(Object inputElement) { return getChildren(inputElement); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IContentProvider#dispose() */ @Override public void dispose() { if (extensionStateModel != null) extensionStateModel.removePropertyChangeListener(rootModeListener); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object) */ @Override public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } /** * Update the common navigator root mode. */ private void updateRootMode(boolean updateInput) { CommonNavigator navigator = viewer.getCommonNavigator(); if (navigator == null) return; Object newInput; boolean filterActive; if (extensionStateModel.getBooleanProperty(SHOW_TOP_LEVEL_WORKING_SETS)) { navigator.setRootMode(IUIConstants.MODE_WORKING_SETS); newInput = Platform.getAdapterManager().getAdapter(navigator, WorkingSetViewStateManager.class); filterActive = true; } else { navigator.setRootMode(IUIConstants.MODE_NORMAL); newInput = ViewRoot.getInstance(); filterActive = false; } if (updateInput && !newInput.equals(viewer.getInput())) { viewer.setInput(newInput); } setFilterActive(filterActive); } /** * Update the working set viewer filter active state. */ private void setFilterActive(boolean active) { if (filter != null) filter.setActive(active); } }
true
true
public Object getParent(Object element) { CommonNavigator navigator = viewer.getCommonNavigator(); WorkingSetViewStateManager manager = navigator != null ? (WorkingSetViewStateManager)Platform.getAdapterManager().getAdapter(navigator, WorkingSetViewStateManager.class) : null; if (element instanceof IWorkingSet) { List<IWorkingSet> allWorkingSets = manager != null ? Arrays.asList(manager.getAllWorkingSets()) : new ArrayList<IWorkingSet>(); if (allWorkingSets.contains(element)) { return manager; } } else if (element instanceof WorkingSetElementHolder) { String wsName = ((WorkingSetElementHolder)element).getWorkingSetName(); if (wsName != null) { IWorkingSet ws = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(wsName); if (ws == null && manager != null) { ws = manager.getLocalWorkingSetManager().getWorkingSet(wsName); } return ws; } } else if (element instanceof IWorkingSetElement) { if (navigator != null) { if (navigator.getRootMode() == IUIConstants.MODE_WORKING_SETS) { IWorkingSet[] workingSets = PlatformUI.getWorkbench().getWorkingSetManager().getAllWorkingSets(); List<IWorkingSet> list = new ArrayList<IWorkingSet>(); list.addAll(Arrays.asList(workingSets)); ILocalWorkingSetManager wsManager = manager != null ? manager.getLocalWorkingSetManager() : null; workingSets = wsManager != null ? wsManager.getAllWorkingSets() : new IWorkingSet[0]; list.addAll(Arrays.asList(workingSets)); for (IWorkingSet workingSet : list) { IAdaptable[] wsElements = getWorkingSetElements(workingSet); for (IAdaptable wsElement : wsElements) { if (wsElement == element) return workingSet; } } } } } return null; }
public Object getParent(Object element) { CommonNavigator navigator = viewer != null ? viewer.getCommonNavigator() : null; WorkingSetViewStateManager manager = navigator != null ? (WorkingSetViewStateManager)Platform.getAdapterManager().getAdapter(navigator, WorkingSetViewStateManager.class) : null; if (element instanceof IWorkingSet) { List<IWorkingSet> allWorkingSets = manager != null ? Arrays.asList(manager.getAllWorkingSets()) : new ArrayList<IWorkingSet>(); if (allWorkingSets.contains(element)) { return manager; } } else if (element instanceof WorkingSetElementHolder) { String wsName = ((WorkingSetElementHolder)element).getWorkingSetName(); if (wsName != null) { IWorkingSet ws = PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(wsName); if (ws == null && manager != null) { ws = manager.getLocalWorkingSetManager().getWorkingSet(wsName); } return ws; } } else if (element instanceof IWorkingSetElement) { if (navigator != null) { if (navigator.getRootMode() == IUIConstants.MODE_WORKING_SETS) { IWorkingSet[] workingSets = PlatformUI.getWorkbench().getWorkingSetManager().getAllWorkingSets(); List<IWorkingSet> list = new ArrayList<IWorkingSet>(); list.addAll(Arrays.asList(workingSets)); ILocalWorkingSetManager wsManager = manager != null ? manager.getLocalWorkingSetManager() : null; workingSets = wsManager != null ? wsManager.getAllWorkingSets() : new IWorkingSet[0]; list.addAll(Arrays.asList(workingSets)); for (IWorkingSet workingSet : list) { IAdaptable[] wsElements = getWorkingSetElements(workingSet); for (IAdaptable wsElement : wsElements) { if (wsElement == element) return workingSet; } } } } } return null; }
diff --git a/src/Afck.java b/src/Afck.java index 8410c2d..d7bdb15 100644 --- a/src/Afck.java +++ b/src/Afck.java @@ -1,276 +1,275 @@ /* (C) Copyright 2013 Stephen Chandler Paul ([email protected]) * * This program and accompanying materials are made available under the terms of * the GNU Lesser General Public License (LGPL) version 2.1 which accompanies * this distribution (LICENSE at the root of this project's directory), and is * also available at * http://www.gnu.org/licenses/gpl-3.0.html * * This program is distributed in the hopes that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ import java.util.*; import java.util.zip.*; import java.io.*; import javax.xml.parsers.*; import org.xml.sax.SAXException; import org.w3c.dom.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.StreamResult; public class Afck { public static final String VERSION = "0.0.0"; // Buffer size for extracting Alice worlds public static final int BUFFER_SIZE = 2048; /** * Recursively returns all the elementData files in the directory * {@link parent}. * * @param parent The directory to search * @return All the elementData files found */ public static List<File> getAllElementData(File parent) { List<File> filteredList = new ArrayList<File>(); for (File file : parent.listFiles()) { if (file.isDirectory()) filteredList.addAll(getAllElementData(file)); else if (file.getName().equals("elementData.xml")) filteredList.add(file); } return filteredList; } /** * Recursively look for an internal reference property for the index variable * in the elementData.xml file. * * @param rootElement The top element in the elementData.xml file * @return Whether or not the property was found */ public static boolean checkForIndexInternalReferenceMarker(Element rootElement) { NodeList elements = rootElement.getChildNodes(); int elementCount = elements.getLength(); for (int i = 0; i < elementCount; i++) { // Make sure the current item is actually an element if (elements.item(i).getNodeType() == Node.ELEMENT_NODE) { Element currentElement = (Element) elements.item(i); /* If the currentElement has children, check to see if we can find * the property node for the index variable in them */ if (currentElement.hasChildNodes()) if (checkForIndexInternalReferenceMarker(currentElement)) return true; /* If the current element has a criterionClass, check if it marks * index as an internal reference */ if (currentElement.hasAttribute("criterionClass")) { if (currentElement.getAttribute("criterionClass").equals( "edu.cmu.cs.stage3.alice.core.criterion.InternalReferenceKeyedCriterion") && currentElement.getFirstChild().getNodeValue().endsWith("index")) return true; } } } // No index marker was found return false; } public static boolean hasIndexVariable(Element rootElement) { NodeList childFiles = rootElement.getElementsByTagName("child"); int childFilesLength = childFiles.getLength(); for (int i = 0; i < childFilesLength; i++) { Element currentElement = ((Element) childFiles.item(i)); if (currentElement.getAttribute("filename").equals("index")) return true; } return false; } public static void main(String[] args) { // LGPL stuff System.out.print("afck Copyright (C) 2013 Chandler Paul\n" + "This program comes with ABSOLUTELY NO WARRANTY " + "and is distributed under the terms of the LGPL " + "license. For more information, please see the file " + "LICENSE at the root of the source code, or go to " + "http://www.gnu.org/licenses/lgpl.html\n"); // Don't bother with the GUI if a path is specified on the command line if (args.length > 0) { File brokenAliceWorld = new File(args[0]); File tmpDir; String worldName; Random generator = new Random(); /* Check to see if the main argument is a file name, otherwise * return an error */ if (!brokenAliceWorld.exists()) { System.err.printf("Path specified is not valid! Exiting...\n"); System.exit(-1); } // Determine the actual name of the project worldName = brokenAliceWorld.getPath(); // Create a temporary directory and extract the zip tmpDir = new File(System.getProperty("java.io.tmpdir") + "/afck-" + Integer.toString(Math.abs(generator.nextInt()))); tmpDir.mkdirs(); // Attempt to extract the alice world to the temporary directory try { ZipFile brokenAliceWorldZip = new ZipFile(brokenAliceWorld); Enumeration aliceZipEntries = brokenAliceWorldZip.entries(); System.out.print("Extracting world..."); // Extract each file in the Alice world while (aliceZipEntries.hasMoreElements()) { // Get the current zip entry ZipEntry entry = (ZipEntry) aliceZipEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(tmpDir, currentEntry); /* If the parent directory structure for the current entry needs * to be created, do so */ File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); // If the current entry is a file, begin writing it to the disk if (!entry.isDirectory()) { BufferedInputStream inputStream = new BufferedInputStream(brokenAliceWorldZip.getInputStream(entry)); int currentByte; byte data[] = new byte[BUFFER_SIZE]; // Buffer // Create output streams FileOutputStream outputStream = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(outputStream, BUFFER_SIZE); // Read/Write until EOF while ((currentByte = inputStream.read(data, 0, BUFFER_SIZE)) != -1) dest.write(data, 0, currentByte); // Flush the data dest.flush(); // Close the streams dest.close(); outputStream.close(); inputStream.close(); } } } catch (ZipException e) { System.err.printf("Fatal zip file exception! %s\n" + "Exiting...\n", e.getMessage()); // TODO: Clean up System.exit(-1); } catch (IOException e) { System.err.printf("Fatal I/O Exception: %s\n" + "Exiting...\n", e.getMessage()); System.exit(-1); } System.out.print(" done!\n"); - // TODO: Fix the alice file /* Look through all the element data in the alice world and find * improperly marked index variables * Note: At some point I might convert this to the SAX parser, but * right now I'm on a deadline to get this in by it's due date, so * for now we'll just stick with DOM */ try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); for (File file : getAllElementData(tmpDir)) { Document elementData = docBuilder.parse(file); Element rootElement = elementData.getDocumentElement(); /* Make sure the index variable is marked correctly, * otherwise fix it */ if (hasIndexVariable (rootElement) && !checkForIndexInternalReferenceMarker(rootElement)) { /* Find the original property element for index, and * remove it to make space for the new correctly marked * one */ System.out.println(file.getAbsolutePath()); NodeList propertyNodes = rootElement.getElementsByTagName("property"); int propertyCount = propertyNodes.getLength(); Node badNode = null; for (int i = 0; i < propertyCount; i++) { Node currentNode = propertyNodes.item(i); System.out.println(((Element) currentNode).getAttribute("name")); /* If we've found the bad node, store it in the * appropriate variable */ if (((Element) currentNode).getAttribute("name"). equals("index")) { badNode = currentNode; break; } } // Fix the bad node ((Element) badNode).setAttribute("criterionClass", "edu.cmu.cs.stage3.alice.core.criterion.InternalReferenceKeyedCriterion"); /* Determine the full class name of the index variable * and add it to the bad node */ ((Element) badNode).setTextContent(file.getAbsolutePath(). replaceFirst(tmpDir.getAbsolutePath() + "(/|\\\\)", ""). replaceFirst("elementData.xml", ""). replaceAll("(/|\\\\)", ".") + "index"); // Write to the elementData file try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(elementData); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (TransformerConfigurationException e) { System.exit(-1); } catch (TransformerException e) { System.exit(-1); } } } } catch (ParserConfigurationException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (SAXException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } // Clean up tmpDir.delete(); } } }
true
true
public static void main(String[] args) { // LGPL stuff System.out.print("afck Copyright (C) 2013 Chandler Paul\n" + "This program comes with ABSOLUTELY NO WARRANTY " + "and is distributed under the terms of the LGPL " + "license. For more information, please see the file " + "LICENSE at the root of the source code, or go to " + "http://www.gnu.org/licenses/lgpl.html\n"); // Don't bother with the GUI if a path is specified on the command line if (args.length > 0) { File brokenAliceWorld = new File(args[0]); File tmpDir; String worldName; Random generator = new Random(); /* Check to see if the main argument is a file name, otherwise * return an error */ if (!brokenAliceWorld.exists()) { System.err.printf("Path specified is not valid! Exiting...\n"); System.exit(-1); } // Determine the actual name of the project worldName = brokenAliceWorld.getPath(); // Create a temporary directory and extract the zip tmpDir = new File(System.getProperty("java.io.tmpdir") + "/afck-" + Integer.toString(Math.abs(generator.nextInt()))); tmpDir.mkdirs(); // Attempt to extract the alice world to the temporary directory try { ZipFile brokenAliceWorldZip = new ZipFile(brokenAliceWorld); Enumeration aliceZipEntries = brokenAliceWorldZip.entries(); System.out.print("Extracting world..."); // Extract each file in the Alice world while (aliceZipEntries.hasMoreElements()) { // Get the current zip entry ZipEntry entry = (ZipEntry) aliceZipEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(tmpDir, currentEntry); /* If the parent directory structure for the current entry needs * to be created, do so */ File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); // If the current entry is a file, begin writing it to the disk if (!entry.isDirectory()) { BufferedInputStream inputStream = new BufferedInputStream(brokenAliceWorldZip.getInputStream(entry)); int currentByte; byte data[] = new byte[BUFFER_SIZE]; // Buffer // Create output streams FileOutputStream outputStream = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(outputStream, BUFFER_SIZE); // Read/Write until EOF while ((currentByte = inputStream.read(data, 0, BUFFER_SIZE)) != -1) dest.write(data, 0, currentByte); // Flush the data dest.flush(); // Close the streams dest.close(); outputStream.close(); inputStream.close(); } } } catch (ZipException e) { System.err.printf("Fatal zip file exception! %s\n" + "Exiting...\n", e.getMessage()); // TODO: Clean up System.exit(-1); } catch (IOException e) { System.err.printf("Fatal I/O Exception: %s\n" + "Exiting...\n", e.getMessage()); System.exit(-1); } System.out.print(" done!\n"); // TODO: Fix the alice file /* Look through all the element data in the alice world and find * improperly marked index variables * Note: At some point I might convert this to the SAX parser, but * right now I'm on a deadline to get this in by it's due date, so * for now we'll just stick with DOM */ try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); for (File file : getAllElementData(tmpDir)) { Document elementData = docBuilder.parse(file); Element rootElement = elementData.getDocumentElement(); /* Make sure the index variable is marked correctly, * otherwise fix it */ if (hasIndexVariable (rootElement) && !checkForIndexInternalReferenceMarker(rootElement)) { /* Find the original property element for index, and * remove it to make space for the new correctly marked * one */ System.out.println(file.getAbsolutePath()); NodeList propertyNodes = rootElement.getElementsByTagName("property"); int propertyCount = propertyNodes.getLength(); Node badNode = null; for (int i = 0; i < propertyCount; i++) { Node currentNode = propertyNodes.item(i); System.out.println(((Element) currentNode).getAttribute("name")); /* If we've found the bad node, store it in the * appropriate variable */ if (((Element) currentNode).getAttribute("name"). equals("index")) { badNode = currentNode; break; } } // Fix the bad node ((Element) badNode).setAttribute("criterionClass", "edu.cmu.cs.stage3.alice.core.criterion.InternalReferenceKeyedCriterion"); /* Determine the full class name of the index variable * and add it to the bad node */ ((Element) badNode).setTextContent(file.getAbsolutePath(). replaceFirst(tmpDir.getAbsolutePath() + "(/|\\\\)", ""). replaceFirst("elementData.xml", ""). replaceAll("(/|\\\\)", ".") + "index"); // Write to the elementData file try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(elementData); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (TransformerConfigurationException e) { System.exit(-1); } catch (TransformerException e) { System.exit(-1); } } } } catch (ParserConfigurationException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (SAXException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } // Clean up tmpDir.delete(); } }
public static void main(String[] args) { // LGPL stuff System.out.print("afck Copyright (C) 2013 Chandler Paul\n" + "This program comes with ABSOLUTELY NO WARRANTY " + "and is distributed under the terms of the LGPL " + "license. For more information, please see the file " + "LICENSE at the root of the source code, or go to " + "http://www.gnu.org/licenses/lgpl.html\n"); // Don't bother with the GUI if a path is specified on the command line if (args.length > 0) { File brokenAliceWorld = new File(args[0]); File tmpDir; String worldName; Random generator = new Random(); /* Check to see if the main argument is a file name, otherwise * return an error */ if (!brokenAliceWorld.exists()) { System.err.printf("Path specified is not valid! Exiting...\n"); System.exit(-1); } // Determine the actual name of the project worldName = brokenAliceWorld.getPath(); // Create a temporary directory and extract the zip tmpDir = new File(System.getProperty("java.io.tmpdir") + "/afck-" + Integer.toString(Math.abs(generator.nextInt()))); tmpDir.mkdirs(); // Attempt to extract the alice world to the temporary directory try { ZipFile brokenAliceWorldZip = new ZipFile(brokenAliceWorld); Enumeration aliceZipEntries = brokenAliceWorldZip.entries(); System.out.print("Extracting world..."); // Extract each file in the Alice world while (aliceZipEntries.hasMoreElements()) { // Get the current zip entry ZipEntry entry = (ZipEntry) aliceZipEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(tmpDir, currentEntry); /* If the parent directory structure for the current entry needs * to be created, do so */ File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); // If the current entry is a file, begin writing it to the disk if (!entry.isDirectory()) { BufferedInputStream inputStream = new BufferedInputStream(brokenAliceWorldZip.getInputStream(entry)); int currentByte; byte data[] = new byte[BUFFER_SIZE]; // Buffer // Create output streams FileOutputStream outputStream = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(outputStream, BUFFER_SIZE); // Read/Write until EOF while ((currentByte = inputStream.read(data, 0, BUFFER_SIZE)) != -1) dest.write(data, 0, currentByte); // Flush the data dest.flush(); // Close the streams dest.close(); outputStream.close(); inputStream.close(); } } } catch (ZipException e) { System.err.printf("Fatal zip file exception! %s\n" + "Exiting...\n", e.getMessage()); // TODO: Clean up System.exit(-1); } catch (IOException e) { System.err.printf("Fatal I/O Exception: %s\n" + "Exiting...\n", e.getMessage()); System.exit(-1); } System.out.print(" done!\n"); /* Look through all the element data in the alice world and find * improperly marked index variables * Note: At some point I might convert this to the SAX parser, but * right now I'm on a deadline to get this in by it's due date, so * for now we'll just stick with DOM */ try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); for (File file : getAllElementData(tmpDir)) { Document elementData = docBuilder.parse(file); Element rootElement = elementData.getDocumentElement(); /* Make sure the index variable is marked correctly, * otherwise fix it */ if (hasIndexVariable (rootElement) && !checkForIndexInternalReferenceMarker(rootElement)) { /* Find the original property element for index, and * remove it to make space for the new correctly marked * one */ System.out.println(file.getAbsolutePath()); NodeList propertyNodes = rootElement.getElementsByTagName("property"); int propertyCount = propertyNodes.getLength(); Node badNode = null; for (int i = 0; i < propertyCount; i++) { Node currentNode = propertyNodes.item(i); System.out.println(((Element) currentNode).getAttribute("name")); /* If we've found the bad node, store it in the * appropriate variable */ if (((Element) currentNode).getAttribute("name"). equals("index")) { badNode = currentNode; break; } } // Fix the bad node ((Element) badNode).setAttribute("criterionClass", "edu.cmu.cs.stage3.alice.core.criterion.InternalReferenceKeyedCriterion"); /* Determine the full class name of the index variable * and add it to the bad node */ ((Element) badNode).setTextContent(file.getAbsolutePath(). replaceFirst(tmpDir.getAbsolutePath() + "(/|\\\\)", ""). replaceFirst("elementData.xml", ""). replaceAll("(/|\\\\)", ".") + "index"); // Write to the elementData file try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(elementData); StreamResult result = new StreamResult(file); transformer.transform(source, result); } catch (TransformerConfigurationException e) { System.exit(-1); } catch (TransformerException e) { System.exit(-1); } } } } catch (ParserConfigurationException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (SAXException e) { System.err.println(e.getMessage()); System.exit(-1); } catch (IOException e) { System.err.println(e.getMessage()); System.exit(-1); } // Clean up tmpDir.delete(); } }
diff --git a/src/com/android/exchange/adapter/CalendarSyncAdapter.java b/src/com/android/exchange/adapter/CalendarSyncAdapter.java index 1d1059f..b467eb7 100644 --- a/src/com/android/exchange/adapter/CalendarSyncAdapter.java +++ b/src/com/android/exchange/adapter/CalendarSyncAdapter.java @@ -1,2172 +1,2174 @@ /* * Copyright (C) 2008-2009 Marc Blank * Licensed to The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange.adapter; import android.content.ContentProviderClient; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Entity; import android.content.Entity.NamedContentValues; import android.content.EntityIterator; import android.content.OperationApplicationException; import android.database.Cursor; import android.database.DatabaseUtils; import android.net.Uri; import android.os.RemoteException; import android.provider.CalendarContract; import android.provider.CalendarContract.Attendees; import android.provider.CalendarContract.Calendars; import android.provider.CalendarContract.Events; import android.provider.CalendarContract.EventsEntity; import android.provider.CalendarContract.ExtendedProperties; import android.provider.CalendarContract.Reminders; import android.provider.CalendarContract.SyncState; import android.provider.ContactsContract.RawContacts; import android.provider.SyncStateContract; import android.text.TextUtils; import android.util.Log; import com.android.emailcommon.AccountManagerTypes; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.Message; import com.android.emailcommon.utility.Utility; import com.android.exchange.CommandStatusException; import com.android.exchange.Eas; import com.android.exchange.EasOutboxService; import com.android.exchange.EasSyncService; import com.android.exchange.ExchangeService; import com.android.exchange.utility.CalendarUtilities; import com.android.exchange.utility.Duration; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.TimeZone; import java.util.UUID; /** * Sync adapter class for EAS calendars * */ public class CalendarSyncAdapter extends AbstractSyncAdapter { private static final String TAG = "EasCalendarSyncAdapter"; private static final String EVENT_SAVED_TIMEZONE_COLUMN = Events.SYNC_DATA1; /** * Used to keep track of exception vs parent event dirtiness. */ private static final String EVENT_SYNC_MARK = Events.SYNC_DATA8; private static final String EVENT_SYNC_VERSION = Events.SYNC_DATA4; // Since exceptions will have the same _SYNC_ID as the original event we have to check that // there's no original event when finding an item by _SYNC_ID private static final String SERVER_ID_AND_CALENDAR_ID = Events._SYNC_ID + "=? AND " + Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?"; private static final String EVENT_ID_AND_CALENDAR_ID = Events._ID + "=? AND " + Events.ORIGINAL_SYNC_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?"; private static final String DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR = "(" + Events.DIRTY + "=1 OR " + EVENT_SYNC_MARK + "= 1) AND " + Events.ORIGINAL_ID + " ISNULL AND " + Events.CALENDAR_ID + "=?"; private static final String DIRTY_EXCEPTION_IN_CALENDAR = Events.DIRTY + "=1 AND " + Events.ORIGINAL_ID + " NOTNULL AND " + Events.CALENDAR_ID + "=?"; private static final String CLIENT_ID_SELECTION = Events.SYNC_DATA2 + "=?"; private static final String ORIGINAL_EVENT_AND_CALENDAR = Events.ORIGINAL_SYNC_ID + "=? AND " + Events.CALENDAR_ID + "=?"; private static final String ATTENDEES_EXCEPT_ORGANIZER = Attendees.EVENT_ID + "=? AND " + Attendees.ATTENDEE_RELATIONSHIP + "!=" + Attendees.RELATIONSHIP_ORGANIZER; private static final String[] ID_PROJECTION = new String[] {Events._ID}; private static final String[] ORIGINAL_EVENT_PROJECTION = new String[] {Events.ORIGINAL_ID, Events._ID}; private static final String EVENT_ID_AND_NAME = ExtendedProperties.EVENT_ID + "=? AND " + ExtendedProperties.NAME + "=?"; // Note that we use LIKE below for its case insensitivity private static final String EVENT_AND_EMAIL = Attendees.EVENT_ID + "=? AND "+ Attendees.ATTENDEE_EMAIL + " LIKE ?"; private static final int ATTENDEE_STATUS_COLUMN_STATUS = 0; private static final String[] ATTENDEE_STATUS_PROJECTION = new String[] {Attendees.ATTENDEE_STATUS}; public static final String CALENDAR_SELECTION = Calendars.ACCOUNT_NAME + "=? AND " + Calendars.ACCOUNT_TYPE + "=?"; private static final int CALENDAR_SELECTION_ID = 0; private static final String[] EXTENDED_PROPERTY_PROJECTION = new String[] {ExtendedProperties._ID}; private static final int EXTENDED_PROPERTY_ID = 0; private static final String CATEGORY_TOKENIZER_DELIMITER = "\\"; private static final String ATTENDEE_TOKENIZER_DELIMITER = CATEGORY_TOKENIZER_DELIMITER; private static final String EXTENDED_PROPERTY_USER_ATTENDEE_STATUS = "userAttendeeStatus"; private static final String EXTENDED_PROPERTY_ATTENDEES = "attendees"; private static final String EXTENDED_PROPERTY_DTSTAMP = "dtstamp"; private static final String EXTENDED_PROPERTY_MEETING_STATUS = "meeting_status"; private static final String EXTENDED_PROPERTY_CATEGORIES = "categories"; // Used to indicate that we removed the attendee list because it was too large private static final String EXTENDED_PROPERTY_ATTENDEES_REDACTED = "attendeesRedacted"; // Used to indicate that upsyncs aren't allowed (we catch this in sendLocalChanges) private static final String EXTENDED_PROPERTY_UPSYNC_PROHIBITED = "upsyncProhibited"; private static final ContentProviderOperation PLACEHOLDER_OPERATION = ContentProviderOperation.newInsert(Uri.EMPTY).build(); private static final Object sSyncKeyLock = new Object(); private static final TimeZone UTC_TIMEZONE = TimeZone.getTimeZone("UTC"); private final TimeZone mLocalTimeZone = TimeZone.getDefault(); // Maximum number of allowed attendees; above this number, we mark the Event with the // attendeesRedacted extended property and don't allow the event to be upsynced to the server private static final int MAX_SYNCED_ATTENDEES = 50; // We set the organizer to this when the user is the organizer and we've redacted the // attendee list. By making the meeting organizer OTHER than the user, we cause the UI to // prevent edits to this event (except local changes like reminder). private static final String BOGUS_ORGANIZER_EMAIL = "[email protected]"; // Maximum number of CPO's before we start redacting attendees in exceptions // The number 500 has been determined empirically; 1500 CPOs appears to be the limit before // binder failures occur, but we need room at any point for additional events/exceptions so // we set our limit at 1/3 of the apparent maximum for extra safety // TODO Find a better solution to this workaround private static final int MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION = 500; private long mCalendarId = -1; private String mCalendarIdString; private String[] mCalendarIdArgument; /*package*/ String mEmailAddress; private ArrayList<Long> mDeletedIdList = new ArrayList<Long>(); private ArrayList<Long> mUploadedIdList = new ArrayList<Long>(); private ArrayList<Long> mSendCancelIdList = new ArrayList<Long>(); private ArrayList<Message> mOutgoingMailList = new ArrayList<Message>(); public CalendarSyncAdapter(EasSyncService service) { super(service); mEmailAddress = mAccount.mEmailAddress; Cursor c = mService.mContentResolver.query(Calendars.CONTENT_URI, new String[] {Calendars._ID}, CALENDAR_SELECTION, new String[] {mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE}, null); if (c == null) return; try { if (c.moveToFirst()) { mCalendarId = c.getLong(CALENDAR_SELECTION_ID); } else { mCalendarId = CalendarUtilities.createCalendar(mService, mAccount, mMailbox); } mCalendarIdString = Long.toString(mCalendarId); mCalendarIdArgument = new String[] {mCalendarIdString}; } finally { c.close(); } } @Override public String getCollectionName() { return "Calendar"; } @Override public void cleanup() { } @Override public void wipe() { // Delete the calendar associated with this account // CalendarProvider2 does NOT handle selection arguments in deletions mContentResolver.delete( asSyncAdapter(Calendars.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), Calendars.ACCOUNT_NAME + "=" + DatabaseUtils.sqlEscapeString(mEmailAddress) + " AND " + Calendars.ACCOUNT_TYPE + "=" + DatabaseUtils.sqlEscapeString(AccountManagerTypes.TYPE_EXCHANGE), null); // Invalidate our calendar observers ExchangeService.unregisterCalendarObservers(); } @Override public void sendSyncOptions(Double protocolVersion, Serializer s) throws IOException { setPimSyncOptions(protocolVersion, Eas.FILTER_2_WEEKS, s); } @Override public boolean isSyncable() { return ContentResolver.getSyncAutomatically(mAccountManagerAccount, CalendarContract.AUTHORITY); } @Override public boolean parse(InputStream is) throws IOException, CommandStatusException { EasCalendarSyncParser p = new EasCalendarSyncParser(is, this); return p.parse(); } public static Uri asSyncAdapter(Uri uri, String account, String accountType) { return uri.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(Calendars.ACCOUNT_NAME, account) .appendQueryParameter(Calendars.ACCOUNT_TYPE, accountType).build(); } /** * Generate the uri for the data row associated with this NamedContentValues object * @param ncv the NamedContentValues object * @return a uri that can be used to refer to this row */ public Uri dataUriFromNamedContentValues(NamedContentValues ncv) { long id = ncv.values.getAsLong(RawContacts._ID); Uri dataUri = ContentUris.withAppendedId(ncv.uri, id); return dataUri; } /** * We get our SyncKey from CalendarProvider. If there's not one, we set it to "0" (the reset * state) and save that away. */ @Override public String getSyncKey() throws IOException { synchronized (sSyncKeyLock) { ContentProviderClient client = mService.mContentResolver .acquireContentProviderClient(CalendarContract.CONTENT_URI); try { byte[] data = SyncStateContract.Helpers.get( client, asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount); if (data == null || data.length == 0) { // Initialize the SyncKey setSyncKey("0", false); return "0"; } else { String syncKey = new String(data); userLog("SyncKey retrieved as ", syncKey, " from CalendarProvider"); return syncKey; } } catch (RemoteException e) { throw new IOException("Can't get SyncKey from CalendarProvider"); } } } /** * We only need to set this when we're forced to make the SyncKey "0" (a reset). In all other * cases, the SyncKey is set within Calendar */ @Override public void setSyncKey(String syncKey, boolean inCommands) throws IOException { synchronized (sSyncKeyLock) { if ("0".equals(syncKey) || !inCommands) { ContentProviderClient client = mService.mContentResolver .acquireContentProviderClient(CalendarContract.CONTENT_URI); try { SyncStateContract.Helpers.set( client, asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount, syncKey.getBytes()); userLog("SyncKey set to ", syncKey, " in CalendarProvider"); } catch (RemoteException e) { throw new IOException("Can't set SyncKey in CalendarProvider"); } } mMailbox.mSyncKey = syncKey; } } public class EasCalendarSyncParser extends AbstractSyncParser { String[] mBindArgument = new String[1]; Uri mAccountUri; CalendarOperations mOps = new CalendarOperations(); public EasCalendarSyncParser(InputStream in, CalendarSyncAdapter adapter) throws IOException { super(in, adapter); setLoggingTag("CalendarParser"); mAccountUri = Events.CONTENT_URI; } private void addOrganizerToAttendees(CalendarOperations ops, long eventId, String organizerName, String organizerEmail) { // Handle the organizer (who IS an attendee on device, but NOT in EAS) if (organizerName != null || organizerEmail != null) { ContentValues attendeeCv = new ContentValues(); if (organizerName != null) { attendeeCv.put(Attendees.ATTENDEE_NAME, organizerName); } if (organizerEmail != null) { attendeeCv.put(Attendees.ATTENDEE_EMAIL, organizerEmail); } attendeeCv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ORGANIZER); attendeeCv.put(Attendees.ATTENDEE_TYPE, Attendees.TYPE_REQUIRED); attendeeCv.put(Attendees.ATTENDEE_STATUS, Attendees.ATTENDEE_STATUS_ACCEPTED); if (eventId < 0) { ops.newAttendee(attendeeCv); } else { ops.updatedAttendee(attendeeCv, eventId); } } } /** * Set DTSTART, DTEND, DURATION and EVENT_TIMEZONE as appropriate for the given Event * The follow rules are enforced by CalendarProvider2: * Events that aren't exceptions MUST have either 1) a DTEND or 2) a DURATION * Recurring events (i.e. events with RRULE) must have a DURATION * All-day recurring events MUST have a DURATION that is in the form P<n>D * Other events MAY have a DURATION in any valid form (we use P<n>M) * All-day events MUST have hour, minute, and second = 0; in addition, they must have * the EVENT_TIMEZONE set to UTC * Also, exceptions to all-day events need to have an ORIGINAL_INSTANCE_TIME that has * hour, minute, and second = 0 and be set in UTC * @param cv the ContentValues for the Event * @param startTime the start time for the Event * @param endTime the end time for the Event * @param allDayEvent whether this is an all day event (1) or not (0) */ /*package*/ void setTimeRelatedValues(ContentValues cv, long startTime, long endTime, int allDayEvent) { // If there's no startTime, the event will be found to be invalid, so return if (startTime < 0) return; // EAS events can arrive without an end time, but CalendarProvider requires them // so we'll default to 30 minutes; this will be superceded if this is an all-day event if (endTime < 0) endTime = startTime + (30*MINUTES); // If this is an all-day event, set hour, minute, and second to zero, and use UTC if (allDayEvent != 0) { startTime = CalendarUtilities.getUtcAllDayCalendarTime(startTime, mLocalTimeZone); endTime = CalendarUtilities.getUtcAllDayCalendarTime(endTime, mLocalTimeZone); String originalTimeZone = cv.getAsString(Events.EVENT_TIMEZONE); cv.put(EVENT_SAVED_TIMEZONE_COLUMN, originalTimeZone); cv.put(Events.EVENT_TIMEZONE, UTC_TIMEZONE.getID()); } // If this is an exception, and the original was an all-day event, make sure the // original instance time has hour, minute, and second set to zero, and is in UTC if (cv.containsKey(Events.ORIGINAL_INSTANCE_TIME) && cv.containsKey(Events.ORIGINAL_ALL_DAY)) { Integer ade = cv.getAsInteger(Events.ORIGINAL_ALL_DAY); if (ade != null && ade != 0) { long exceptionTime = cv.getAsLong(Events.ORIGINAL_INSTANCE_TIME); GregorianCalendar cal = new GregorianCalendar(UTC_TIMEZONE); cal.setTimeInMillis(exceptionTime); cal.set(GregorianCalendar.HOUR_OF_DAY, 0); cal.set(GregorianCalendar.MINUTE, 0); cal.set(GregorianCalendar.SECOND, 0); cv.put(Events.ORIGINAL_INSTANCE_TIME, cal.getTimeInMillis()); } } // Always set DTSTART cv.put(Events.DTSTART, startTime); // For recurring events, set DURATION. Use P<n>D format for all day events if (cv.containsKey(Events.RRULE)) { if (allDayEvent != 0) { cv.put(Events.DURATION, "P" + ((endTime - startTime) / DAYS) + "D"); } else { cv.put(Events.DURATION, "P" + ((endTime - startTime) / MINUTES) + "M"); } // For other events, set DTEND and LAST_DATE } else { cv.put(Events.DTEND, endTime); cv.put(Events.LAST_DATE, endTime); } } public void addEvent(CalendarOperations ops, String serverId, boolean update) throws IOException { ContentValues cv = new ContentValues(); cv.put(Events.CALENDAR_ID, mCalendarId); cv.put(Events._SYNC_ID, serverId); cv.put(Events.HAS_ATTENDEE_DATA, 1); cv.put(Events.SYNC_DATA2, "0"); int allDayEvent = 0; String organizerName = null; String organizerEmail = null; int eventOffset = -1; int deleteOffset = -1; int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE; int responseType = CalendarUtilities.RESPONSE_TYPE_NONE; boolean firstTag = true; long eventId = -1; long startTime = -1; long endTime = -1; TimeZone timeZone = null; // Keep track of the attendees; exceptions will need them ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>(); int reminderMins = -1; String dtStamp = null; boolean organizerAdded = false; while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) { if (update && firstTag) { // Find the event that's being updated Cursor c = getServerIdCursor(serverId); long id = -1; try { if (c != null && c.moveToFirst()) { id = c.getLong(0); } } finally { if (c != null) c.close(); } if (id > 0) { // DTSTAMP can come first, and we simply need to track it if (tag == Tags.CALENDAR_DTSTAMP) { dtStamp = getValue(); continue; } else if (tag == Tags.CALENDAR_ATTENDEES) { // This is an attendees-only update; just // delete/re-add attendees mBindArgument[0] = Long.toString(id); ops.add(ContentProviderOperation .newDelete( asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withSelection(ATTENDEES_EXCEPT_ORGANIZER, mBindArgument) .build()); eventId = id; } else { // Otherwise, delete the original event and recreate it userLog("Changing (delete/add) event ", serverId); deleteOffset = ops.newDelete(id, serverId); // Add a placeholder event so that associated tables can reference // this as a back reference. We add the event at the end of the method eventOffset = ops.newEvent(PLACEHOLDER_OPERATION); } } else { // The changed item isn't found. We'll treat this as a new item eventOffset = ops.newEvent(PLACEHOLDER_OPERATION); userLog(TAG, "Changed item not found; treating as new."); } } else if (firstTag) { // Add a placeholder event so that associated tables can reference // this as a back reference. We add the event at the end of the method eventOffset = ops.newEvent(PLACEHOLDER_OPERATION); } firstTag = false; switch (tag) { case Tags.CALENDAR_ALL_DAY_EVENT: allDayEvent = getValueInt(); if (allDayEvent != 0 && timeZone != null) { // If the event doesn't start at midnight local time, we won't consider // this an all-day event in the local time zone (this is what OWA does) GregorianCalendar cal = new GregorianCalendar(mLocalTimeZone); cal.setTimeInMillis(startTime); userLog("All-day event arrived in: " + timeZone.getID()); if (cal.get(GregorianCalendar.HOUR_OF_DAY) != 0 || cal.get(GregorianCalendar.MINUTE) != 0) { allDayEvent = 0; userLog("Not an all-day event locally: " + mLocalTimeZone.getID()); } } cv.put(Events.ALL_DAY, allDayEvent); break; case Tags.CALENDAR_ATTACHMENTS: attachmentsParser(); break; case Tags.CALENDAR_ATTENDEES: // If eventId >= 0, this is an update; otherwise, a new Event attendeeValues = attendeesParser(ops, eventId); break; case Tags.BASE_BODY: cv.put(Events.DESCRIPTION, bodyParser()); break; case Tags.CALENDAR_BODY: cv.put(Events.DESCRIPTION, getValue()); break; case Tags.CALENDAR_TIME_ZONE: timeZone = CalendarUtilities.tziStringToTimeZone(getValue()); if (timeZone == null) { timeZone = mLocalTimeZone; } cv.put(Events.EVENT_TIMEZONE, timeZone.getID()); break; case Tags.CALENDAR_START_TIME: startTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_END_TIME: endTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_EXCEPTIONS: // For exceptions to show the organizer, the organizer must be added before // we call exceptionsParser addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail); organizerAdded = true; exceptionsParser(ops, cv, attendeeValues, reminderMins, busyStatus, startTime, endTime); break; case Tags.CALENDAR_LOCATION: cv.put(Events.EVENT_LOCATION, getValue()); break; case Tags.CALENDAR_RECURRENCE: String rrule = recurrenceParser(); if (rrule != null) { cv.put(Events.RRULE, rrule); } break; case Tags.CALENDAR_ORGANIZER_EMAIL: organizerEmail = getValue(); cv.put(Events.ORGANIZER, organizerEmail); break; case Tags.CALENDAR_SUBJECT: cv.put(Events.TITLE, getValue()); break; case Tags.CALENDAR_SENSITIVITY: cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt())); break; case Tags.CALENDAR_ORGANIZER_NAME: organizerName = getValue(); break; case Tags.CALENDAR_REMINDER_MINS_BEFORE: reminderMins = getValueInt(); ops.newReminder(reminderMins); cv.put(Events.HAS_ALARM, 1); break; // The following are fields we should save (for changes), though they don't // relate to data used by CalendarProvider at this point case Tags.CALENDAR_UID: cv.put(Events.SYNC_DATA2, getValue()); break; case Tags.CALENDAR_DTSTAMP: dtStamp = getValue(); break; case Tags.CALENDAR_MEETING_STATUS: ops.newExtendedProperty(EXTENDED_PROPERTY_MEETING_STATUS, getValue()); break; case Tags.CALENDAR_BUSY_STATUS: // We'll set the user's status in the Attendees table below // Don't set selfAttendeeStatus or CalendarProvider will create a duplicate // attendee! busyStatus = getValueInt(); break; case Tags.CALENDAR_RESPONSE_TYPE: // EAS 14+ uses this for the user's response status; we'll use this instead // of busy status, if it appears responseType = getValueInt(); break; case Tags.CALENDAR_CATEGORIES: String categories = categoriesParser(ops); if (categories.length() > 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_CATEGORIES, categories); } break; default: skipTag(); } } // Enforce CalendarProvider required properties setTimeRelatedValues(cv, startTime, endTime, allDayEvent); // If we haven't added the organizer to attendees, do it now if (!organizerAdded) { addOrganizerToAttendees(ops, eventId, organizerName, organizerEmail); } // Note that organizerEmail can be null with a DTSTAMP only change from the server boolean selfOrganizer = (mEmailAddress.equals(organizerEmail)); // Store email addresses of attendees (in a tokenizable string) in ExtendedProperties // If the user is an attendee, set the attendee status using busyStatus (note that the // busyStatus is inherited from the parent unless it's specified in the exception) // Add the insert/update operation for each attendee (based on whether it's add/change) int numAttendees = attendeeValues.size(); if (numAttendees > MAX_SYNCED_ATTENDEES) { // Indicate that we've redacted attendees. If we're the organizer, disable edit // by setting organizerEmail to a bogus value and by setting the upsync prohibited // extended properly. // Note that we don't set ANY attendees if we're in this branch; however, the // organizer has already been included above, and WILL show up (which is good) if (eventId < 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1"); if (selfOrganizer) { ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1"); } } else { ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "1", eventId); if (selfOrganizer) { ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "1", eventId); } } if (selfOrganizer) { organizerEmail = BOGUS_ORGANIZER_EMAIL; cv.put(Events.ORGANIZER, organizerEmail); } // Tell UI that we don't have any attendees cv.put(Events.HAS_ATTENDEE_DATA, "0"); mService.userLog("Maximum number of attendees exceeded; redacting"); } else if (numAttendees > 0) { StringBuilder sb = new StringBuilder(); for (ContentValues attendee: attendeeValues) { String attendeeEmail = attendee.getAsString(Attendees.ATTENDEE_EMAIL); sb.append(attendeeEmail); sb.append(ATTENDEE_TOKENIZER_DELIMITER); if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) { int attendeeStatus; // We'll use the response type (EAS 14), if we've got one; otherwise, we'll // try to infer it from busy status if (responseType != CalendarUtilities.RESPONSE_TYPE_NONE) { attendeeStatus = CalendarUtilities.attendeeStatusFromResponseType(responseType); } else if (!update) { // For new events in EAS < 14, we have no idea what the busy status // means, so we show "none", allowing the user to select an option. attendeeStatus = Attendees.ATTENDEE_STATUS_NONE; } else { // For updated events, we'll try to infer the attendee status from the // busy status attendeeStatus = CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus); } attendee.put(Attendees.ATTENDEE_STATUS, attendeeStatus); // If we're an attendee, save away our initial attendee status in the // event's ExtendedProperties (we look for differences between this and // the user's current attendee status to determine whether an email needs // to be sent to the organizer) // organizerEmail will be null in the case that this is an attendees-only // change from the server if (organizerEmail == null || !organizerEmail.equalsIgnoreCase(attendeeEmail)) { if (eventId < 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS, Integer.toString(attendeeStatus)); } else { ops.updatedExtendedProperty(EXTENDED_PROPERTY_USER_ATTENDEE_STATUS, Integer.toString(attendeeStatus), eventId); } } } if (eventId < 0) { ops.newAttendee(attendee); } else { ops.updatedAttendee(attendee, eventId); } } if (eventId < 0) { ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString()); ops.newExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0"); ops.newExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0"); } else { ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES, sb.toString(), eventId); ops.updatedExtendedProperty(EXTENDED_PROPERTY_ATTENDEES_REDACTED, "0", eventId); ops.updatedExtendedProperty(EXTENDED_PROPERTY_UPSYNC_PROHIBITED, "0", eventId); } } // Put the real event in the proper place in the ops ArrayList if (eventOffset >= 0) { // Store away the DTSTAMP here if (dtStamp != null) { ops.newExtendedProperty(EXTENDED_PROPERTY_DTSTAMP, dtStamp); } if (isValidEventValues(cv)) { ops.set(eventOffset, ContentProviderOperation .newInsert( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValues(cv).build()); } else { // If we can't add this event (it's invalid), remove all of the inserts // we've built for it int cnt = ops.mCount - eventOffset; userLog(TAG, "Removing " + cnt + " inserts from mOps"); for (int i = 0; i < cnt; i++) { ops.remove(eventOffset); } ops.mCount = eventOffset; // If this is a change, we need to also remove the deletion that comes // before the addition if (deleteOffset >= 0) { // Remove the deletion ops.remove(deleteOffset); // And the deletion of exceptions ops.remove(deleteOffset); userLog(TAG, "Removing deletion ops from mOps"); ops.mCount = deleteOffset; } } } } private void logEventColumns(ContentValues cv, String reason) { if (Eas.USER_LOG) { StringBuilder sb = new StringBuilder("Event invalid, " + reason + ", skipping: Columns = "); for (Entry<String, Object> entry: cv.valueSet()) { sb.append(entry.getKey()); sb.append('/'); } userLog(TAG, sb.toString()); } } /*package*/ boolean isValidEventValues(ContentValues cv) { boolean isException = cv.containsKey(Events.ORIGINAL_INSTANCE_TIME); // All events require DTSTART if (!cv.containsKey(Events.DTSTART)) { logEventColumns(cv, "DTSTART missing"); return false; // If we're a top-level event, we must have _SYNC_DATA (uid) } else if (!isException && !cv.containsKey(Events.SYNC_DATA2)) { logEventColumns(cv, "_SYNC_DATA missing"); return false; // We must also have DTEND or DURATION if we're not an exception } else if (!isException && !cv.containsKey(Events.DTEND) && !cv.containsKey(Events.DURATION)) { logEventColumns(cv, "DTEND/DURATION missing"); return false; // Exceptions require DTEND } else if (isException && !cv.containsKey(Events.DTEND)) { logEventColumns(cv, "Exception missing DTEND"); return false; // If this is a recurrence, we need a DURATION (in days if an all-day event) } else if (cv.containsKey(Events.RRULE)) { String duration = cv.getAsString(Events.DURATION); if (duration == null) return false; if (cv.containsKey(Events.ALL_DAY)) { Integer ade = cv.getAsInteger(Events.ALL_DAY); if (ade != null && ade != 0 && !duration.endsWith("D")) { return false; } } } return true; } public String recurrenceParser() throws IOException { // Turn this information into an RRULE int type = -1; int occurrences = -1; int interval = -1; int dow = -1; int dom = -1; int wom = -1; int moy = -1; String until = null; while (nextTag(Tags.CALENDAR_RECURRENCE) != END) { switch (tag) { case Tags.CALENDAR_RECURRENCE_TYPE: type = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_INTERVAL: interval = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_OCCURRENCES: occurrences = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_DAYOFWEEK: dow = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_DAYOFMONTH: dom = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_WEEKOFMONTH: wom = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_MONTHOFYEAR: moy = getValueInt(); break; case Tags.CALENDAR_RECURRENCE_UNTIL: until = getValue(); break; default: skipTag(); } } return CalendarUtilities.rruleFromRecurrence(type, occurrences, interval, dow, dom, wom, moy, until); } private void exceptionParser(CalendarOperations ops, ContentValues parentCv, ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus, long startTime, long endTime) throws IOException { ContentValues cv = new ContentValues(); cv.put(Events.CALENDAR_ID, mCalendarId); // It appears that these values have to be copied from the parent if they are to appear // Note that they can be overridden below cv.put(Events.ORGANIZER, parentCv.getAsString(Events.ORGANIZER)); cv.put(Events.TITLE, parentCv.getAsString(Events.TITLE)); cv.put(Events.DESCRIPTION, parentCv.getAsString(Events.DESCRIPTION)); cv.put(Events.ORIGINAL_ALL_DAY, parentCv.getAsInteger(Events.ALL_DAY)); cv.put(Events.EVENT_LOCATION, parentCv.getAsString(Events.EVENT_LOCATION)); cv.put(Events.ACCESS_LEVEL, parentCv.getAsString(Events.ACCESS_LEVEL)); cv.put(Events.EVENT_TIMEZONE, parentCv.getAsString(Events.EVENT_TIMEZONE)); // Exceptions should always have this set to zero, since EAS has no concept of // separate attendee lists for exceptions; if we fail to do this, then the UI will // allow the user to change attendee data, and this change would never get reflected // on the server. cv.put(Events.HAS_ATTENDEE_DATA, 0); int allDayEvent = 0; // This column is the key that links the exception to the serverId cv.put(Events.ORIGINAL_SYNC_ID, parentCv.getAsString(Events._SYNC_ID)); String exceptionStartTime = "_noStartTime"; while (nextTag(Tags.SYNC_APPLICATION_DATA) != END) { switch (tag) { case Tags.CALENDAR_ATTACHMENTS: attachmentsParser(); break; case Tags.CALENDAR_EXCEPTION_START_TIME: exceptionStartTime = getValue(); cv.put(Events.ORIGINAL_INSTANCE_TIME, Utility.parseDateTimeToMillis(exceptionStartTime)); break; case Tags.CALENDAR_EXCEPTION_IS_DELETED: if (getValueInt() == 1) { cv.put(Events.STATUS, Events.STATUS_CANCELED); } break; case Tags.CALENDAR_ALL_DAY_EVENT: allDayEvent = getValueInt(); cv.put(Events.ALL_DAY, allDayEvent); break; case Tags.BASE_BODY: cv.put(Events.DESCRIPTION, bodyParser()); break; case Tags.CALENDAR_BODY: cv.put(Events.DESCRIPTION, getValue()); break; case Tags.CALENDAR_START_TIME: startTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_END_TIME: endTime = Utility.parseDateTimeToMillis(getValue()); break; case Tags.CALENDAR_LOCATION: cv.put(Events.EVENT_LOCATION, getValue()); break; case Tags.CALENDAR_RECURRENCE: String rrule = recurrenceParser(); if (rrule != null) { cv.put(Events.RRULE, rrule); } break; case Tags.CALENDAR_SUBJECT: cv.put(Events.TITLE, getValue()); break; case Tags.CALENDAR_SENSITIVITY: cv.put(Events.ACCESS_LEVEL, encodeVisibility(getValueInt())); break; case Tags.CALENDAR_BUSY_STATUS: busyStatus = getValueInt(); // Don't set selfAttendeeStatus or CalendarProvider will create a duplicate // attendee! break; // TODO How to handle these items that are linked to event id! // case Tags.CALENDAR_DTSTAMP: // ops.newExtendedProperty("dtstamp", getValue()); // break; // case Tags.CALENDAR_REMINDER_MINS_BEFORE: // ops.newReminder(getValueInt()); // break; default: skipTag(); } } // We need a _sync_id, but it can't be the parent's id, so we generate one cv.put(Events._SYNC_ID, parentCv.getAsString(Events._SYNC_ID) + '_' + exceptionStartTime); // Enforce CalendarProvider required properties setTimeRelatedValues(cv, startTime, endTime, allDayEvent); // Don't insert an invalid exception event if (!isValidEventValues(cv)) return; // Add the exception insert int exceptionStart = ops.mCount; ops.newException(cv); // Also add the attendees, because they need to be copied over from the parent event boolean attendeesRedacted = false; if (attendeeValues != null) { for (ContentValues attValues: attendeeValues) { // If this is the user, use his busy status for attendee status String attendeeEmail = attValues.getAsString(Attendees.ATTENDEE_EMAIL); // Note that the exception at which we surpass the redaction limit might have // any number of attendees shown; since this is an edge case and a workaround, // it seems to be an acceptable implementation if (mEmailAddress.equalsIgnoreCase(attendeeEmail)) { attValues.put(Attendees.ATTENDEE_STATUS, CalendarUtilities.attendeeStatusFromBusyStatus(busyStatus)); ops.newAttendee(attValues, exceptionStart); } else if (ops.size() < MAX_OPS_BEFORE_EXCEPTION_ATTENDEE_REDACTION) { ops.newAttendee(attValues, exceptionStart); } else { attendeesRedacted = true; } } } // And add the parent's reminder value if (reminderMins > 0) { ops.newReminder(reminderMins, exceptionStart); } if (attendeesRedacted) { mService.userLog("Attendees redacted in this exception"); } } private int encodeVisibility(int easVisibility) { int visibility = 0; switch(easVisibility) { case 0: visibility = Events.ACCESS_DEFAULT; break; case 1: visibility = Events.ACCESS_PUBLIC; break; case 2: visibility = Events.ACCESS_PRIVATE; break; case 3: visibility = Events.ACCESS_CONFIDENTIAL; break; } return visibility; } private void exceptionsParser(CalendarOperations ops, ContentValues cv, ArrayList<ContentValues> attendeeValues, int reminderMins, int busyStatus, long startTime, long endTime) throws IOException { while (nextTag(Tags.CALENDAR_EXCEPTIONS) != END) { switch (tag) { case Tags.CALENDAR_EXCEPTION: exceptionParser(ops, cv, attendeeValues, reminderMins, busyStatus, startTime, endTime); break; default: skipTag(); } } } private String categoriesParser(CalendarOperations ops) throws IOException { StringBuilder categories = new StringBuilder(); while (nextTag(Tags.CALENDAR_CATEGORIES) != END) { switch (tag) { case Tags.CALENDAR_CATEGORY: // TODO Handle categories (there's no similar concept for gdata AFAIK) // We need to save them and spit them back when we update the event categories.append(getValue()); categories.append(CATEGORY_TOKENIZER_DELIMITER); break; default: skipTag(); } } return categories.toString(); } /** * For now, we ignore (but still have to parse) event attachments; these are new in EAS 14 */ private void attachmentsParser() throws IOException { while (nextTag(Tags.CALENDAR_ATTACHMENTS) != END) { switch (tag) { case Tags.CALENDAR_ATTACHMENT: skipParser(Tags.CALENDAR_ATTACHMENT); break; default: skipTag(); } } } private ArrayList<ContentValues> attendeesParser(CalendarOperations ops, long eventId) throws IOException { int attendeeCount = 0; ArrayList<ContentValues> attendeeValues = new ArrayList<ContentValues>(); while (nextTag(Tags.CALENDAR_ATTENDEES) != END) { switch (tag) { case Tags.CALENDAR_ATTENDEE: ContentValues cv = attendeeParser(ops, eventId); // If we're going to redact these attendees anyway, let's avoid unnecessary // memory pressure, and not keep them around // We still need to parse them all, however attendeeCount++; // Allow one more than MAX_ATTENDEES, so that the check for "too many" will // succeed in addEvent if (attendeeCount <= (MAX_SYNCED_ATTENDEES+1)) { attendeeValues.add(cv); } break; default: skipTag(); } } return attendeeValues; } private ContentValues attendeeParser(CalendarOperations ops, long eventId) throws IOException { ContentValues cv = new ContentValues(); while (nextTag(Tags.CALENDAR_ATTENDEE) != END) { switch (tag) { case Tags.CALENDAR_ATTENDEE_EMAIL: cv.put(Attendees.ATTENDEE_EMAIL, getValue()); break; case Tags.CALENDAR_ATTENDEE_NAME: cv.put(Attendees.ATTENDEE_NAME, getValue()); break; case Tags.CALENDAR_ATTENDEE_STATUS: int status = getValueInt(); cv.put(Attendees.ATTENDEE_STATUS, (status == 2) ? Attendees.ATTENDEE_STATUS_TENTATIVE : (status == 3) ? Attendees.ATTENDEE_STATUS_ACCEPTED : (status == 4) ? Attendees.ATTENDEE_STATUS_DECLINED : (status == 5) ? Attendees.ATTENDEE_STATUS_INVITED : Attendees.ATTENDEE_STATUS_NONE); break; case Tags.CALENDAR_ATTENDEE_TYPE: int type = Attendees.TYPE_NONE; // EAS types: 1 = req'd, 2 = opt, 3 = resource switch (getValueInt()) { case 1: type = Attendees.TYPE_REQUIRED; break; case 2: type = Attendees.TYPE_OPTIONAL; break; } cv.put(Attendees.ATTENDEE_TYPE, type); break; default: skipTag(); } } cv.put(Attendees.ATTENDEE_RELATIONSHIP, Attendees.RELATIONSHIP_ATTENDEE); return cv; } private String bodyParser() throws IOException { String body = null; while (nextTag(Tags.BASE_BODY) != END) { switch (tag) { case Tags.BASE_DATA: body = getValue(); break; default: skipTag(); } } // Handle null data without error if (body == null) return ""; // Remove \r's from any body text return body.replace("\r\n", "\n"); } public void addParser(CalendarOperations ops) throws IOException { String serverId = null; while (nextTag(Tags.SYNC_ADD) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: // same as serverId = getValue(); break; case Tags.SYNC_APPLICATION_DATA: addEvent(ops, serverId, false); break; default: skipTag(); } } } private Cursor getServerIdCursor(String serverId) { return mContentResolver.query(mAccountUri, ID_PROJECTION, SERVER_ID_AND_CALENDAR_ID, new String[] {serverId, mCalendarIdString}, null); } private Cursor getClientIdCursor(String clientId) { mBindArgument[0] = clientId; return mContentResolver.query(mAccountUri, ID_PROJECTION, CLIENT_ID_SELECTION, mBindArgument, null); } public void deleteParser(CalendarOperations ops) throws IOException { while (nextTag(Tags.SYNC_DELETE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: String serverId = getValue(); // Find the event with the given serverId Cursor c = getServerIdCursor(serverId); try { if (c.moveToFirst()) { userLog("Deleting ", serverId); ops.delete(c.getLong(0), serverId); } } finally { c.close(); } break; default: skipTag(); } } } /** * A change is handled as a delete (including all exceptions) and an add * This isn't as efficient as attempting to traverse the original and all of its exceptions, * but changes happen infrequently and this code is both simpler and easier to maintain * @param ops the array of pending ContactProviderOperations. * @throws IOException */ public void changeParser(CalendarOperations ops) throws IOException { String serverId = null; while (nextTag(Tags.SYNC_CHANGE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: serverId = getValue(); break; case Tags.SYNC_APPLICATION_DATA: userLog("Changing " + serverId); addEvent(ops, serverId, true); break; default: skipTag(); } } } @Override public void commandsParser() throws IOException { while (nextTag(Tags.SYNC_COMMANDS) != END) { if (tag == Tags.SYNC_ADD) { addParser(mOps); incrementChangeCount(); } else if (tag == Tags.SYNC_DELETE) { deleteParser(mOps); incrementChangeCount(); } else if (tag == Tags.SYNC_CHANGE) { changeParser(mOps); incrementChangeCount(); } else skipTag(); } } @Override public void commit() throws IOException { userLog("Calendar SyncKey saved as: ", mMailbox.mSyncKey); // Save the syncKey here, using the Helper provider by Calendar provider mOps.add(SyncStateContract.Helpers.newSetOperation( asSyncAdapter(SyncState.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), mAccountManagerAccount, mMailbox.mSyncKey.getBytes())); // We need to send cancellations now, because the Event won't exist after the commit for (long eventId: mSendCancelIdList) { EmailContent.Message msg; try { msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_CANCEL, null, mAccount); } catch (RemoteException e) { // Nothing to do here; the Event may no longer exist continue; } if (msg != null) { EasOutboxService.sendMessage(mContext, mAccount.mId, msg); } } // Execute these all at once... mOps.execute(); if (mOps.mResults != null) { // Clear dirty and mark flags for updates sent to server if (!mUploadedIdList.isEmpty()) { ContentValues cv = new ContentValues(); cv.put(Events.DIRTY, 0); cv.put(EVENT_SYNC_MARK, "0"); for (long eventId : mUploadedIdList) { mContentResolver.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } } // Delete events marked for deletion if (!mDeletedIdList.isEmpty()) { for (long eventId : mDeletedIdList) { mContentResolver.delete( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } } // Send any queued up email (invitations replies, etc.) for (Message msg: mOutgoingMailList) { EasOutboxService.sendMessage(mContext, mAccount.mId, msg); } } } public void addResponsesParser() throws IOException { String serverId = null; String clientId = null; int status = -1; ContentValues cv = new ContentValues(); while (nextTag(Tags.SYNC_ADD) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: serverId = getValue(); break; case Tags.SYNC_CLIENT_ID: clientId = getValue(); break; case Tags.SYNC_STATUS: status = getValueInt(); if (status != 1) { userLog("Attempt to add event failed with status: " + status); } break; default: skipTag(); } } if (clientId == null) return; if (serverId == null) { // TODO Reconsider how to handle this serverId = "FAIL:" + status; } Cursor c = getClientIdCursor(clientId); try { if (c.moveToFirst()) { cv.put(Events._SYNC_ID, serverId); cv.put(Events.SYNC_DATA2, clientId); long id = c.getLong(0); // Write the serverId into the Event mOps.add(ContentProviderOperation .newUpdate( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, id), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValues(cv).build()); userLog("New event " + clientId + " was given serverId: " + serverId); } } finally { c.close(); } } public void changeResponsesParser() throws IOException { String serverId = null; String status = null; while (nextTag(Tags.SYNC_CHANGE) != END) { switch (tag) { case Tags.SYNC_SERVER_ID: serverId = getValue(); break; case Tags.SYNC_STATUS: status = getValue(); break; default: skipTag(); } } if (serverId != null && status != null) { userLog("Changed event " + serverId + " failed with status: " + status); } } @Override public void responsesParser() throws IOException { // Handle server responses here (for Add and Change) while (nextTag(Tags.SYNC_RESPONSES) != END) { if (tag == Tags.SYNC_ADD) { addResponsesParser(); } else if (tag == Tags.SYNC_CHANGE) { changeResponsesParser(); } else skipTag(); } } } protected class CalendarOperations extends ArrayList<ContentProviderOperation> { private static final long serialVersionUID = 1L; public int mCount = 0; private ContentProviderResult[] mResults = null; private int mEventStart = 0; @Override public boolean add(ContentProviderOperation op) { super.add(op); mCount++; return true; } public int newEvent(ContentProviderOperation op) { mEventStart = mCount; add(op); return mEventStart; } public int newDelete(long id, String serverId) { int offset = mCount; delete(id, serverId); return offset; } public void newAttendee(ContentValues cv) { newAttendee(cv, mEventStart); } public void newAttendee(ContentValues cv, int eventStart) { add(ContentProviderOperation .newInsert(asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv) .withValueBackReference(Attendees.EVENT_ID, eventStart).build()); } public void updatedAttendee(ContentValues cv, long id) { cv.put(Attendees.EVENT_ID, id); add(ContentProviderOperation.newInsert(asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build()); } public void newException(ContentValues cv) { add(ContentProviderOperation.newInsert( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).withValues(cv).build()); } public void newExtendedProperty(String name, String value) { add(ContentProviderOperation .newInsert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValue(ExtendedProperties.NAME, name) .withValue(ExtendedProperties.VALUE, value) .withValueBackReference(ExtendedProperties.EVENT_ID, mEventStart).build()); } public void updatedExtendedProperty(String name, String value, long id) { // Find an existing ExtendedProperties row for this event and property name Cursor c = mService.mContentResolver.query(ExtendedProperties.CONTENT_URI, EXTENDED_PROPERTY_PROJECTION, EVENT_ID_AND_NAME, new String[] {Long.toString(id), name}, null); long extendedPropertyId = -1; // If there is one, capture its _id if (c != null) { try { if (c.moveToFirst()) { extendedPropertyId = c.getLong(EXTENDED_PROPERTY_ID); } } finally { c.close(); } } // Either do an update or an insert, depending on whether one // already exists if (extendedPropertyId >= 0) { add(ContentProviderOperation .newUpdate( ContentUris.withAppendedId( asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), extendedPropertyId)) .withValue(ExtendedProperties.VALUE, value).build()); } else { newExtendedProperty(name, value); } } public void newReminder(int mins, int eventStart) { add(ContentProviderOperation .newInsert(asSyncAdapter(Reminders.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withValue(Reminders.MINUTES, mins) .withValue(Reminders.METHOD, Reminders.METHOD_ALERT) .withValueBackReference(ExtendedProperties.EVENT_ID, eventStart).build()); } public void newReminder(int mins) { newReminder(mins, mEventStart); } public void delete(long id, String syncId) { add(ContentProviderOperation.newDelete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, id), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)).build()); // Delete the exceptions for this Event (CalendarProvider doesn't do // this) add(ContentProviderOperation .newDelete(asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE)) .withSelection(Events.ORIGINAL_SYNC_ID + "=?", new String[] {syncId}).build()); } public void execute() { synchronized (mService.getSynchronizer()) { if (!mService.isStopped()) { try { if (!isEmpty()) { mService.userLog("Executing ", size(), " CPO's"); mResults = mContext.getContentResolver().applyBatch( CalendarContract.AUTHORITY, this); } } catch (RemoteException e) { // There is nothing sensible to be done here Log.e(TAG, "problem inserting event during server update", e); } catch (OperationApplicationException e) { // There is nothing sensible to be done here Log.e(TAG, "problem inserting event during server update", e); } } } } } private String decodeVisibility(int visibility) { int easVisibility = 0; switch(visibility) { case Events.ACCESS_DEFAULT: easVisibility = 0; break; case Events.ACCESS_PUBLIC: easVisibility = 1; break; case Events.ACCESS_PRIVATE: easVisibility = 2; break; case Events.ACCESS_CONFIDENTIAL: easVisibility = 3; break; } return Integer.toString(easVisibility); } private int getInt(ContentValues cv, String column) { Integer i = cv.getAsInteger(column); if (i == null) return 0; return i; } private void sendEvent(Entity entity, String clientId, Serializer s) throws IOException { // Serialize for EAS here // Set uid with the client id we created // 1) Serialize the top-level event // 2) Serialize attendees and reminders from subvalues // 3) Look for exceptions and serialize with the top-level event ContentValues entityValues = entity.getEntityValues(); final boolean isException = (clientId == null); boolean hasAttendees = false; final boolean isChange = entityValues.containsKey(Events._SYNC_ID); final Double version = mService.mProtocolVersionDouble; final boolean allDay = CalendarUtilities.getIntegerValueAsBoolean(entityValues, Events.ALL_DAY); // NOTE: Exchange 2003 (EAS 2.5) seems to require the "exception deleted" and "exception // start time" data before other data in exceptions. Failure to do so results in a // status 6 error during sync if (isException) { // Send exception deleted flag if necessary Integer deleted = entityValues.getAsInteger(Events.DELETED); boolean isDeleted = deleted != null && deleted == 1; Integer eventStatus = entityValues.getAsInteger(Events.STATUS); boolean isCanceled = eventStatus != null && eventStatus.equals(Events.STATUS_CANCELED); if (isDeleted || isCanceled) { s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "1"); // If we're deleted, the UI will continue to show this exception until we mark // it canceled, so we'll do that here... if (isDeleted && !isCanceled) { final long eventId = entityValues.getAsLong(Events._ID); ContentValues cv = new ContentValues(); cv.put(Events.STATUS, Events.STATUS_CANCELED); mService.mContentResolver.update( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } } else { s.data(Tags.CALENDAR_EXCEPTION_IS_DELETED, "0"); } // TODO Add reminders to exceptions (allow them to be specified!) Long originalTime = entityValues.getAsLong(Events.ORIGINAL_INSTANCE_TIME); if (originalTime != null) { final boolean originalAllDay = CalendarUtilities.getIntegerValueAsBoolean(entityValues, Events.ORIGINAL_ALL_DAY); if (originalAllDay) { // For all day events, we need our local all-day time originalTime = CalendarUtilities.getLocalAllDayCalendarTime(originalTime, mLocalTimeZone); } s.data(Tags.CALENDAR_EXCEPTION_START_TIME, CalendarUtilities.millisToEasDateTime(originalTime)); } else { // Illegal; what should we do? } } // Get the event's time zone String timeZoneName = entityValues.getAsString(allDay ? EVENT_SAVED_TIMEZONE_COLUMN : Events.EVENT_TIMEZONE); if (timeZoneName == null) { timeZoneName = mLocalTimeZone.getID(); } TimeZone eventTimeZone = TimeZone.getTimeZone(timeZoneName); if (!isException) { // A time zone is required in all EAS events; we'll use the default if none is set // Exchange 2003 seems to require this first... :-) String timeZone = CalendarUtilities.timeZoneToTziString(eventTimeZone); s.data(Tags.CALENDAR_TIME_ZONE, timeZone); } s.data(Tags.CALENDAR_ALL_DAY_EVENT, allDay ? "1" : "0"); // DTSTART is always supplied long startTime = entityValues.getAsLong(Events.DTSTART); // Determine endTime; it's either provided as DTEND or we calculate using DURATION // If no DURATION is provided, we default to one hour long endTime; if (entityValues.containsKey(Events.DTEND)) { endTime = entityValues.getAsLong(Events.DTEND); } else { long durationMillis = HOURS; if (entityValues.containsKey(Events.DURATION)) { Duration duration = new Duration(); try { duration.parse(entityValues.getAsString(Events.DURATION)); durationMillis = duration.getMillis(); } catch (ParseException e) { // Can't do much about this; use the default (1 hour) } } endTime = startTime + durationMillis; } if (allDay) { TimeZone tz = mLocalTimeZone; startTime = CalendarUtilities.getLocalAllDayCalendarTime(startTime, tz); endTime = CalendarUtilities.getLocalAllDayCalendarTime(endTime, tz); } s.data(Tags.CALENDAR_START_TIME, CalendarUtilities.millisToEasDateTime(startTime)); s.data(Tags.CALENDAR_END_TIME, CalendarUtilities.millisToEasDateTime(endTime)); s.data(Tags.CALENDAR_DTSTAMP, CalendarUtilities.millisToEasDateTime(System.currentTimeMillis())); String loc = entityValues.getAsString(Events.EVENT_LOCATION); if (!TextUtils.isEmpty(loc)) { if (version < Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { // EAS 2.5 doesn't like bare line feeds loc = Utility.replaceBareLfWithCrlf(loc); } s.data(Tags.CALENDAR_LOCATION, loc); } s.writeStringValue(entityValues, Events.TITLE, Tags.CALENDAR_SUBJECT); if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { s.start(Tags.BASE_BODY); s.data(Tags.BASE_TYPE, "1"); s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.BASE_DATA); s.end(); } else { // EAS 2.5 doesn't like bare line feeds s.writeStringValue(entityValues, Events.DESCRIPTION, Tags.CALENDAR_BODY); } if (!isException) { // For Exchange 2003, only upsync if the event is new if ((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) { s.writeStringValue(entityValues, Events.ORGANIZER, Tags.CALENDAR_ORGANIZER_EMAIL); } String rrule = entityValues.getAsString(Events.RRULE); if (rrule != null) { CalendarUtilities.recurrenceFromRrule(rrule, startTime, s); } // Handle associated data EXCEPT for attendees, which have to be grouped ArrayList<NamedContentValues> subValues = entity.getSubValues(); // The earliest of the reminders for this Event; we can only send one reminder... int earliestReminder = -1; for (NamedContentValues ncv: subValues) { Uri ncvUri = ncv.uri; ContentValues ncvValues = ncv.values; if (ncvUri.equals(ExtendedProperties.CONTENT_URI)) { String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); String propertyValue = ncvValues.getAsString(ExtendedProperties.VALUE); if (TextUtils.isEmpty(propertyValue)) { continue; } if (propertyName.equals(EXTENDED_PROPERTY_CATEGORIES)) { // Send all the categories back to the server // We've saved them as a String of delimited tokens StringTokenizer st = new StringTokenizer(propertyValue, CATEGORY_TOKENIZER_DELIMITER); if (st.countTokens() > 0) { s.start(Tags.CALENDAR_CATEGORIES); while (st.hasMoreTokens()) { String category = st.nextToken(); s.data(Tags.CALENDAR_CATEGORY, category); } s.end(); } } } else if (ncvUri.equals(Reminders.CONTENT_URI)) { Integer mins = ncvValues.getAsInteger(Reminders.MINUTES); if (mins != null) { // -1 means "default", which for Exchange, is 30 if (mins < 0) { mins = 30; } // Save this away if it's the earliest reminder (greatest minutes) if (mins > earliestReminder) { earliestReminder = mins; } } } } // If we have a reminder, send it to the server if (earliestReminder >= 0) { s.data(Tags.CALENDAR_REMINDER_MINS_BEFORE, Integer.toString(earliestReminder)); } // We've got to send a UID, unless this is an exception. If the event is new, we've // generated one; if not, we should have gotten one from extended properties. if (clientId != null) { s.data(Tags.CALENDAR_UID, clientId); } // Handle attendee data here; keep track of organizer and stream it afterward String organizerName = null; String organizerEmail = null; for (NamedContentValues ncv: subValues) { Uri ncvUri = ncv.uri; ContentValues ncvValues = ncv.values; if (ncvUri.equals(Attendees.CONTENT_URI)) { Integer relationship = ncvValues.getAsInteger(Attendees.ATTENDEE_RELATIONSHIP); // If there's no relationship, we can't create this for EAS // Similarly, we need an attendee email for each invitee if (relationship != null && ncvValues.containsKey(Attendees.ATTENDEE_EMAIL)) { // Organizer isn't among attendees in EAS if (relationship == Attendees.RELATIONSHIP_ORGANIZER) { organizerName = ncvValues.getAsString(Attendees.ATTENDEE_NAME); organizerEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL); continue; } if (!hasAttendees) { s.start(Tags.CALENDAR_ATTENDEES); hasAttendees = true; } s.start(Tags.CALENDAR_ATTENDEE); String attendeeEmail = ncvValues.getAsString(Attendees.ATTENDEE_EMAIL); String attendeeName = ncvValues.getAsString(Attendees.ATTENDEE_NAME); if (attendeeName == null) { attendeeName = attendeeEmail; } s.data(Tags.CALENDAR_ATTENDEE_NAME, attendeeName); s.data(Tags.CALENDAR_ATTENDEE_EMAIL, attendeeEmail); if (version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) { s.data(Tags.CALENDAR_ATTENDEE_TYPE, "1"); // Required } s.end(); // Attendee } } } if (hasAttendees) { s.end(); // Attendees } // Get busy status from Attendees table long eventId = entityValues.getAsLong(Events._ID); int busyStatus = CalendarUtilities.BUSY_STATUS_TENTATIVE; Cursor c = mService.mContentResolver.query( asSyncAdapter(Attendees.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), ATTENDEE_STATUS_PROJECTION, EVENT_AND_EMAIL, new String[] {Long.toString(eventId), mEmailAddress}, null); if (c != null) { try { if (c.moveToFirst()) { busyStatus = CalendarUtilities.busyStatusFromAttendeeStatus( c.getInt(ATTENDEE_STATUS_COLUMN_STATUS)); } } finally { c.close(); } } s.data(Tags.CALENDAR_BUSY_STATUS, Integer.toString(busyStatus)); // Meeting status, 0 = appointment, 1 = meeting, 3 = attendee if (mEmailAddress.equalsIgnoreCase(organizerEmail)) { s.data(Tags.CALENDAR_MEETING_STATUS, hasAttendees ? "1" : "0"); } else { s.data(Tags.CALENDAR_MEETING_STATUS, "3"); } // For Exchange 2003, only upsync if the event is new if (((version >= Eas.SUPPORTED_PROTOCOL_EX2007_DOUBLE) || !isChange) && organizerName != null) { s.data(Tags.CALENDAR_ORGANIZER_NAME, organizerName); } // NOTE: Sensitivity must NOT be sent to the server for exceptions in Exchange 2003 // The result will be a status 6 failure during sync Integer visibility = entityValues.getAsInteger(Events.ACCESS_LEVEL); if (visibility != null) { s.data(Tags.CALENDAR_SENSITIVITY, decodeVisibility(visibility)); } else { // Default to private if not set s.data(Tags.CALENDAR_SENSITIVITY, "1"); } } } /** * Convenience method for sending an email to the organizer declining the meeting * @param entity * @param clientId */ private void sendDeclinedEmail(Entity entity, String clientId) { Message msg = CalendarUtilities.createMessageForEntity(mContext, entity, Message.FLAG_OUTGOING_MEETING_DECLINE, clientId, mAccount); if (msg != null) { userLog("Queueing declined response to " + msg.mTo); mOutgoingMailList.add(msg); } } @Override public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mService.mContentResolver; if (getSyncKey().equals("0")) { return false; } try { // We've got to handle exceptions as part of the parent when changes occur, so we need // to find new/changed exceptions and mark the parent dirty ArrayList<Long> orphanedExceptions = new ArrayList<Long>(); Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION, DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null); try { ContentValues cv = new ContentValues(); // We use _sync_mark here to distinguish dirty parents from parents with dirty // exceptions cv.put(EVENT_SYNC_MARK, "1"); while (c.moveToNext()) { // Mark the parents of dirty exceptions long parentId = c.getLong(0); int cnt = cr.update( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, EVENT_ID_AND_CALENDAR_ID, new String[] { Long.toString(parentId), mCalendarIdString }); // Keep track of any orphaned exceptions if (cnt == 0) { orphanedExceptions.add(c.getLong(1)); } } } finally { c.close(); } // Delete any orphaned exceptions for (long orphan : orphanedExceptions) { userLog(TAG, "Deleted orphaned exception: " + orphan); cr.delete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } orphanedExceptions.clear(); // Now we can go through dirty/marked top-level events and send them // back to the server EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr); ContentValues cidValues = new ContentValues(); try { boolean first = true; while (eventIterator.hasNext()) { Entity entity = eventIterator.next(); // For each of these entities, create the change commands ContentValues entityValues = entity.getEntityValues(); String serverId = entityValues.getAsString(Events._SYNC_ID); // We first need to check whether we can upsync this event; our test for this // is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED // If this is set to "1", we can't upsync the event for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; if (ncvValues.getAsString(ExtendedProperties.NAME).equals( EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) { if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) { // Make sure we mark this to clear the dirty flag mUploadedIdList.add(entityValues.getAsLong(Events._ID)); continue; } } } } // Find our uid in the entity; otherwise create one String clientId = entityValues.getAsString(Events.SYNC_DATA2); if (clientId == null) { clientId = UUID.randomUUID().toString(); } // EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID // We can generate all but what we're testing for below String organizerEmail = entityValues.getAsString(Events.ORGANIZER); boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress); if (!entityValues.containsKey(Events.DTSTART) || (!entityValues.containsKey(Events.DURATION) && !entityValues.containsKey(Events.DTEND)) || organizerEmail == null) { continue; } if (first) { s.start(Tags.SYNC_COMMANDS); userLog("Sending Calendar changes to the server"); first = false; } long eventId = entityValues.getAsLong(Events._ID); if (serverId == null) { // This is a new event; create a clientId userLog("Creating new event with clientId: ", clientId); s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId); // And save it in the Event as the local id cidValues.put(Events.SYNC_DATA2, clientId); cidValues.put(EVENT_SYNC_VERSION, "0"); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); } else { if (entityValues.getAsInteger(Events.DELETED) == 1) { userLog("Deleting event with serverId: ", serverId); s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); mDeletedIdList.add(eventId); if (selfOrganizer) { mSendCancelIdList.add(eventId); } else { sendDeclinedEmail(entity, clientId); } continue; } userLog("Upsync change to event with serverId: " + serverId); // Get the current version String version = entityValues.getAsString(EVENT_SYNC_VERSION); // This should never be null, but catch this error anyway // Version should be "0" when we create the event, so use that if (version == null) { version = "0"; } else { // Increment and save try { version = Integer.toString((Integer.parseInt(version) + 1)); } catch (Exception e) { // Handle the case in which someone writes a non-integer here; // shouldn't happen, but we don't want to kill the sync for his version = "0"; } } cidValues.put(EVENT_SYNC_VERSION, version); // Also save in entityValues so that we send it this time around entityValues.put(EVENT_SYNC_VERSION, version); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId); } s.start(Tags.SYNC_APPLICATION_DATA); sendEvent(entity, clientId, s); // Now, the hard part; find exceptions for this event if (serverId != null) { EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, ORIGINAL_EVENT_AND_CALENDAR, new String[] { serverId, mCalendarIdString }, null), cr); boolean exFirst = true; while (exIterator.hasNext()) { Entity exEntity = exIterator.next(); if (exFirst) { s.start(Tags.CALENDAR_EXCEPTIONS); exFirst = false; } s.start(Tags.CALENDAR_EXCEPTION); sendEvent(exEntity, null, s); ContentValues exValues = exEntity.getEntityValues(); if (getInt(exValues, Events.DIRTY) == 1) { // This is a new/updated exception, so we've got to notify our // attendees about it long exEventId = exValues.getAsLong(Events._ID); int flag; // Copy subvalues into the exception; otherwise, we won't see the // attendees when preparing the message for (NamedContentValues ncv: entity.getSubValues()) { exEntity.addSubValue(ncv.uri, ncv.values); } if ((getInt(exValues, Events.DELETED) == 1) || (getInt(exValues, Events.STATUS) == Events.STATUS_CANCELED)) { flag = Message.FLAG_OUTGOING_MEETING_CANCEL; if (!selfOrganizer) { // Send a cancellation notice to the organizer // Since CalendarProvider2 sets the organizer of exceptions // to the user, we have to reset it first to the original // organizer exValues.put(Events.ORGANIZER, entityValues.getAsString(Events.ORGANIZER)); sendDeclinedEmail(exEntity, clientId); } } else { flag = Message.FLAG_OUTGOING_MEETING_INVITE; } // Add the eventId of the exception to the uploaded id list, so that // the dirty/mark bits are cleared mUploadedIdList.add(exEventId); // Copy version so the ics attachment shows the proper sequence # exValues.put(EVENT_SYNC_VERSION, entityValues.getAsString(EVENT_SYNC_VERSION)); // Copy location so that it's included in the outgoing email if (entityValues.containsKey(Events.EVENT_LOCATION)) { exValues.put(Events.EVENT_LOCATION, entityValues.getAsString(Events.EVENT_LOCATION)); } if (selfOrganizer) { Message msg = CalendarUtilities.createMessageForEntity(mContext, exEntity, flag, clientId, mAccount); if (msg != null) { userLog("Queueing exception update to " + msg.mTo); mOutgoingMailList.add(msg); } } } s.end(); // EXCEPTION } if (!exFirst) { s.end(); // EXCEPTIONS } } s.end().end(); // ApplicationData & Change mUploadedIdList.add(eventId); // Go through the extended properties of this Event and pull out our tokenized // attendees list and the user attendee status; we will need them later String attendeeString = null; long attendeeStringId = -1; String userAttendeeStatus = null; long userAttendeeStatusId = -1; for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) { attendeeString = ncvValues.getAsString(ExtendedProperties.VALUE); attendeeStringId = ncvValues.getAsLong(ExtendedProperties._ID); } else if (propertyName.equals( EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) { userAttendeeStatus = ncvValues.getAsString(ExtendedProperties.VALUE); userAttendeeStatusId = ncvValues.getAsLong(ExtendedProperties._ID); } } } // Send the meeting invite if there are attendees and we're the organizer AND // if the Event itself is dirty (we might be syncing only because an exception // is dirty, in which case we DON'T send email about the Event) if (selfOrganizer && (getInt(entityValues, Events.DIRTY) == 1)) { EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId, mAccount); if (msg != null) { userLog("Queueing invitation to ", msg.mTo); mOutgoingMailList.add(msg); } // Make a list out of our tokenized attendees, if we have any ArrayList<String> originalAttendeeList = new ArrayList<String>(); if (attendeeString != null) { StringTokenizer st = new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER); while (st.hasMoreTokens()) { originalAttendeeList.add(st.nextToken()); } } StringBuilder newTokenizedAttendees = new StringBuilder(); // See if any attendees have been dropped and while we're at it, build // an updated String with tokenized attendee addresses for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(Attendees.CONTENT_URI)) { String attendeeEmail = ncv.values.getAsString(Attendees.ATTENDEE_EMAIL); // Remove all found attendees originalAttendeeList.remove(attendeeEmail); newTokenizedAttendees.append(attendeeEmail); newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER); } } // Update extended properties with the new attendee list, if we have one // Otherwise, create one (this would be the case for Events created on // device or "legacy" events (before this code was added) ContentValues cv = new ContentValues(); cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString()); if (attendeeString != null) { cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, attendeeStringId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } else { // If there wasn't an "attendees" property, insert one cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES); cv.put(ExtendedProperties.EVENT_ID, eventId); cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv); } // Whoever is left has been removed from the attendee list; send them // a cancellation for (String removedAttendee: originalAttendeeList) { // Send a cancellation message to each of them msg = CalendarUtilities.createMessageForEventId(mContext, eventId, Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount, removedAttendee); if (msg != null) { // Just send it to the removed attendee userLog("Queueing cancellation to removed attendee " + msg.mTo); mOutgoingMailList.add(msg); } } } else if (!selfOrganizer) { // If we're not the organizer, see if we've changed our attendee status // Our last synced attendee status is in ExtendedProperties, and we've // retrieved it above as userAttendeeStatus int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS); int syncStatus = Attendees.ATTENDEE_STATUS_NONE; if (userAttendeeStatus != null) { try { syncStatus = Integer.parseInt(userAttendeeStatus); } catch (NumberFormatException e) { // Just in case somebody else mucked with this and it's not Integer } } if ((currentStatus != syncStatus) && (currentStatus != Attendees.ATTENDEE_STATUS_NONE)) { // If so, send a meeting reply int messageFlag = 0; switch (currentStatus) { case Attendees.ATTENDEE_STATUS_ACCEPTED: messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT; break; case Attendees.ATTENDEE_STATUS_DECLINED: messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE; break; case Attendees.ATTENDEE_STATUS_TENTATIVE: messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; break; } // Make sure we have a valid status (messageFlag should never be zero) if (messageFlag != 0 && userAttendeeStatusId >= 0) { // Save away the new status cidValues.clear(); cidValues.put(ExtendedProperties.VALUE, Integer.toString(currentStatus)); - cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI, - userAttendeeStatusId), cidValues, null, null); + cr.update(asSyncAdapter(ContentUris.withAppendedId( + ExtendedProperties.CONTENT_URI, userAttendeeStatusId), + mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), + cidValues, null, null); // Send mail to the organizer advising of the new status EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, messageFlag, clientId, mAccount); if (msg != null) { userLog("Queueing invitation reply to " + msg.mTo); mOutgoingMailList.add(msg); } } } } } if (!first) { s.end(); // Commands } } finally { eventIterator.close(); } } catch (RemoteException e) { Log.e(TAG, "Could not read dirty events."); } return false; } }
true
true
public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mService.mContentResolver; if (getSyncKey().equals("0")) { return false; } try { // We've got to handle exceptions as part of the parent when changes occur, so we need // to find new/changed exceptions and mark the parent dirty ArrayList<Long> orphanedExceptions = new ArrayList<Long>(); Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION, DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null); try { ContentValues cv = new ContentValues(); // We use _sync_mark here to distinguish dirty parents from parents with dirty // exceptions cv.put(EVENT_SYNC_MARK, "1"); while (c.moveToNext()) { // Mark the parents of dirty exceptions long parentId = c.getLong(0); int cnt = cr.update( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, EVENT_ID_AND_CALENDAR_ID, new String[] { Long.toString(parentId), mCalendarIdString }); // Keep track of any orphaned exceptions if (cnt == 0) { orphanedExceptions.add(c.getLong(1)); } } } finally { c.close(); } // Delete any orphaned exceptions for (long orphan : orphanedExceptions) { userLog(TAG, "Deleted orphaned exception: " + orphan); cr.delete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } orphanedExceptions.clear(); // Now we can go through dirty/marked top-level events and send them // back to the server EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr); ContentValues cidValues = new ContentValues(); try { boolean first = true; while (eventIterator.hasNext()) { Entity entity = eventIterator.next(); // For each of these entities, create the change commands ContentValues entityValues = entity.getEntityValues(); String serverId = entityValues.getAsString(Events._SYNC_ID); // We first need to check whether we can upsync this event; our test for this // is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED // If this is set to "1", we can't upsync the event for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; if (ncvValues.getAsString(ExtendedProperties.NAME).equals( EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) { if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) { // Make sure we mark this to clear the dirty flag mUploadedIdList.add(entityValues.getAsLong(Events._ID)); continue; } } } } // Find our uid in the entity; otherwise create one String clientId = entityValues.getAsString(Events.SYNC_DATA2); if (clientId == null) { clientId = UUID.randomUUID().toString(); } // EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID // We can generate all but what we're testing for below String organizerEmail = entityValues.getAsString(Events.ORGANIZER); boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress); if (!entityValues.containsKey(Events.DTSTART) || (!entityValues.containsKey(Events.DURATION) && !entityValues.containsKey(Events.DTEND)) || organizerEmail == null) { continue; } if (first) { s.start(Tags.SYNC_COMMANDS); userLog("Sending Calendar changes to the server"); first = false; } long eventId = entityValues.getAsLong(Events._ID); if (serverId == null) { // This is a new event; create a clientId userLog("Creating new event with clientId: ", clientId); s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId); // And save it in the Event as the local id cidValues.put(Events.SYNC_DATA2, clientId); cidValues.put(EVENT_SYNC_VERSION, "0"); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); } else { if (entityValues.getAsInteger(Events.DELETED) == 1) { userLog("Deleting event with serverId: ", serverId); s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); mDeletedIdList.add(eventId); if (selfOrganizer) { mSendCancelIdList.add(eventId); } else { sendDeclinedEmail(entity, clientId); } continue; } userLog("Upsync change to event with serverId: " + serverId); // Get the current version String version = entityValues.getAsString(EVENT_SYNC_VERSION); // This should never be null, but catch this error anyway // Version should be "0" when we create the event, so use that if (version == null) { version = "0"; } else { // Increment and save try { version = Integer.toString((Integer.parseInt(version) + 1)); } catch (Exception e) { // Handle the case in which someone writes a non-integer here; // shouldn't happen, but we don't want to kill the sync for his version = "0"; } } cidValues.put(EVENT_SYNC_VERSION, version); // Also save in entityValues so that we send it this time around entityValues.put(EVENT_SYNC_VERSION, version); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId); } s.start(Tags.SYNC_APPLICATION_DATA); sendEvent(entity, clientId, s); // Now, the hard part; find exceptions for this event if (serverId != null) { EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, ORIGINAL_EVENT_AND_CALENDAR, new String[] { serverId, mCalendarIdString }, null), cr); boolean exFirst = true; while (exIterator.hasNext()) { Entity exEntity = exIterator.next(); if (exFirst) { s.start(Tags.CALENDAR_EXCEPTIONS); exFirst = false; } s.start(Tags.CALENDAR_EXCEPTION); sendEvent(exEntity, null, s); ContentValues exValues = exEntity.getEntityValues(); if (getInt(exValues, Events.DIRTY) == 1) { // This is a new/updated exception, so we've got to notify our // attendees about it long exEventId = exValues.getAsLong(Events._ID); int flag; // Copy subvalues into the exception; otherwise, we won't see the // attendees when preparing the message for (NamedContentValues ncv: entity.getSubValues()) { exEntity.addSubValue(ncv.uri, ncv.values); } if ((getInt(exValues, Events.DELETED) == 1) || (getInt(exValues, Events.STATUS) == Events.STATUS_CANCELED)) { flag = Message.FLAG_OUTGOING_MEETING_CANCEL; if (!selfOrganizer) { // Send a cancellation notice to the organizer // Since CalendarProvider2 sets the organizer of exceptions // to the user, we have to reset it first to the original // organizer exValues.put(Events.ORGANIZER, entityValues.getAsString(Events.ORGANIZER)); sendDeclinedEmail(exEntity, clientId); } } else { flag = Message.FLAG_OUTGOING_MEETING_INVITE; } // Add the eventId of the exception to the uploaded id list, so that // the dirty/mark bits are cleared mUploadedIdList.add(exEventId); // Copy version so the ics attachment shows the proper sequence # exValues.put(EVENT_SYNC_VERSION, entityValues.getAsString(EVENT_SYNC_VERSION)); // Copy location so that it's included in the outgoing email if (entityValues.containsKey(Events.EVENT_LOCATION)) { exValues.put(Events.EVENT_LOCATION, entityValues.getAsString(Events.EVENT_LOCATION)); } if (selfOrganizer) { Message msg = CalendarUtilities.createMessageForEntity(mContext, exEntity, flag, clientId, mAccount); if (msg != null) { userLog("Queueing exception update to " + msg.mTo); mOutgoingMailList.add(msg); } } } s.end(); // EXCEPTION } if (!exFirst) { s.end(); // EXCEPTIONS } } s.end().end(); // ApplicationData & Change mUploadedIdList.add(eventId); // Go through the extended properties of this Event and pull out our tokenized // attendees list and the user attendee status; we will need them later String attendeeString = null; long attendeeStringId = -1; String userAttendeeStatus = null; long userAttendeeStatusId = -1; for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) { attendeeString = ncvValues.getAsString(ExtendedProperties.VALUE); attendeeStringId = ncvValues.getAsLong(ExtendedProperties._ID); } else if (propertyName.equals( EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) { userAttendeeStatus = ncvValues.getAsString(ExtendedProperties.VALUE); userAttendeeStatusId = ncvValues.getAsLong(ExtendedProperties._ID); } } } // Send the meeting invite if there are attendees and we're the organizer AND // if the Event itself is dirty (we might be syncing only because an exception // is dirty, in which case we DON'T send email about the Event) if (selfOrganizer && (getInt(entityValues, Events.DIRTY) == 1)) { EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId, mAccount); if (msg != null) { userLog("Queueing invitation to ", msg.mTo); mOutgoingMailList.add(msg); } // Make a list out of our tokenized attendees, if we have any ArrayList<String> originalAttendeeList = new ArrayList<String>(); if (attendeeString != null) { StringTokenizer st = new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER); while (st.hasMoreTokens()) { originalAttendeeList.add(st.nextToken()); } } StringBuilder newTokenizedAttendees = new StringBuilder(); // See if any attendees have been dropped and while we're at it, build // an updated String with tokenized attendee addresses for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(Attendees.CONTENT_URI)) { String attendeeEmail = ncv.values.getAsString(Attendees.ATTENDEE_EMAIL); // Remove all found attendees originalAttendeeList.remove(attendeeEmail); newTokenizedAttendees.append(attendeeEmail); newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER); } } // Update extended properties with the new attendee list, if we have one // Otherwise, create one (this would be the case for Events created on // device or "legacy" events (before this code was added) ContentValues cv = new ContentValues(); cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString()); if (attendeeString != null) { cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, attendeeStringId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } else { // If there wasn't an "attendees" property, insert one cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES); cv.put(ExtendedProperties.EVENT_ID, eventId); cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv); } // Whoever is left has been removed from the attendee list; send them // a cancellation for (String removedAttendee: originalAttendeeList) { // Send a cancellation message to each of them msg = CalendarUtilities.createMessageForEventId(mContext, eventId, Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount, removedAttendee); if (msg != null) { // Just send it to the removed attendee userLog("Queueing cancellation to removed attendee " + msg.mTo); mOutgoingMailList.add(msg); } } } else if (!selfOrganizer) { // If we're not the organizer, see if we've changed our attendee status // Our last synced attendee status is in ExtendedProperties, and we've // retrieved it above as userAttendeeStatus int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS); int syncStatus = Attendees.ATTENDEE_STATUS_NONE; if (userAttendeeStatus != null) { try { syncStatus = Integer.parseInt(userAttendeeStatus); } catch (NumberFormatException e) { // Just in case somebody else mucked with this and it's not Integer } } if ((currentStatus != syncStatus) && (currentStatus != Attendees.ATTENDEE_STATUS_NONE)) { // If so, send a meeting reply int messageFlag = 0; switch (currentStatus) { case Attendees.ATTENDEE_STATUS_ACCEPTED: messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT; break; case Attendees.ATTENDEE_STATUS_DECLINED: messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE; break; case Attendees.ATTENDEE_STATUS_TENTATIVE: messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; break; } // Make sure we have a valid status (messageFlag should never be zero) if (messageFlag != 0 && userAttendeeStatusId >= 0) { // Save away the new status cidValues.clear(); cidValues.put(ExtendedProperties.VALUE, Integer.toString(currentStatus)); cr.update(ContentUris.withAppendedId(ExtendedProperties.CONTENT_URI, userAttendeeStatusId), cidValues, null, null); // Send mail to the organizer advising of the new status EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, messageFlag, clientId, mAccount); if (msg != null) { userLog("Queueing invitation reply to " + msg.mTo); mOutgoingMailList.add(msg); } } } } } if (!first) { s.end(); // Commands } } finally { eventIterator.close(); } } catch (RemoteException e) { Log.e(TAG, "Could not read dirty events."); } return false; }
public boolean sendLocalChanges(Serializer s) throws IOException { ContentResolver cr = mService.mContentResolver; if (getSyncKey().equals("0")) { return false; } try { // We've got to handle exceptions as part of the parent when changes occur, so we need // to find new/changed exceptions and mark the parent dirty ArrayList<Long> orphanedExceptions = new ArrayList<Long>(); Cursor c = cr.query(Events.CONTENT_URI, ORIGINAL_EVENT_PROJECTION, DIRTY_EXCEPTION_IN_CALENDAR, mCalendarIdArgument, null); try { ContentValues cv = new ContentValues(); // We use _sync_mark here to distinguish dirty parents from parents with dirty // exceptions cv.put(EVENT_SYNC_MARK, "1"); while (c.moveToNext()) { // Mark the parents of dirty exceptions long parentId = c.getLong(0); int cnt = cr.update( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, EVENT_ID_AND_CALENDAR_ID, new String[] { Long.toString(parentId), mCalendarIdString }); // Keep track of any orphaned exceptions if (cnt == 0) { orphanedExceptions.add(c.getLong(1)); } } } finally { c.close(); } // Delete any orphaned exceptions for (long orphan : orphanedExceptions) { userLog(TAG, "Deleted orphaned exception: " + orphan); cr.delete( asSyncAdapter(ContentUris.withAppendedId(Events.CONTENT_URI, orphan), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, null); } orphanedExceptions.clear(); // Now we can go through dirty/marked top-level events and send them // back to the server EntityIterator eventIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, DIRTY_OR_MARKED_TOP_LEVEL_IN_CALENDAR, mCalendarIdArgument, null), cr); ContentValues cidValues = new ContentValues(); try { boolean first = true; while (eventIterator.hasNext()) { Entity entity = eventIterator.next(); // For each of these entities, create the change commands ContentValues entityValues = entity.getEntityValues(); String serverId = entityValues.getAsString(Events._SYNC_ID); // We first need to check whether we can upsync this event; our test for this // is currently the value of EXTENDED_PROPERTY_ATTENDEES_REDACTED // If this is set to "1", we can't upsync the event for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; if (ncvValues.getAsString(ExtendedProperties.NAME).equals( EXTENDED_PROPERTY_UPSYNC_PROHIBITED)) { if ("1".equals(ncvValues.getAsString(ExtendedProperties.VALUE))) { // Make sure we mark this to clear the dirty flag mUploadedIdList.add(entityValues.getAsLong(Events._ID)); continue; } } } } // Find our uid in the entity; otherwise create one String clientId = entityValues.getAsString(Events.SYNC_DATA2); if (clientId == null) { clientId = UUID.randomUUID().toString(); } // EAS 2.5 needs: BusyStatus DtStamp EndTime Sensitivity StartTime TimeZone UID // We can generate all but what we're testing for below String organizerEmail = entityValues.getAsString(Events.ORGANIZER); boolean selfOrganizer = organizerEmail.equalsIgnoreCase(mEmailAddress); if (!entityValues.containsKey(Events.DTSTART) || (!entityValues.containsKey(Events.DURATION) && !entityValues.containsKey(Events.DTEND)) || organizerEmail == null) { continue; } if (first) { s.start(Tags.SYNC_COMMANDS); userLog("Sending Calendar changes to the server"); first = false; } long eventId = entityValues.getAsLong(Events._ID); if (serverId == null) { // This is a new event; create a clientId userLog("Creating new event with clientId: ", clientId); s.start(Tags.SYNC_ADD).data(Tags.SYNC_CLIENT_ID, clientId); // And save it in the Event as the local id cidValues.put(Events.SYNC_DATA2, clientId); cidValues.put(EVENT_SYNC_VERSION, "0"); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); } else { if (entityValues.getAsInteger(Events.DELETED) == 1) { userLog("Deleting event with serverId: ", serverId); s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end(); mDeletedIdList.add(eventId); if (selfOrganizer) { mSendCancelIdList.add(eventId); } else { sendDeclinedEmail(entity, clientId); } continue; } userLog("Upsync change to event with serverId: " + serverId); // Get the current version String version = entityValues.getAsString(EVENT_SYNC_VERSION); // This should never be null, but catch this error anyway // Version should be "0" when we create the event, so use that if (version == null) { version = "0"; } else { // Increment and save try { version = Integer.toString((Integer.parseInt(version) + 1)); } catch (Exception e) { // Handle the case in which someone writes a non-integer here; // shouldn't happen, but we don't want to kill the sync for his version = "0"; } } cidValues.put(EVENT_SYNC_VERSION, version); // Also save in entityValues so that we send it this time around entityValues.put(EVENT_SYNC_VERSION, version); cr.update( asSyncAdapter( ContentUris.withAppendedId(Events.CONTENT_URI, eventId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); s.start(Tags.SYNC_CHANGE).data(Tags.SYNC_SERVER_ID, serverId); } s.start(Tags.SYNC_APPLICATION_DATA); sendEvent(entity, clientId, s); // Now, the hard part; find exceptions for this event if (serverId != null) { EntityIterator exIterator = EventsEntity.newEntityIterator(cr.query( asSyncAdapter(Events.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), null, ORIGINAL_EVENT_AND_CALENDAR, new String[] { serverId, mCalendarIdString }, null), cr); boolean exFirst = true; while (exIterator.hasNext()) { Entity exEntity = exIterator.next(); if (exFirst) { s.start(Tags.CALENDAR_EXCEPTIONS); exFirst = false; } s.start(Tags.CALENDAR_EXCEPTION); sendEvent(exEntity, null, s); ContentValues exValues = exEntity.getEntityValues(); if (getInt(exValues, Events.DIRTY) == 1) { // This is a new/updated exception, so we've got to notify our // attendees about it long exEventId = exValues.getAsLong(Events._ID); int flag; // Copy subvalues into the exception; otherwise, we won't see the // attendees when preparing the message for (NamedContentValues ncv: entity.getSubValues()) { exEntity.addSubValue(ncv.uri, ncv.values); } if ((getInt(exValues, Events.DELETED) == 1) || (getInt(exValues, Events.STATUS) == Events.STATUS_CANCELED)) { flag = Message.FLAG_OUTGOING_MEETING_CANCEL; if (!selfOrganizer) { // Send a cancellation notice to the organizer // Since CalendarProvider2 sets the organizer of exceptions // to the user, we have to reset it first to the original // organizer exValues.put(Events.ORGANIZER, entityValues.getAsString(Events.ORGANIZER)); sendDeclinedEmail(exEntity, clientId); } } else { flag = Message.FLAG_OUTGOING_MEETING_INVITE; } // Add the eventId of the exception to the uploaded id list, so that // the dirty/mark bits are cleared mUploadedIdList.add(exEventId); // Copy version so the ics attachment shows the proper sequence # exValues.put(EVENT_SYNC_VERSION, entityValues.getAsString(EVENT_SYNC_VERSION)); // Copy location so that it's included in the outgoing email if (entityValues.containsKey(Events.EVENT_LOCATION)) { exValues.put(Events.EVENT_LOCATION, entityValues.getAsString(Events.EVENT_LOCATION)); } if (selfOrganizer) { Message msg = CalendarUtilities.createMessageForEntity(mContext, exEntity, flag, clientId, mAccount); if (msg != null) { userLog("Queueing exception update to " + msg.mTo); mOutgoingMailList.add(msg); } } } s.end(); // EXCEPTION } if (!exFirst) { s.end(); // EXCEPTIONS } } s.end().end(); // ApplicationData & Change mUploadedIdList.add(eventId); // Go through the extended properties of this Event and pull out our tokenized // attendees list and the user attendee status; we will need them later String attendeeString = null; long attendeeStringId = -1; String userAttendeeStatus = null; long userAttendeeStatusId = -1; for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(ExtendedProperties.CONTENT_URI)) { ContentValues ncvValues = ncv.values; String propertyName = ncvValues.getAsString(ExtendedProperties.NAME); if (propertyName.equals(EXTENDED_PROPERTY_ATTENDEES)) { attendeeString = ncvValues.getAsString(ExtendedProperties.VALUE); attendeeStringId = ncvValues.getAsLong(ExtendedProperties._ID); } else if (propertyName.equals( EXTENDED_PROPERTY_USER_ATTENDEE_STATUS)) { userAttendeeStatus = ncvValues.getAsString(ExtendedProperties.VALUE); userAttendeeStatusId = ncvValues.getAsLong(ExtendedProperties._ID); } } } // Send the meeting invite if there are attendees and we're the organizer AND // if the Event itself is dirty (we might be syncing only because an exception // is dirty, in which case we DON'T send email about the Event) if (selfOrganizer && (getInt(entityValues, Events.DIRTY) == 1)) { EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, EmailContent.Message.FLAG_OUTGOING_MEETING_INVITE, clientId, mAccount); if (msg != null) { userLog("Queueing invitation to ", msg.mTo); mOutgoingMailList.add(msg); } // Make a list out of our tokenized attendees, if we have any ArrayList<String> originalAttendeeList = new ArrayList<String>(); if (attendeeString != null) { StringTokenizer st = new StringTokenizer(attendeeString, ATTENDEE_TOKENIZER_DELIMITER); while (st.hasMoreTokens()) { originalAttendeeList.add(st.nextToken()); } } StringBuilder newTokenizedAttendees = new StringBuilder(); // See if any attendees have been dropped and while we're at it, build // an updated String with tokenized attendee addresses for (NamedContentValues ncv: entity.getSubValues()) { if (ncv.uri.equals(Attendees.CONTENT_URI)) { String attendeeEmail = ncv.values.getAsString(Attendees.ATTENDEE_EMAIL); // Remove all found attendees originalAttendeeList.remove(attendeeEmail); newTokenizedAttendees.append(attendeeEmail); newTokenizedAttendees.append(ATTENDEE_TOKENIZER_DELIMITER); } } // Update extended properties with the new attendee list, if we have one // Otherwise, create one (this would be the case for Events created on // device or "legacy" events (before this code was added) ContentValues cv = new ContentValues(); cv.put(ExtendedProperties.VALUE, newTokenizedAttendees.toString()); if (attendeeString != null) { cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, attendeeStringId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv, null, null); } else { // If there wasn't an "attendees" property, insert one cv.put(ExtendedProperties.NAME, EXTENDED_PROPERTY_ATTENDEES); cv.put(ExtendedProperties.EVENT_ID, eventId); cr.insert(asSyncAdapter(ExtendedProperties.CONTENT_URI, mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cv); } // Whoever is left has been removed from the attendee list; send them // a cancellation for (String removedAttendee: originalAttendeeList) { // Send a cancellation message to each of them msg = CalendarUtilities.createMessageForEventId(mContext, eventId, Message.FLAG_OUTGOING_MEETING_CANCEL, clientId, mAccount, removedAttendee); if (msg != null) { // Just send it to the removed attendee userLog("Queueing cancellation to removed attendee " + msg.mTo); mOutgoingMailList.add(msg); } } } else if (!selfOrganizer) { // If we're not the organizer, see if we've changed our attendee status // Our last synced attendee status is in ExtendedProperties, and we've // retrieved it above as userAttendeeStatus int currentStatus = entityValues.getAsInteger(Events.SELF_ATTENDEE_STATUS); int syncStatus = Attendees.ATTENDEE_STATUS_NONE; if (userAttendeeStatus != null) { try { syncStatus = Integer.parseInt(userAttendeeStatus); } catch (NumberFormatException e) { // Just in case somebody else mucked with this and it's not Integer } } if ((currentStatus != syncStatus) && (currentStatus != Attendees.ATTENDEE_STATUS_NONE)) { // If so, send a meeting reply int messageFlag = 0; switch (currentStatus) { case Attendees.ATTENDEE_STATUS_ACCEPTED: messageFlag = Message.FLAG_OUTGOING_MEETING_ACCEPT; break; case Attendees.ATTENDEE_STATUS_DECLINED: messageFlag = Message.FLAG_OUTGOING_MEETING_DECLINE; break; case Attendees.ATTENDEE_STATUS_TENTATIVE: messageFlag = Message.FLAG_OUTGOING_MEETING_TENTATIVE; break; } // Make sure we have a valid status (messageFlag should never be zero) if (messageFlag != 0 && userAttendeeStatusId >= 0) { // Save away the new status cidValues.clear(); cidValues.put(ExtendedProperties.VALUE, Integer.toString(currentStatus)); cr.update(asSyncAdapter(ContentUris.withAppendedId( ExtendedProperties.CONTENT_URI, userAttendeeStatusId), mEmailAddress, Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE), cidValues, null, null); // Send mail to the organizer advising of the new status EmailContent.Message msg = CalendarUtilities.createMessageForEventId(mContext, eventId, messageFlag, clientId, mAccount); if (msg != null) { userLog("Queueing invitation reply to " + msg.mTo); mOutgoingMailList.add(msg); } } } } } if (!first) { s.end(); // Commands } } finally { eventIterator.close(); } } catch (RemoteException e) { Log.e(TAG, "Could not read dirty events."); } return false; }
diff --git a/examples/src/com/clarkparsia/empire/examples/Main.java b/examples/src/com/clarkparsia/empire/examples/Main.java index 4c03c7e..98d5ac6 100644 --- a/examples/src/com/clarkparsia/empire/examples/Main.java +++ b/examples/src/com/clarkparsia/empire/examples/Main.java @@ -1,175 +1,170 @@ /* * Copyright (c) 2009-2010 Clark & Parsia, LLC. <http://www.clarkparsia.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.clarkparsia.empire.examples; import com.clarkparsia.empire.Empire; import com.clarkparsia.empire.impl.RdfQuery; import com.clarkparsia.empire.sesametwo.OpenRdfEmpireModule; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.Query; import java.net.URI; import java.util.Date; import java.util.Arrays; import java.util.List; /** * <p></p> * * @author Michael Grove */ public class Main { public static void main(String[] args) { // Alternatively you can use: -Dempire.configuration.file=examples/examples.empire.config.properties // if so, comment out this line. System.setProperty("empire.configuration.file", "examples/examples.empire.config.properties"); // loads Sesame bindings for Empire Empire.init(new OpenRdfEmpireModule()); // create an EntityManager for the specified persistence context EntityManager aManager = Persistence.createEntityManagerFactory("oreilly") .createEntityManager(); // this retrieves a particular book from the database - IBook aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); - aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); - aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); - aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); - aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); - aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); + Book aBook = aManager.find(Book.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); // prints: Switching to the Mac: The Missing Manual, Leopard Edition System.err.println(aBook.getTitle()); // prints: O'Reilly Media / Pogue Press System.err.println(aBook.getPublisher()); // creating a new book: Book aNewBook = new Book(); aNewBook.setIssued(new Date()); aNewBook.setTitle("How to use Empire"); aNewBook.setPublisher("Clark & Parsia"); aNewBook.setPrimarySubjectOf(URI.create("http://github.com/clarkparsia/Empire")); // grab the ebook manifestation Manifestation aEBook = aManager.find(Manifestation.class, URI.create("urn:x-domain:oreilly.com:product:9780596104306.EBOOK")); // and we'll use it as the embodiment of our new book. aNewBook.setEmbodiments(Arrays.asList(aEBook)); // save the new book to the database aManager.persist(aNewBook); Book aNewBookCopy = aManager.find(Book.class, aNewBook.getRdfId()); // true! System.err.println(aNewBook.equals(aNewBookCopy)); // lets edit our book... // maybe we changed the title and published as a PDF aNewBook.setTitle("Return of the Empire"); // create a new manifestation Manifestation aPDFManifestation = new Manifestation(); aPDFManifestation.setIssued(new Date()); // set the dc:type attribute aPDFManifestation.setType(URI.create("http://purl.oreilly.com/product-types/PDF")); aNewBook.setEmbodiments(Arrays.asList(aPDFManifestation)); // now save our edits aManager.merge(aNewBook); // print the new information we just saved System.err.println(aNewBook.getTitle()); System.err.println(aNewBook.getEmbodiments()); // and importantly, verify that the new manifestation was also saved due to the cascaded merge operation // specified in the Book class via the @OneToMany annotation // true! System.err.println(aManager.contains(aPDFManifestation)); // the copy of the book contains the old information System.err.println(aNewBookCopy.getTitle()); System.err.println(aNewBookCopy.getEmbodiments()); // but can be refreshed... aManager.refresh(aNewBookCopy); // and now contains the correct, up-to-date information System.err.println(aNewBookCopy.getTitle()); System.err.println(aNewBookCopy.getEmbodiments()); // now we can delete our new book aManager.remove(aNewBook); // false! System.err.println(aManager.contains(aNewBook)); // but the new manifestation still exists, since we did not specify that deletes should cascade... // true! System.err.println(aManager.contains(aPDFManifestation)); // Lastly, we can use the query API to run arbitrary sparql queries // create a jpql-style partial SPARQL query (JPQL is currently unsupported) Query aQuery = aManager.createQuery("where { ?result frbr:embodiment ?manifest." + " ?foo <http://purl.org/goodrelations/v1#typeOfGood> ?manifest . " + " ?foo <http://purl.org/goodrelations/v1#hasPriceSpecification> ?price. " + " ?price <http://purl.org/goodrelations/v1#hasCurrencyValue> ?value. " + " ?price <http://purl.org/goodrelations/v1#hasCurrency> \"USD\"@en." + " filter(?value > ??min). }"); // this query should return instances of type Book aQuery.setHint(RdfQuery.HINT_ENTITY_CLASS, Book.class); // set the parameter in the query to the value for the min price // parameters are prefixed with ?? aQuery.setParameter("min", 30); // now execute the query to get the list of all books which are $30 USD List aResults = aQuery.getResultList(); // 233 results System.err.println("Num Results: " + aResults.size()); // print the titles of the first five results for (int i = 0; i < 5; i++) { Book aBookResult = (Book) aResults.get(i); System.err.println(aBookResult.getTitle()); } /* * Switching to the Mac: The Missing Manual, Leopard Edition * O'Reilly Media / Pogue Press * true * Return of the Empire * [http://purl.oreilly.com/product-types/PDF] * true * How to use Empire * [http://purl.oreilly.com/product-types/EBOOK] * Return of the Empire * [http://purl.oreilly.com/product-types/PDF] * false * true * */ } }
true
true
public static void main(String[] args) { // Alternatively you can use: -Dempire.configuration.file=examples/examples.empire.config.properties // if so, comment out this line. System.setProperty("empire.configuration.file", "examples/examples.empire.config.properties"); // loads Sesame bindings for Empire Empire.init(new OpenRdfEmpireModule()); // create an EntityManager for the specified persistence context EntityManager aManager = Persistence.createEntityManagerFactory("oreilly") .createEntityManager(); // this retrieves a particular book from the database IBook aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); aBook = aManager.find(IBook.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); // prints: Switching to the Mac: The Missing Manual, Leopard Edition System.err.println(aBook.getTitle()); // prints: O'Reilly Media / Pogue Press System.err.println(aBook.getPublisher()); // creating a new book: Book aNewBook = new Book(); aNewBook.setIssued(new Date()); aNewBook.setTitle("How to use Empire"); aNewBook.setPublisher("Clark & Parsia"); aNewBook.setPrimarySubjectOf(URI.create("http://github.com/clarkparsia/Empire")); // grab the ebook manifestation Manifestation aEBook = aManager.find(Manifestation.class, URI.create("urn:x-domain:oreilly.com:product:9780596104306.EBOOK")); // and we'll use it as the embodiment of our new book. aNewBook.setEmbodiments(Arrays.asList(aEBook)); // save the new book to the database aManager.persist(aNewBook); Book aNewBookCopy = aManager.find(Book.class, aNewBook.getRdfId()); // true! System.err.println(aNewBook.equals(aNewBookCopy)); // lets edit our book... // maybe we changed the title and published as a PDF aNewBook.setTitle("Return of the Empire"); // create a new manifestation Manifestation aPDFManifestation = new Manifestation(); aPDFManifestation.setIssued(new Date()); // set the dc:type attribute aPDFManifestation.setType(URI.create("http://purl.oreilly.com/product-types/PDF")); aNewBook.setEmbodiments(Arrays.asList(aPDFManifestation)); // now save our edits aManager.merge(aNewBook); // print the new information we just saved System.err.println(aNewBook.getTitle()); System.err.println(aNewBook.getEmbodiments()); // and importantly, verify that the new manifestation was also saved due to the cascaded merge operation // specified in the Book class via the @OneToMany annotation // true! System.err.println(aManager.contains(aPDFManifestation)); // the copy of the book contains the old information System.err.println(aNewBookCopy.getTitle()); System.err.println(aNewBookCopy.getEmbodiments()); // but can be refreshed... aManager.refresh(aNewBookCopy); // and now contains the correct, up-to-date information System.err.println(aNewBookCopy.getTitle()); System.err.println(aNewBookCopy.getEmbodiments()); // now we can delete our new book aManager.remove(aNewBook); // false! System.err.println(aManager.contains(aNewBook)); // but the new manifestation still exists, since we did not specify that deletes should cascade... // true! System.err.println(aManager.contains(aPDFManifestation)); // Lastly, we can use the query API to run arbitrary sparql queries // create a jpql-style partial SPARQL query (JPQL is currently unsupported) Query aQuery = aManager.createQuery("where { ?result frbr:embodiment ?manifest." + " ?foo <http://purl.org/goodrelations/v1#typeOfGood> ?manifest . " + " ?foo <http://purl.org/goodrelations/v1#hasPriceSpecification> ?price. " + " ?price <http://purl.org/goodrelations/v1#hasCurrencyValue> ?value. " + " ?price <http://purl.org/goodrelations/v1#hasCurrency> \"USD\"@en." + " filter(?value > ??min). }"); // this query should return instances of type Book aQuery.setHint(RdfQuery.HINT_ENTITY_CLASS, Book.class); // set the parameter in the query to the value for the min price // parameters are prefixed with ?? aQuery.setParameter("min", 30); // now execute the query to get the list of all books which are $30 USD List aResults = aQuery.getResultList(); // 233 results System.err.println("Num Results: " + aResults.size()); // print the titles of the first five results for (int i = 0; i < 5; i++) { Book aBookResult = (Book) aResults.get(i); System.err.println(aBookResult.getTitle()); } /* * Switching to the Mac: The Missing Manual, Leopard Edition * O'Reilly Media / Pogue Press * true * Return of the Empire * [http://purl.oreilly.com/product-types/PDF] * true * How to use Empire * [http://purl.oreilly.com/product-types/EBOOK] * Return of the Empire * [http://purl.oreilly.com/product-types/PDF] * false * true * */ }
public static void main(String[] args) { // Alternatively you can use: -Dempire.configuration.file=examples/examples.empire.config.properties // if so, comment out this line. System.setProperty("empire.configuration.file", "examples/examples.empire.config.properties"); // loads Sesame bindings for Empire Empire.init(new OpenRdfEmpireModule()); // create an EntityManager for the specified persistence context EntityManager aManager = Persistence.createEntityManagerFactory("oreilly") .createEntityManager(); // this retrieves a particular book from the database Book aBook = aManager.find(Book.class, URI.create("urn:x-domain:oreilly.com:product:9780596514129.IP")); // prints: Switching to the Mac: The Missing Manual, Leopard Edition System.err.println(aBook.getTitle()); // prints: O'Reilly Media / Pogue Press System.err.println(aBook.getPublisher()); // creating a new book: Book aNewBook = new Book(); aNewBook.setIssued(new Date()); aNewBook.setTitle("How to use Empire"); aNewBook.setPublisher("Clark & Parsia"); aNewBook.setPrimarySubjectOf(URI.create("http://github.com/clarkparsia/Empire")); // grab the ebook manifestation Manifestation aEBook = aManager.find(Manifestation.class, URI.create("urn:x-domain:oreilly.com:product:9780596104306.EBOOK")); // and we'll use it as the embodiment of our new book. aNewBook.setEmbodiments(Arrays.asList(aEBook)); // save the new book to the database aManager.persist(aNewBook); Book aNewBookCopy = aManager.find(Book.class, aNewBook.getRdfId()); // true! System.err.println(aNewBook.equals(aNewBookCopy)); // lets edit our book... // maybe we changed the title and published as a PDF aNewBook.setTitle("Return of the Empire"); // create a new manifestation Manifestation aPDFManifestation = new Manifestation(); aPDFManifestation.setIssued(new Date()); // set the dc:type attribute aPDFManifestation.setType(URI.create("http://purl.oreilly.com/product-types/PDF")); aNewBook.setEmbodiments(Arrays.asList(aPDFManifestation)); // now save our edits aManager.merge(aNewBook); // print the new information we just saved System.err.println(aNewBook.getTitle()); System.err.println(aNewBook.getEmbodiments()); // and importantly, verify that the new manifestation was also saved due to the cascaded merge operation // specified in the Book class via the @OneToMany annotation // true! System.err.println(aManager.contains(aPDFManifestation)); // the copy of the book contains the old information System.err.println(aNewBookCopy.getTitle()); System.err.println(aNewBookCopy.getEmbodiments()); // but can be refreshed... aManager.refresh(aNewBookCopy); // and now contains the correct, up-to-date information System.err.println(aNewBookCopy.getTitle()); System.err.println(aNewBookCopy.getEmbodiments()); // now we can delete our new book aManager.remove(aNewBook); // false! System.err.println(aManager.contains(aNewBook)); // but the new manifestation still exists, since we did not specify that deletes should cascade... // true! System.err.println(aManager.contains(aPDFManifestation)); // Lastly, we can use the query API to run arbitrary sparql queries // create a jpql-style partial SPARQL query (JPQL is currently unsupported) Query aQuery = aManager.createQuery("where { ?result frbr:embodiment ?manifest." + " ?foo <http://purl.org/goodrelations/v1#typeOfGood> ?manifest . " + " ?foo <http://purl.org/goodrelations/v1#hasPriceSpecification> ?price. " + " ?price <http://purl.org/goodrelations/v1#hasCurrencyValue> ?value. " + " ?price <http://purl.org/goodrelations/v1#hasCurrency> \"USD\"@en." + " filter(?value > ??min). }"); // this query should return instances of type Book aQuery.setHint(RdfQuery.HINT_ENTITY_CLASS, Book.class); // set the parameter in the query to the value for the min price // parameters are prefixed with ?? aQuery.setParameter("min", 30); // now execute the query to get the list of all books which are $30 USD List aResults = aQuery.getResultList(); // 233 results System.err.println("Num Results: " + aResults.size()); // print the titles of the first five results for (int i = 0; i < 5; i++) { Book aBookResult = (Book) aResults.get(i); System.err.println(aBookResult.getTitle()); } /* * Switching to the Mac: The Missing Manual, Leopard Edition * O'Reilly Media / Pogue Press * true * Return of the Empire * [http://purl.oreilly.com/product-types/PDF] * true * How to use Empire * [http://purl.oreilly.com/product-types/EBOOK] * Return of the Empire * [http://purl.oreilly.com/product-types/PDF] * false * true * */ }
diff --git a/src/com/massivecraft/factions/task/AutoLeaveTask.java b/src/com/massivecraft/factions/task/AutoLeaveTask.java index 044f7f84..18c62cbf 100644 --- a/src/com/massivecraft/factions/task/AutoLeaveTask.java +++ b/src/com/massivecraft/factions/task/AutoLeaveTask.java @@ -1,24 +1,25 @@ package com.massivecraft.factions.task; import com.massivecraft.factions.ConfServer; import com.massivecraft.factions.FPlayerColl; import com.massivecraft.factions.Factions; public class AutoLeaveTask implements Runnable { double rate; public AutoLeaveTask() { this.rate = ConfServer.autoLeaveRoutineRunsEveryXMinutes; } public void run() { FPlayerColl.get().autoLeaveOnInactivityRoutine(); + // TODO: Make it a polling and non-tps-dependent system instead. // maybe setting has been changed? if so, restart task at new rate if (this.rate != ConfServer.autoLeaveRoutineRunsEveryXMinutes) Factions.get().startAutoLeaveTask(true); } }
true
true
public void run() { FPlayerColl.get().autoLeaveOnInactivityRoutine(); // maybe setting has been changed? if so, restart task at new rate if (this.rate != ConfServer.autoLeaveRoutineRunsEveryXMinutes) Factions.get().startAutoLeaveTask(true); }
public void run() { FPlayerColl.get().autoLeaveOnInactivityRoutine(); // TODO: Make it a polling and non-tps-dependent system instead. // maybe setting has been changed? if so, restart task at new rate if (this.rate != ConfServer.autoLeaveRoutineRunsEveryXMinutes) Factions.get().startAutoLeaveTask(true); }
diff --git a/src/budgetapp/util/Money.java b/src/budgetapp/util/Money.java index e234961..51d8b73 100644 --- a/src/budgetapp/util/Money.java +++ b/src/budgetapp/util/Money.java @@ -1,127 +1,127 @@ package budgetapp.util; /** * Money class. Instead of using doubles directly, this class is used to get more flexibility * @author Steen * */ public class Money { private double value; public static boolean after = true; private static String currency = "kr"; private static double exchangeRate = 1; public Money() { value = 0; } public Money(double x) { value = x; } public Money(Money m) { value = m.get(); } public static void setCurrency(String c) { currency = c; } public static String getCurrency() { return currency; } public static double getExchangeRate() { return exchangeRate; } public static void setExchangeRate(double val) { exchangeRate = val; } public void set(double val) { value = val; } public void set(Money val) { value = val.get(); } public double get() { return value; } public Money add(double x) { return new Money(this.value+x); } public Money add(Money x) { return new Money(this.value + x.get()); } public Money subtract(double x) { return new Money(this.value - x); } public Money subtract(Money x) { return new Money(this.value - x.get()); } public Money divide(double x) { if(x!=0) return new Money(this.value/x); else return new Money(); } public Money divide(Money x) { if(x.get()!=0) return new Money(this.value/x.get()); else return new Money(); } public Money multiply(double x) { return new Money(this.value*x); } public Money multiply(Money x) { return new Money(this.value*x.get()); } /** * Returns a string of the value with some formatting to get the minus sign * at the right place and not print out decimals where it's not needed */ public String toString() { - double values = value/exchangeRate; + double fixedValue = value/exchangeRate; if(after) { - if(frac(values)<0.01) - return String.format("%.0f "+currency,values); + if(frac(fixedValue)<0.01) + return String.format("%.0f "+currency,fixedValue); else - return String.format("%.2f "+currency,values); + return String.format("%.2f "+currency,fixedValue); } else { - if(frac(value)<0.01) - return (values<0.0 ? "-" : "") + String.format(currency+"%.0f ",Math.abs(values)); + if(frac(fixedValue)<0.01) + return (fixedValue<0.0 ? "-" : "") + String.format(currency+"%.0f ",Math.abs(fixedValue)); else - return (values<0.0 ? "-" : "") + String.format(currency + "%.2f",Math.abs(values)); + return (fixedValue<0.0 ? "-" : "") + String.format(currency + "%.2f",Math.abs(fixedValue)); } } double frac(double d) { return d-Math.floor(d); } }
false
true
public String toString() { double values = value/exchangeRate; if(after) { if(frac(values)<0.01) return String.format("%.0f "+currency,values); else return String.format("%.2f "+currency,values); } else { if(frac(value)<0.01) return (values<0.0 ? "-" : "") + String.format(currency+"%.0f ",Math.abs(values)); else return (values<0.0 ? "-" : "") + String.format(currency + "%.2f",Math.abs(values)); } }
public String toString() { double fixedValue = value/exchangeRate; if(after) { if(frac(fixedValue)<0.01) return String.format("%.0f "+currency,fixedValue); else return String.format("%.2f "+currency,fixedValue); } else { if(frac(fixedValue)<0.01) return (fixedValue<0.0 ? "-" : "") + String.format(currency+"%.0f ",Math.abs(fixedValue)); else return (fixedValue<0.0 ? "-" : "") + String.format(currency + "%.2f",Math.abs(fixedValue)); } }
diff --git a/bpvss/src/main/gui/GuiImpl.java b/bpvss/src/main/gui/GuiImpl.java index 002b4df..8c29b7e 100644 --- a/bpvss/src/main/gui/GuiImpl.java +++ b/bpvss/src/main/gui/GuiImpl.java @@ -1,393 +1,397 @@ package main.gui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.net.URL; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import main.algorithm.BPVSS; public class GuiImpl extends JFrame { private static final long serialVersionUID = -2301605985365458803L; private String pathSecret = ""; private String pathCover = ""; private String secret = ""; private String cover = ""; private String pathUnion1 = ""; private String union1 = ""; private String pathUnion2 = ""; private String union2 = ""; public GuiImpl() { menu(); init(); setTitle("BPVSS"); setSize(500, 400); setLocationRelativeTo(null); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { messageExit(); } }); setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); } public void init() { JPanel basic = new JPanel(); basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS)); add(basic); JPanel buttonPanel = new JPanel(new BorderLayout(0, 0)); JPanel participantPanel = new JPanel(new FlowLayout()); participantPanel.setBorder(BorderFactory .createEmptyBorder(0, 25, 0, 25)); JLabel label = new JLabel("Participantes"); label.setToolTipText("N�mero de participantes"); final JTextField input = new JTextField(); input.setPreferredSize(new Dimension(50, 20)); input.setEditable(true); final String[] algorithms = { "Algoritmo noise-like", "Algoritmo meaningful share" }; final JComboBox<String> comboBox = new JComboBox<String>(algorithms); comboBox.setSelectedIndex(-1); comboBox.setToolTipText("Algoritmo para ocultar la imagen"); comboBox.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 25)); JPanel startPanel = new JPanel(new FlowLayout()); startPanel.setBorder(BorderFactory.createEmptyBorder(35, 0, 0, 0)); JButton startButton = new JButton("Ejecutar"); JButton joinButton = new JButton("Unir shares"); startButton.setToolTipText("Ejecutar el algoritmo seleccionado"); joinButton.setToolTipText("Unir dos shares para obtener el descifrado"); joinButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpCover = file.getName(); if (checkFormat(tmpCover)) { pathUnion1 = file.getParent().replace("\\", "/") + "/"; union1 = file.getName(); System.out.println(pathUnion1); System.out.println(union1); JOptionPane .showMessageDialog(null, "Primera share a unir cargada correctamente.Cargue la segunda share."); } } returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpCover = file.getName(); if (checkFormat(tmpCover)) { pathUnion2 = file.getParent().replace("\\", "/") + "/"; union2 = file.getName(); System.out.println(pathUnion2); System.out.println(union2); JOptionPane.showMessageDialog(null, "Segunda share a unir cargada correctamente."); } } BPVSS bpvss = new BPVSS(pathUnion1, 3); bpvss.joinImages(pathUnion1 + union1, pathUnion2 + union2, "joinShare.png"); + JOptionPane.showMessageDialog(null, + "Uni�n de las shares correctamente. Resultado en " + + pathUnion1); } }); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (comboBox.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(null, "Elija uno de los dos algoritmos."); } else if (comboBox.getSelectedIndex() == 0) { if (pathSecret.equals("") || secret.equals("")) { JOptionPane .showMessageDialog(null, "Cargue la imagen secreta antes de ejecutar el algoritmo."); } else { try { algorithmNoiseLike(input); JOptionPane.showMessageDialog(null, "El resultado ha sido guardado en " + pathSecret); } catch (Exception e) { JOptionPane .showMessageDialog(null, "Por favor introduzca un n�mero v�lido mayor que 0"); } } } else { if (pathSecret.equals("") || secret.equals("")) { JOptionPane .showMessageDialog(null, "Cargue la imagen secreta antes de ejecutar el algoritmo."); } else if (pathCover.equals("") || cover.equals("")) { JOptionPane .showMessageDialog( null, "Cargue la imagen de fondo para cubrir la secreta antes de ejecutar el algoritmo."); } else { try { algorithmMeaningfulShares(input); JOptionPane.showMessageDialog(null, "El resultado ha sido guardado en " + pathSecret); } catch (Exception e) { JOptionPane .showMessageDialog(null, "Por favor introduzca un n�mero v�lido mayor que 0"); } } } } }); startPanel.add(joinButton); startPanel.add(startButton); JPanel textPanel = new JPanel(new BorderLayout()); - textPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 15, 25)); + textPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 0, 25)); JTextPane pane = new JTextPane(); pane.setContentType("text/html"); String text = "<b>Algoritmo BPVSS</b>" + "<p>Primero tiene que eligir el tipo de algoritmo que desea usar:<br>" + "<b>(1)Noise-like:</b> cargue la imagen secreta dirigi�ndose a Archivo > Cargar imagen secreta o pulsando Ctrl-S.<br>" + "<b>(2)Meaningful share:</b> cargue la imagen secreta de la forma anterior y la imagen de fondo dirigi�ndose a Archivo > Cargar imagen de fondo o pulsando Ctrl-F.</p> " - + "<p>Finalmente introduzca el n�mero de participantes y haga click en ejecutar.</p>"; + + "<p>Finalmente introduzca el n�mero de participantes y haga click en ejecutar." + + " \"Unir shares\" permite apilar dos shares para ver el secreto que esconden.</p>"; pane.setText(text); pane.setEditable(false); textPanel.add(pane); basic.add(textPanel); participantPanel.add(comboBox); participantPanel.add(label); participantPanel.add(input); startPanel.add(startButton); buttonPanel.add(participantPanel, BorderLayout.NORTH); buttonPanel.add(startPanel); basic.add(buttonPanel); } public void messageExit() { int confirmed = JOptionPane.showConfirmDialog(null, "�Est� seguro que desea salir?", "Salir", JOptionPane.YES_NO_OPTION); if (confirmed == JOptionPane.YES_OPTION) { dispose(); } } public void menu() { JMenuBar menuBar = new JMenuBar(); URL pathIcon = getClass().getResource("/resources/exit.jpg"); System.out.println(pathIcon); ImageIcon exitIcon = new ImageIcon(getClass().getResource( "/resources/exit.jpg")); ImageIcon loadSecret = new ImageIcon(getClass().getResource( "/resources/secret.jpg")); ImageIcon loadCover = new ImageIcon(getClass().getResource( "/resources/shield.jpg")); ImageIcon helpIcon = new ImageIcon(getClass().getResource( "/resources/help.jpg")); JMenu file = new JMenu("Archivo"); file.setMnemonic(KeyEvent.VK_A); JMenu help = new JMenu("Ayuda"); help.setMnemonic(KeyEvent.VK_H); JMenuItem aboutItem = new JMenuItem("Sobre nosotros...", helpIcon); aboutItem.setMnemonic(KeyEvent.VK_H); aboutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, ActionEvent.CTRL_MASK)); aboutItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JOptionPane.showMessageDialog(null, "Trabajo de Criptograf�a 5 curso 2012/2013\n" + "Autores:\n" + "Javier Herrera Copano\n" + "Carlos Mu�oz Rodr�guez\n" + "Luis Manuel Sayago L�pez\n"); } }); JMenuItem loadItem = new JMenuItem("Cargar imagen secreta", loadSecret); loadItem.setMnemonic(KeyEvent.VK_S); loadItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); loadItem.setToolTipText("Cargue la imagen secreta"); loadItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpSecret = file.getName(); if (checkFormat(tmpSecret)) { pathSecret = file.getParent().replace("\\", "/") + "/"; secret = file.getName(); System.out.println(pathSecret); System.out.println(secret); JOptionPane.showMessageDialog(null, "Imagen secreta cargada correctamente"); } } } }); JMenuItem loadCoverItem = new JMenuItem("Cargar imagen de fondo", loadCover); loadCoverItem.setMnemonic(KeyEvent.VK_F); loadCoverItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK)); loadCoverItem.setToolTipText("Cargue la imagen para cubrir la secreta"); loadCoverItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpCover = file.getName(); if (checkFormat(tmpCover)) { pathCover = file.getParent().replace("\\", "/") + "/"; cover = file.getName(); System.out.println(pathCover); System.out.println(cover); JOptionPane.showMessageDialog(null, "Imagen de fondo cargada correctamente."); } } } }); JMenuItem exitItem = new JMenuItem("Salir", exitIcon); exitItem.setMnemonic(KeyEvent.VK_E); exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK)); exitItem.setToolTipText("Salga de la aplicaci�n"); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { messageExit(); } }); file.add(loadItem); file.add(loadCoverItem); file.add(exitItem); help.add(aboutItem); menuBar.add(file); menuBar.add(help); setJMenuBar(menuBar); } public void algorithmNoiseLike(JTextField input) { Integer n = Integer.valueOf(input.getText()); if (n > 0) { BPVSS bpvss = new BPVSS(pathSecret, n); bpvss.noiselikeShares(secret); shares(bpvss, n); } else { throw new IllegalArgumentException(); } } public void algorithmMeaningfulShares(JTextField input) { Integer n = Integer.valueOf(input.getText()); if (n > 0) { BPVSS bpvss = new BPVSS(pathSecret, n); bpvss.meaningfulShares(secret, pathCover + cover); shares(bpvss, n); } else { throw new IllegalArgumentException(); } } public void shares(BPVSS bpvss, Integer n) { for (int i = 0; i < n - 1; i++) { if (i == 0) { bpvss.joinImages("share0.png", "share1.png", "join1.png"); } else { if (i == n - 2) { bpvss.joinImages("join" + i + ".png", "share" + (i + 1) + ".png", "res.png"); } else { bpvss.joinImages("join" + i + ".png", "share" + (i + 1) + ".png", "join" + (i + 1) + ".png"); } } } } public static Boolean checkFormat(String picture) { Boolean flag = picture.contains(".jpg") || picture.contains(".png") || picture.contains(".JPG") || picture.contains(".PNG") || picture.contains(".jpeg") || picture.contains(".JPEG"); if (!flag) { JOptionPane.showMessageDialog(null, "Por favor introduzca una imagen jpg o png."); } return flag; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { GuiImpl gui = new GuiImpl(); gui.setVisible(true); } }); } }
false
true
public void init() { JPanel basic = new JPanel(); basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS)); add(basic); JPanel buttonPanel = new JPanel(new BorderLayout(0, 0)); JPanel participantPanel = new JPanel(new FlowLayout()); participantPanel.setBorder(BorderFactory .createEmptyBorder(0, 25, 0, 25)); JLabel label = new JLabel("Participantes"); label.setToolTipText("N�mero de participantes"); final JTextField input = new JTextField(); input.setPreferredSize(new Dimension(50, 20)); input.setEditable(true); final String[] algorithms = { "Algoritmo noise-like", "Algoritmo meaningful share" }; final JComboBox<String> comboBox = new JComboBox<String>(algorithms); comboBox.setSelectedIndex(-1); comboBox.setToolTipText("Algoritmo para ocultar la imagen"); comboBox.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 25)); JPanel startPanel = new JPanel(new FlowLayout()); startPanel.setBorder(BorderFactory.createEmptyBorder(35, 0, 0, 0)); JButton startButton = new JButton("Ejecutar"); JButton joinButton = new JButton("Unir shares"); startButton.setToolTipText("Ejecutar el algoritmo seleccionado"); joinButton.setToolTipText("Unir dos shares para obtener el descifrado"); joinButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpCover = file.getName(); if (checkFormat(tmpCover)) { pathUnion1 = file.getParent().replace("\\", "/") + "/"; union1 = file.getName(); System.out.println(pathUnion1); System.out.println(union1); JOptionPane .showMessageDialog(null, "Primera share a unir cargada correctamente.Cargue la segunda share."); } } returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpCover = file.getName(); if (checkFormat(tmpCover)) { pathUnion2 = file.getParent().replace("\\", "/") + "/"; union2 = file.getName(); System.out.println(pathUnion2); System.out.println(union2); JOptionPane.showMessageDialog(null, "Segunda share a unir cargada correctamente."); } } BPVSS bpvss = new BPVSS(pathUnion1, 3); bpvss.joinImages(pathUnion1 + union1, pathUnion2 + union2, "joinShare.png"); } }); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (comboBox.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(null, "Elija uno de los dos algoritmos."); } else if (comboBox.getSelectedIndex() == 0) { if (pathSecret.equals("") || secret.equals("")) { JOptionPane .showMessageDialog(null, "Cargue la imagen secreta antes de ejecutar el algoritmo."); } else { try { algorithmNoiseLike(input); JOptionPane.showMessageDialog(null, "El resultado ha sido guardado en " + pathSecret); } catch (Exception e) { JOptionPane .showMessageDialog(null, "Por favor introduzca un n�mero v�lido mayor que 0"); } } } else { if (pathSecret.equals("") || secret.equals("")) { JOptionPane .showMessageDialog(null, "Cargue la imagen secreta antes de ejecutar el algoritmo."); } else if (pathCover.equals("") || cover.equals("")) { JOptionPane .showMessageDialog( null, "Cargue la imagen de fondo para cubrir la secreta antes de ejecutar el algoritmo."); } else { try { algorithmMeaningfulShares(input); JOptionPane.showMessageDialog(null, "El resultado ha sido guardado en " + pathSecret); } catch (Exception e) { JOptionPane .showMessageDialog(null, "Por favor introduzca un n�mero v�lido mayor que 0"); } } } } }); startPanel.add(joinButton); startPanel.add(startButton); JPanel textPanel = new JPanel(new BorderLayout()); textPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 15, 25)); JTextPane pane = new JTextPane(); pane.setContentType("text/html"); String text = "<b>Algoritmo BPVSS</b>" + "<p>Primero tiene que eligir el tipo de algoritmo que desea usar:<br>" + "<b>(1)Noise-like:</b> cargue la imagen secreta dirigi�ndose a Archivo > Cargar imagen secreta o pulsando Ctrl-S.<br>" + "<b>(2)Meaningful share:</b> cargue la imagen secreta de la forma anterior y la imagen de fondo dirigi�ndose a Archivo > Cargar imagen de fondo o pulsando Ctrl-F.</p> " + "<p>Finalmente introduzca el n�mero de participantes y haga click en ejecutar.</p>"; pane.setText(text); pane.setEditable(false); textPanel.add(pane); basic.add(textPanel); participantPanel.add(comboBox); participantPanel.add(label); participantPanel.add(input); startPanel.add(startButton); buttonPanel.add(participantPanel, BorderLayout.NORTH); buttonPanel.add(startPanel); basic.add(buttonPanel); }
public void init() { JPanel basic = new JPanel(); basic.setLayout(new BoxLayout(basic, BoxLayout.Y_AXIS)); add(basic); JPanel buttonPanel = new JPanel(new BorderLayout(0, 0)); JPanel participantPanel = new JPanel(new FlowLayout()); participantPanel.setBorder(BorderFactory .createEmptyBorder(0, 25, 0, 25)); JLabel label = new JLabel("Participantes"); label.setToolTipText("N�mero de participantes"); final JTextField input = new JTextField(); input.setPreferredSize(new Dimension(50, 20)); input.setEditable(true); final String[] algorithms = { "Algoritmo noise-like", "Algoritmo meaningful share" }; final JComboBox<String> comboBox = new JComboBox<String>(algorithms); comboBox.setSelectedIndex(-1); comboBox.setToolTipText("Algoritmo para ocultar la imagen"); comboBox.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 25)); JPanel startPanel = new JPanel(new FlowLayout()); startPanel.setBorder(BorderFactory.createEmptyBorder(35, 0, 0, 0)); JButton startButton = new JButton("Ejecutar"); JButton joinButton = new JButton("Unir shares"); startButton.setToolTipText("Ejecutar el algoritmo seleccionado"); joinButton.setToolTipText("Unir dos shares para obtener el descifrado"); joinButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpCover = file.getName(); if (checkFormat(tmpCover)) { pathUnion1 = file.getParent().replace("\\", "/") + "/"; union1 = file.getName(); System.out.println(pathUnion1); System.out.println(union1); JOptionPane .showMessageDialog(null, "Primera share a unir cargada correctamente.Cargue la segunda share."); } } returnVal = fc.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String tmpCover = file.getName(); if (checkFormat(tmpCover)) { pathUnion2 = file.getParent().replace("\\", "/") + "/"; union2 = file.getName(); System.out.println(pathUnion2); System.out.println(union2); JOptionPane.showMessageDialog(null, "Segunda share a unir cargada correctamente."); } } BPVSS bpvss = new BPVSS(pathUnion1, 3); bpvss.joinImages(pathUnion1 + union1, pathUnion2 + union2, "joinShare.png"); JOptionPane.showMessageDialog(null, "Uni�n de las shares correctamente. Resultado en " + pathUnion1); } }); startButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (comboBox.getSelectedIndex() == -1) { JOptionPane.showMessageDialog(null, "Elija uno de los dos algoritmos."); } else if (comboBox.getSelectedIndex() == 0) { if (pathSecret.equals("") || secret.equals("")) { JOptionPane .showMessageDialog(null, "Cargue la imagen secreta antes de ejecutar el algoritmo."); } else { try { algorithmNoiseLike(input); JOptionPane.showMessageDialog(null, "El resultado ha sido guardado en " + pathSecret); } catch (Exception e) { JOptionPane .showMessageDialog(null, "Por favor introduzca un n�mero v�lido mayor que 0"); } } } else { if (pathSecret.equals("") || secret.equals("")) { JOptionPane .showMessageDialog(null, "Cargue la imagen secreta antes de ejecutar el algoritmo."); } else if (pathCover.equals("") || cover.equals("")) { JOptionPane .showMessageDialog( null, "Cargue la imagen de fondo para cubrir la secreta antes de ejecutar el algoritmo."); } else { try { algorithmMeaningfulShares(input); JOptionPane.showMessageDialog(null, "El resultado ha sido guardado en " + pathSecret); } catch (Exception e) { JOptionPane .showMessageDialog(null, "Por favor introduzca un n�mero v�lido mayor que 0"); } } } } }); startPanel.add(joinButton); startPanel.add(startButton); JPanel textPanel = new JPanel(new BorderLayout()); textPanel.setBorder(BorderFactory.createEmptyBorder(15, 25, 0, 25)); JTextPane pane = new JTextPane(); pane.setContentType("text/html"); String text = "<b>Algoritmo BPVSS</b>" + "<p>Primero tiene que eligir el tipo de algoritmo que desea usar:<br>" + "<b>(1)Noise-like:</b> cargue la imagen secreta dirigi�ndose a Archivo > Cargar imagen secreta o pulsando Ctrl-S.<br>" + "<b>(2)Meaningful share:</b> cargue la imagen secreta de la forma anterior y la imagen de fondo dirigi�ndose a Archivo > Cargar imagen de fondo o pulsando Ctrl-F.</p> " + "<p>Finalmente introduzca el n�mero de participantes y haga click en ejecutar." + " \"Unir shares\" permite apilar dos shares para ver el secreto que esconden.</p>"; pane.setText(text); pane.setEditable(false); textPanel.add(pane); basic.add(textPanel); participantPanel.add(comboBox); participantPanel.add(label); participantPanel.add(input); startPanel.add(startButton); buttonPanel.add(participantPanel, BorderLayout.NORTH); buttonPanel.add(startPanel); basic.add(buttonPanel); }
diff --git a/src/com/ensifera/animosity/craftirc/RelayedMessage.java b/src/com/ensifera/animosity/craftirc/RelayedMessage.java index ca0e4e5..c943230 100644 --- a/src/com/ensifera/animosity/craftirc/RelayedMessage.java +++ b/src/com/ensifera/animosity/craftirc/RelayedMessage.java @@ -1,199 +1,199 @@ package com.ensifera.animosity.craftirc; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RelayedMessage { enum DeliveryMethod { STANDARD, ADMINS, COMMAND } static String typeString = "MSG"; private CraftIRC plugin; private EndPoint source; //Origin endpoint of the message private EndPoint target; //Target endpoint of the message private String eventType; //Event type private LinkedList<EndPoint> cc; //Multiple extra targets for the message private String template; //Formatting string private Map<String,String> fields; //All message attributes RelayedMessage(CraftIRC plugin, EndPoint source) { this(plugin, source, null, ""); } RelayedMessage(CraftIRC plugin, EndPoint source, EndPoint target) { this(plugin, source, target, ""); } RelayedMessage(CraftIRC plugin, EndPoint source, EndPoint target, String eventType) { this.plugin = plugin; this.source = source; this.target = target; if (eventType.equals("")) eventType = "generic"; this.eventType = eventType; this.template = "%message%"; if (eventType != null && eventType != "" && target != null) this.template = plugin.cFormatting(eventType, this); fields = new HashMap<String,String>(); } public CraftIRC getPlugin() { return this.plugin; } EndPoint getSource() { return source; } EndPoint getTarget() { return target; } public String getEvent() { return eventType; } public void setField(String key, String value) { fields.put(key, value); } public String getField(String key) { return fields.get(key); } public Set<String> setFields() { return fields.keySet(); } public void copyFields(RelayedMessage msg) { if (msg == null) return; for (String key : msg.setFields()) setField(key, msg.getField(key)); } public boolean addExtraTarget(EndPoint ep) { if (cc.contains(ep)) return false; cc.add(ep); return true; } public String getMessage() { return getMessage(null); } public String getMessage(EndPoint currentTarget) { String result = template; EndPoint realTarget; //Resolve target realTarget = target; if (realTarget == null) { if (currentTarget == null) return result; realTarget = currentTarget; result = plugin.cFormatting(eventType, this, realTarget); if (result == null) result = template; } //IRC color code aliases (actually not recommended) if (realTarget.getType() == EndPoint.Type.IRC) { result = result.replaceAll("%k([0-9]{1,2})%", Character.toString((char) 3) + "$1"); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", Character.toString((char) 3) + "$1,$2"); result = result.replace("%k%", Character.toString((char) 3)); result = result.replace("%o%", Character.toString((char) 15)); result = result.replace("%b%", Character.toString((char) 2)); result = result.replace("%u%", Character.toString((char) 31)); result = result.replace("%r%", Character.toString((char) 22)); } else if (realTarget.getType() == EndPoint.Type.MINECRAFT) { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", plugin.cColorGameFromName("foreground")); result = result.replace("%o%", plugin.cColorGameFromName("foreground")); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } else { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", ""); result = result.replace("%o%", ""); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } //Fields and named colors (all the important stuff is here actually) Pattern other_vars = Pattern.compile("%([A-Za-z0-9]+)%"); Matcher find_vars = other_vars.matcher(result); while (find_vars.find()) { if (fields.get(find_vars.group(1)) != null) result = find_vars.replaceFirst(Matcher.quoteReplacement(fields.get(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.IRC) result = find_vars.replaceFirst(Character.toString((char) 3) + String.format("%02d", this.plugin.cColorIrcFromName(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.MINECRAFT) result = find_vars.replaceFirst(this.plugin.cColorGameFromName(find_vars.group(1))); else result = find_vars.replaceFirst(""); find_vars = other_vars.matcher(result); } //Convert colors boolean colors = plugin.cPathAttribute(fields.get("source"), fields.get("target"), "attributes.colors"); if (source.getType() == EndPoint.Type.MINECRAFT) { if (realTarget.getType() == EndPoint.Type.IRC && colors) { - Pattern color_codes = Pattern.compile("\u00C2\u00A7([A-Fa-f0-9])?"); + Pattern color_codes = Pattern.compile("\u00A7([A-Fa-f0-9])?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { - result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00C2\u00A7" + find_colors.group(1)))); + result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00A7" + find_colors.group(1)))); find_colors = color_codes.matcher(result); } } else if (realTarget.getType() != EndPoint.Type.MINECRAFT || !colors) { //Strip colors - result = result.replaceAll("(\u00C2\u00A7([A-Fa-f0-9])?)", ""); + result = result.replaceAll("(\u00A7([A-Fa-f0-9])?)", ""); } } if (source.getType() == EndPoint.Type.IRC) { if (realTarget.getType() == EndPoint.Type.MINECRAFT && colors) { result = result.replaceAll("(" + Character.toString((char) 2) + "|" + Character.toString((char) 22) + "|" + Character.toString((char) 31) + ")", ""); Pattern color_codes = Pattern.compile(Character.toString((char) 3) + "([01]?[0-9])(,[0-9]{0,2})?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst(this.plugin.cColorGameFromIrc(Integer.parseInt(find_colors.group(1)))); find_colors = color_codes.matcher(result); } result = result.replaceAll(Character.toString((char) 15) + "|" + Character.toString((char) 3), this.plugin.cColorGameFromName("foreground")); } else if (realTarget.getType() != EndPoint.Type.IRC || !colors) { //Strip colors result = result.replaceAll( "(" + Character.toString((char) 2) + "|" + Character.toString((char) 15) + "|" + Character.toString((char) 22) + Character.toString((char) 31) + "|" + Character.toString((char) 3) + "[0-9]{0,2}(,[0-9]{0,2})?)", ""); } } return result; } public boolean post() { return post(DeliveryMethod.STANDARD, null); } public boolean post(boolean admin) { return post(admin ? DeliveryMethod.ADMINS : DeliveryMethod.STANDARD, null); } boolean post(DeliveryMethod dm, String username) { List<EndPoint> destinations; if (cc != null) destinations = new LinkedList<EndPoint>(cc); else destinations = new LinkedList<EndPoint>(); if (target != null) destinations.add(target); Collections.reverse(destinations); return plugin.delivery(this, destinations, username, dm); } public boolean postToUser(String username) { return post(DeliveryMethod.STANDARD, username); } public String toString() { String rep = "{" + eventType + " " + typeString + "}"; for(String key : fields.keySet()) rep = rep + " (" + key + ": " + fields.get(key) + ")"; return rep; } }
false
true
public String getMessage(EndPoint currentTarget) { String result = template; EndPoint realTarget; //Resolve target realTarget = target; if (realTarget == null) { if (currentTarget == null) return result; realTarget = currentTarget; result = plugin.cFormatting(eventType, this, realTarget); if (result == null) result = template; } //IRC color code aliases (actually not recommended) if (realTarget.getType() == EndPoint.Type.IRC) { result = result.replaceAll("%k([0-9]{1,2})%", Character.toString((char) 3) + "$1"); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", Character.toString((char) 3) + "$1,$2"); result = result.replace("%k%", Character.toString((char) 3)); result = result.replace("%o%", Character.toString((char) 15)); result = result.replace("%b%", Character.toString((char) 2)); result = result.replace("%u%", Character.toString((char) 31)); result = result.replace("%r%", Character.toString((char) 22)); } else if (realTarget.getType() == EndPoint.Type.MINECRAFT) { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", plugin.cColorGameFromName("foreground")); result = result.replace("%o%", plugin.cColorGameFromName("foreground")); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } else { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", ""); result = result.replace("%o%", ""); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } //Fields and named colors (all the important stuff is here actually) Pattern other_vars = Pattern.compile("%([A-Za-z0-9]+)%"); Matcher find_vars = other_vars.matcher(result); while (find_vars.find()) { if (fields.get(find_vars.group(1)) != null) result = find_vars.replaceFirst(Matcher.quoteReplacement(fields.get(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.IRC) result = find_vars.replaceFirst(Character.toString((char) 3) + String.format("%02d", this.plugin.cColorIrcFromName(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.MINECRAFT) result = find_vars.replaceFirst(this.plugin.cColorGameFromName(find_vars.group(1))); else result = find_vars.replaceFirst(""); find_vars = other_vars.matcher(result); } //Convert colors boolean colors = plugin.cPathAttribute(fields.get("source"), fields.get("target"), "attributes.colors"); if (source.getType() == EndPoint.Type.MINECRAFT) { if (realTarget.getType() == EndPoint.Type.IRC && colors) { Pattern color_codes = Pattern.compile("\u00C2\u00A7([A-Fa-f0-9])?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00C2\u00A7" + find_colors.group(1)))); find_colors = color_codes.matcher(result); } } else if (realTarget.getType() != EndPoint.Type.MINECRAFT || !colors) { //Strip colors result = result.replaceAll("(\u00C2\u00A7([A-Fa-f0-9])?)", ""); } } if (source.getType() == EndPoint.Type.IRC) { if (realTarget.getType() == EndPoint.Type.MINECRAFT && colors) { result = result.replaceAll("(" + Character.toString((char) 2) + "|" + Character.toString((char) 22) + "|" + Character.toString((char) 31) + ")", ""); Pattern color_codes = Pattern.compile(Character.toString((char) 3) + "([01]?[0-9])(,[0-9]{0,2})?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst(this.plugin.cColorGameFromIrc(Integer.parseInt(find_colors.group(1)))); find_colors = color_codes.matcher(result); } result = result.replaceAll(Character.toString((char) 15) + "|" + Character.toString((char) 3), this.plugin.cColorGameFromName("foreground")); } else if (realTarget.getType() != EndPoint.Type.IRC || !colors) { //Strip colors result = result.replaceAll( "(" + Character.toString((char) 2) + "|" + Character.toString((char) 15) + "|" + Character.toString((char) 22) + Character.toString((char) 31) + "|" + Character.toString((char) 3) + "[0-9]{0,2}(,[0-9]{0,2})?)", ""); } } return result; }
public String getMessage(EndPoint currentTarget) { String result = template; EndPoint realTarget; //Resolve target realTarget = target; if (realTarget == null) { if (currentTarget == null) return result; realTarget = currentTarget; result = plugin.cFormatting(eventType, this, realTarget); if (result == null) result = template; } //IRC color code aliases (actually not recommended) if (realTarget.getType() == EndPoint.Type.IRC) { result = result.replaceAll("%k([0-9]{1,2})%", Character.toString((char) 3) + "$1"); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", Character.toString((char) 3) + "$1,$2"); result = result.replace("%k%", Character.toString((char) 3)); result = result.replace("%o%", Character.toString((char) 15)); result = result.replace("%b%", Character.toString((char) 2)); result = result.replace("%u%", Character.toString((char) 31)); result = result.replace("%r%", Character.toString((char) 22)); } else if (realTarget.getType() == EndPoint.Type.MINECRAFT) { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", plugin.cColorGameFromName("foreground")); result = result.replace("%o%", plugin.cColorGameFromName("foreground")); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } else { result = result.replaceAll("%k([0-9]{1,2})%", ""); result = result.replaceAll("%k([0-9]{1,2}),([0-9]{1,2})%", ""); result = result.replace("%k%", ""); result = result.replace("%o%", ""); result = result.replace("%b%", ""); result = result.replace("%u%", ""); result = result.replace("%r%", ""); } //Fields and named colors (all the important stuff is here actually) Pattern other_vars = Pattern.compile("%([A-Za-z0-9]+)%"); Matcher find_vars = other_vars.matcher(result); while (find_vars.find()) { if (fields.get(find_vars.group(1)) != null) result = find_vars.replaceFirst(Matcher.quoteReplacement(fields.get(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.IRC) result = find_vars.replaceFirst(Character.toString((char) 3) + String.format("%02d", this.plugin.cColorIrcFromName(find_vars.group(1)))); else if (realTarget.getType() == EndPoint.Type.MINECRAFT) result = find_vars.replaceFirst(this.plugin.cColorGameFromName(find_vars.group(1))); else result = find_vars.replaceFirst(""); find_vars = other_vars.matcher(result); } //Convert colors boolean colors = plugin.cPathAttribute(fields.get("source"), fields.get("target"), "attributes.colors"); if (source.getType() == EndPoint.Type.MINECRAFT) { if (realTarget.getType() == EndPoint.Type.IRC && colors) { Pattern color_codes = Pattern.compile("\u00A7([A-Fa-f0-9])?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst("\u0003" + Integer.toString(this.plugin.cColorIrcFromGame("\u00A7" + find_colors.group(1)))); find_colors = color_codes.matcher(result); } } else if (realTarget.getType() != EndPoint.Type.MINECRAFT || !colors) { //Strip colors result = result.replaceAll("(\u00A7([A-Fa-f0-9])?)", ""); } } if (source.getType() == EndPoint.Type.IRC) { if (realTarget.getType() == EndPoint.Type.MINECRAFT && colors) { result = result.replaceAll("(" + Character.toString((char) 2) + "|" + Character.toString((char) 22) + "|" + Character.toString((char) 31) + ")", ""); Pattern color_codes = Pattern.compile(Character.toString((char) 3) + "([01]?[0-9])(,[0-9]{0,2})?"); Matcher find_colors = color_codes.matcher(result); while (find_colors.find()) { result = find_colors.replaceFirst(this.plugin.cColorGameFromIrc(Integer.parseInt(find_colors.group(1)))); find_colors = color_codes.matcher(result); } result = result.replaceAll(Character.toString((char) 15) + "|" + Character.toString((char) 3), this.plugin.cColorGameFromName("foreground")); } else if (realTarget.getType() != EndPoint.Type.IRC || !colors) { //Strip colors result = result.replaceAll( "(" + Character.toString((char) 2) + "|" + Character.toString((char) 15) + "|" + Character.toString((char) 22) + Character.toString((char) 31) + "|" + Character.toString((char) 3) + "[0-9]{0,2}(,[0-9]{0,2})?)", ""); } } return result; }
diff --git a/src/ch/almana/android/stechkarte/view/ListDays.java b/src/ch/almana/android/stechkarte/view/ListDays.java index 7aa4778..03d34c3 100644 --- a/src/ch/almana/android/stechkarte/view/ListDays.java +++ b/src/ch/almana/android/stechkarte/view/ListDays.java @@ -1,209 +1,211 @@ package ch.almana.android.stechkarte.view; import android.app.ListActivity; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.SimpleCursorAdapter.ViewBinder; import android.widget.TextView; import ch.almana.android.stechkarte.R; import ch.almana.android.stechkarte.log.Logger; import ch.almana.android.stechkarte.model.Day; import ch.almana.android.stechkarte.provider.db.DB; import ch.almana.android.stechkarte.provider.db.DB.Days; import ch.almana.android.stechkarte.provider.db.DB.Timestamps; import ch.almana.android.stechkarte.utils.DeleteDayDialog; import ch.almana.android.stechkarte.utils.DialogCallback; import ch.almana.android.stechkarte.utils.Formater; import ch.almana.android.stechkarte.utils.RebuildDaysTask; public class ListDays extends ListActivity implements DialogCallback { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); setTitle(R.string.daysListTitle); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(Days.CONTENT_URI); } Cursor cursor = managedQuery(DB.Days.CONTENT_URI, DB.Days.DEFAULT_PROJECTION, null, null, Days.DEFAULT_SORTORDER); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.daylist_item, cursor, new String[] { DB.NAME_ID, DB.Days.NAME_DAYREF, DB.Days.NAME_HOURS_WORKED, DB.Days.NAME_OVERTIME, DB.Days.NAME_HOURS_TARGET, DB.Days.NAME_HOLIDAY, DB.Days.NAME_HOLIDAY_LEFT, DB.Days.NAME_FIXED }, new int[] { R.id.TextViewDayRef, R.id.TextViewDayRef, R.id.TextViewHoursWorked, R.id.TextViewOvertime, R.id.TextViewHoursTarget, R.id.TextViewHoliday, R.id.TextViewHolidaysLeft, R.id.ImageViewLock }); adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (cursor == null) { return false; } if (columnIndex == DB.Days.INDEX_DAYREF) { Day d = new Day(cursor); int color = Color.GREEN; if (d.isError()) { color = Color.RED; } TextView errorView = (TextView) view.findViewById(R.id.TextViewDayRef); errorView.setTextColor(color); // since we do not set the dayref no: return true; } else if (columnIndex == DB.Days.INDEX_OVERTIME) { Day d = new Day(cursor); CharSequence formatHourMinFromHours = Formater.formatHourMinFromHours(d.getOvertime()); ((TextView) view.findViewById(R.id.TextViewOvertime)).setText(formatHourMinFromHours); TextView tv = (TextView) ((View) view.getParent()).findViewById(R.id.TextViewOvertimeCur); float overtime = d.getHoursWorked() - d.getHoursTarget(); tv.setText(Formater.formatHourMinFromHours(overtime)); + tv.setTextColor(Color.LTGRAY); if (overtime > 5) { tv.setTextColor(Color.RED); } else if (overtime > 3) { tv.setTextColor(Color.YELLOW); } return true; } else if (columnIndex == DB.Days.INDEX_HOURS_WORKED) { float hoursWorked = cursor.getFloat(Days.INDEX_HOURS_WORKED); TextView tv = (TextView) view.findViewById(R.id.TextViewHoursWorked); tv.setText(Formater.formatHourMinFromHours(hoursWorked)); - if (hoursWorked > 15) { + tv.setTextColor(Color.LTGRAY); + if (hoursWorked > 12) { tv.setTextColor(Color.RED); - } else if (hoursWorked > 12) { + } else if (hoursWorked > 10) { tv.setTextColor(Color.YELLOW); } return true; } else if (columnIndex == DB.Days.INDEX_HOURS_TARGET) { Day d = new Day(cursor); ((TextView) view.findViewById(R.id.TextViewHoursTarget)).setText(Formater.formatHourMinFromHours(d.getHoursTarget())); return true; } else if (columnIndex == DB.Days.INDEX_FIXED) { ImageView iv = (ImageView) view.findViewById(R.id.ImageViewLock); if (cursor.getInt(Days.INDEX_FIXED) > 0) { iv.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_lock_lock)); } else { iv.setImageBitmap(null); } return true; } return false; } }); setListAdapter(adapter); getListView().setOnCreateContextMenuListener(this); // dia.dismiss(); } @Override protected void onResume() { RebuildDaysTask.rebuildDaysIfNeeded(this); super.onResume(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.daylist_option, menu); // menu.getItem(0).setEnabled(!RebuildDaysTask.isRebuilding()); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.itemDaylistRebuild: rebuildDays(); break; case R.id.itemDaylistInsertDay: startActivity(new Intent(Intent.ACTION_INSERT, Days.CONTENT_URI)); break; case R.id.itemDaylistInsertTImestamp: startActivity(new Intent(Intent.ACTION_INSERT, Timestamps.CONTENT_URI)); break; default: return super.onOptionsItemSelected(item); } return true; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Uri uri = ContentUris.withAppendedId(getIntent().getData(), id); String action = getIntent().getAction(); if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) { setResult(RESULT_OK, new Intent().setData(uri)); } else { startActivity(new Intent(Intent.ACTION_EDIT, uri)); } } private void rebuildDays() { RebuildDaysTask.rebuildDays(this, null); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); getMenuInflater().inflate(R.menu.daylist_context, menu); } @Override public boolean onContextItemSelected(MenuItem item) { super.onContextItemSelected(item); AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(Logger.LOG_TAG, "bad menuInfo", e); return false; } // Uri uri = ContentUris.withAppendedId(Days.CONTENT_URI, info.id); switch (item.getItemId()) { case R.id.itemDeleteDay: { DeleteDayDialog alert = new DeleteDayDialog(this, info.id); alert.setTitle("Delete Day..."); alert.show(); return true; } } return false; } @Override public void finished(boolean success) { // TODO Auto-generated method stub } @Override public Context getContext() { return this; } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); setTitle(R.string.daysListTitle); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(Days.CONTENT_URI); } Cursor cursor = managedQuery(DB.Days.CONTENT_URI, DB.Days.DEFAULT_PROJECTION, null, null, Days.DEFAULT_SORTORDER); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.daylist_item, cursor, new String[] { DB.NAME_ID, DB.Days.NAME_DAYREF, DB.Days.NAME_HOURS_WORKED, DB.Days.NAME_OVERTIME, DB.Days.NAME_HOURS_TARGET, DB.Days.NAME_HOLIDAY, DB.Days.NAME_HOLIDAY_LEFT, DB.Days.NAME_FIXED }, new int[] { R.id.TextViewDayRef, R.id.TextViewDayRef, R.id.TextViewHoursWorked, R.id.TextViewOvertime, R.id.TextViewHoursTarget, R.id.TextViewHoliday, R.id.TextViewHolidaysLeft, R.id.ImageViewLock }); adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (cursor == null) { return false; } if (columnIndex == DB.Days.INDEX_DAYREF) { Day d = new Day(cursor); int color = Color.GREEN; if (d.isError()) { color = Color.RED; } TextView errorView = (TextView) view.findViewById(R.id.TextViewDayRef); errorView.setTextColor(color); // since we do not set the dayref no: return true; } else if (columnIndex == DB.Days.INDEX_OVERTIME) { Day d = new Day(cursor); CharSequence formatHourMinFromHours = Formater.formatHourMinFromHours(d.getOvertime()); ((TextView) view.findViewById(R.id.TextViewOvertime)).setText(formatHourMinFromHours); TextView tv = (TextView) ((View) view.getParent()).findViewById(R.id.TextViewOvertimeCur); float overtime = d.getHoursWorked() - d.getHoursTarget(); tv.setText(Formater.formatHourMinFromHours(overtime)); if (overtime > 5) { tv.setTextColor(Color.RED); } else if (overtime > 3) { tv.setTextColor(Color.YELLOW); } return true; } else if (columnIndex == DB.Days.INDEX_HOURS_WORKED) { float hoursWorked = cursor.getFloat(Days.INDEX_HOURS_WORKED); TextView tv = (TextView) view.findViewById(R.id.TextViewHoursWorked); tv.setText(Formater.formatHourMinFromHours(hoursWorked)); if (hoursWorked > 15) { tv.setTextColor(Color.RED); } else if (hoursWorked > 12) { tv.setTextColor(Color.YELLOW); } return true; } else if (columnIndex == DB.Days.INDEX_HOURS_TARGET) { Day d = new Day(cursor); ((TextView) view.findViewById(R.id.TextViewHoursTarget)).setText(Formater.formatHourMinFromHours(d.getHoursTarget())); return true; } else if (columnIndex == DB.Days.INDEX_FIXED) { ImageView iv = (ImageView) view.findViewById(R.id.ImageViewLock); if (cursor.getInt(Days.INDEX_FIXED) > 0) { iv.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_lock_lock)); } else { iv.setImageBitmap(null); } return true; } return false; } }); setListAdapter(adapter); getListView().setOnCreateContextMenuListener(this); // dia.dismiss(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); setTitle(R.string.daysListTitle); Intent intent = getIntent(); if (intent.getData() == null) { intent.setData(Days.CONTENT_URI); } Cursor cursor = managedQuery(DB.Days.CONTENT_URI, DB.Days.DEFAULT_PROJECTION, null, null, Days.DEFAULT_SORTORDER); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.daylist_item, cursor, new String[] { DB.NAME_ID, DB.Days.NAME_DAYREF, DB.Days.NAME_HOURS_WORKED, DB.Days.NAME_OVERTIME, DB.Days.NAME_HOURS_TARGET, DB.Days.NAME_HOLIDAY, DB.Days.NAME_HOLIDAY_LEFT, DB.Days.NAME_FIXED }, new int[] { R.id.TextViewDayRef, R.id.TextViewDayRef, R.id.TextViewHoursWorked, R.id.TextViewOvertime, R.id.TextViewHoursTarget, R.id.TextViewHoliday, R.id.TextViewHolidaysLeft, R.id.ImageViewLock }); adapter.setViewBinder(new ViewBinder() { @Override public boolean setViewValue(View view, Cursor cursor, int columnIndex) { if (cursor == null) { return false; } if (columnIndex == DB.Days.INDEX_DAYREF) { Day d = new Day(cursor); int color = Color.GREEN; if (d.isError()) { color = Color.RED; } TextView errorView = (TextView) view.findViewById(R.id.TextViewDayRef); errorView.setTextColor(color); // since we do not set the dayref no: return true; } else if (columnIndex == DB.Days.INDEX_OVERTIME) { Day d = new Day(cursor); CharSequence formatHourMinFromHours = Formater.formatHourMinFromHours(d.getOvertime()); ((TextView) view.findViewById(R.id.TextViewOvertime)).setText(formatHourMinFromHours); TextView tv = (TextView) ((View) view.getParent()).findViewById(R.id.TextViewOvertimeCur); float overtime = d.getHoursWorked() - d.getHoursTarget(); tv.setText(Formater.formatHourMinFromHours(overtime)); tv.setTextColor(Color.LTGRAY); if (overtime > 5) { tv.setTextColor(Color.RED); } else if (overtime > 3) { tv.setTextColor(Color.YELLOW); } return true; } else if (columnIndex == DB.Days.INDEX_HOURS_WORKED) { float hoursWorked = cursor.getFloat(Days.INDEX_HOURS_WORKED); TextView tv = (TextView) view.findViewById(R.id.TextViewHoursWorked); tv.setText(Formater.formatHourMinFromHours(hoursWorked)); tv.setTextColor(Color.LTGRAY); if (hoursWorked > 12) { tv.setTextColor(Color.RED); } else if (hoursWorked > 10) { tv.setTextColor(Color.YELLOW); } return true; } else if (columnIndex == DB.Days.INDEX_HOURS_TARGET) { Day d = new Day(cursor); ((TextView) view.findViewById(R.id.TextViewHoursTarget)).setText(Formater.formatHourMinFromHours(d.getHoursTarget())); return true; } else if (columnIndex == DB.Days.INDEX_FIXED) { ImageView iv = (ImageView) view.findViewById(R.id.ImageViewLock); if (cursor.getInt(Days.INDEX_FIXED) > 0) { iv.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_lock_lock)); } else { iv.setImageBitmap(null); } return true; } return false; } }); setListAdapter(adapter); getListView().setOnCreateContextMenuListener(this); // dia.dismiss(); }
diff --git a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/MauerEditor.java b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/MauerEditor.java index b35d2e7b..9f331830 100644 --- a/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/MauerEditor.java +++ b/src/main/java/de/cismet/cids/custom/objecteditors/wunda_blau/MauerEditor.java @@ -1,4222 +1,4222 @@ /*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.cismet.cids.custom.objecteditors.wunda_blau; import Sirius.navigator.connection.SessionManager; import Sirius.navigator.exception.ConnectionException; import Sirius.navigator.ui.RequestsFullSizeComponent; import Sirius.server.middleware.types.MetaClass; import Sirius.server.middleware.types.MetaObject; import com.vividsolutions.jts.geom.Geometry; import edu.umd.cs.piccolo.event.PBasicInputEventHandler; import edu.umd.cs.piccolo.event.PInputEvent; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import org.jdesktop.swingx.JXErrorPane; import org.jdesktop.swingx.error.ErrorInfo; import org.openide.util.Exceptions; import org.openide.util.NbBundle; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Image; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.regex.Pattern; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.event.IIOReadProgressListener; import javax.imageio.stream.ImageInputStream; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.ProgressMonitor; import javax.swing.SwingWorker; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.filechooser.FileFilter; import de.cismet.cids.client.tools.DevelopmentTools; import de.cismet.cids.custom.objecteditors.utils.DoubleNumberConverter; import de.cismet.cids.custom.objecteditors.utils.NumberConverter; import de.cismet.cids.custom.objecteditors.utils.RendererTools; import de.cismet.cids.custom.objecteditors.utils.WebDavHelper; import de.cismet.cids.custom.objectrenderer.utils.CidsBeanSupport; import de.cismet.cids.custom.objectrenderer.utils.ObjectRendererUtils; import de.cismet.cids.custom.reports.wunda_blau.MauernReportGenerator; import de.cismet.cids.custom.utils.alkis.AlkisConstants; import de.cismet.cids.custom.wunda_blau.search.server.MauerNummerSearch; import de.cismet.cids.dynamics.CidsBean; import de.cismet.cids.editors.DefaultCustomObjectEditor; import de.cismet.cids.editors.EditorClosedEvent; import de.cismet.cids.editors.EditorSaveListener; import de.cismet.cids.editors.EditorSaveListener.EditorSaveStatus; import de.cismet.cids.navigator.utils.ClassCacheMultiple; import de.cismet.cids.server.search.CidsServerSearch; import de.cismet.cids.tools.metaobjectrenderer.CidsBeanRenderer; import de.cismet.cismap.cids.geometryeditor.DefaultCismapGeometryComboBoxEditor; import de.cismet.cismap.commons.CrsTransformer; import de.cismet.cismap.commons.XBoundingBox; import de.cismet.cismap.commons.features.DefaultStyledFeature; import de.cismet.cismap.commons.features.StyledFeature; import de.cismet.cismap.commons.gui.MappingComponent; import de.cismet.cismap.commons.gui.layerwidget.ActiveLayerModel; import de.cismet.cismap.commons.raster.wms.simple.SimpleWMS; import de.cismet.cismap.commons.raster.wms.simple.SimpleWmsGetMapUrl; import de.cismet.netutil.Proxy; import de.cismet.tools.CismetThreadPool; import de.cismet.tools.PasswordEncrypter; import de.cismet.tools.gui.BorderProvider; import de.cismet.tools.gui.FooterComponentProvider; import de.cismet.tools.gui.StaticSwingTools; import de.cismet.tools.gui.TitleComponentProvider; /** * DOCUMENT ME! * * @author daniel * @version $Revision$, $Date$ */ public class MauerEditor extends javax.swing.JPanel implements RequestsFullSizeComponent, CidsBeanRenderer, EditorSaveListener, FooterComponentProvider, TitleComponentProvider, BorderProvider { //~ Static fields/initializers --------------------------------------------- private static final ImageIcon ERROR_ICON = new ImageIcon(MauerEditor.class.getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/file-broken.png")); private static final String WEB_DAV_DIRECTORY; private static final String WEB_DAV_USER; private static final String WEB_DAV_PASSWORD; private static final String FILE_PREFIX = "FOTO-"; private static final int CACHE_SIZE = 20; private static final Map<String, SoftReference<BufferedImage>> IMAGE_CACHE = new LinkedHashMap<String, SoftReference<BufferedImage>>(CACHE_SIZE) { @Override protected boolean removeEldestEntry(final Map.Entry<String, SoftReference<BufferedImage>> eldest) { return size() >= CACHE_SIZE; } }; private static final ImageIcon FOLDER_ICON = new ImageIcon(MauerEditor.class.getResource( "/de/cismet/cids/custom/objecteditors/wunda_blau/inode-directory.png")); private static final Pattern IMAGE_FILE_PATTERN = Pattern.compile( ".*\\.(bmp|png|jpg|jpeg|tif|tiff|wbmp)$", Pattern.CASE_INSENSITIVE); static { final ResourceBundle bundle = ResourceBundle.getBundle("WebDav"); String pass = bundle.getString("password"); if ((pass != null) && pass.startsWith(PasswordEncrypter.CRYPT_PREFIX)) { pass = PasswordEncrypter.decryptString(pass); } WEB_DAV_PASSWORD = pass; WEB_DAV_USER = bundle.getString("user"); WEB_DAV_DIRECTORY = bundle.getString("url"); } //~ Instance fields -------------------------------------------------------- private CidsBean cidsBean; private String title; private final Logger log = Logger.getLogger(MauerEditor.class); private MappingComponent map; private boolean editable; private CardLayout cardLayout; private CidsBean fotoCidsBean; private final PropertyChangeListener listRepaintListener; private BufferedImage image; private final Timer timer; private ImageResizeWorker currentResizeWorker; private boolean resizeListenerEnabled; private final WebDavHelper webDavHelper; private final JFileChooser fileChooser; private final List<CidsBean> removedFotoBeans = new ArrayList<CidsBean>(); private final List<CidsBean> removeNewAddedFotoBean = new ArrayList<CidsBean>(); private boolean listListenerEnabled; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAddImg; private javax.swing.JButton btnImages; private javax.swing.JButton btnInfo; private javax.swing.JButton btnNextImg; private javax.swing.JButton btnPrevImg; private javax.swing.JButton btnRemoveImg; private javax.swing.JButton btnReport; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbArtErstePruefung; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbArtLetztePruefung; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbArtNaechstePruefung1; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbDauerhaftigkeit; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbEigentuemer; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbEingriffAnsicht; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbEingriffGelaende; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbEingriffGelaender; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbEingriffGruendung; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbEingriffKopf; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbEingriffVerformung; private javax.swing.JComboBox cbGeom; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbLastklasse; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbMaterialtyp; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbMauertyp; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbStandsicherheit; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbStuetzmauertyp; private de.cismet.cids.editors.DefaultBindableReferenceCombo cbVerkehrssicherheit; private de.cismet.cids.editors.DefaultBindableDateChooser dcBauwerksbuchfertigstellung; private de.cismet.cids.editors.DefaultBindableDateChooser dcErstePruefung; private de.cismet.cids.editors.DefaultBindableDateChooser dcLetztePruefung; private de.cismet.cids.editors.DefaultBindableDateChooser dcNaechstePruefung; private de.cismet.cids.editors.DefaultBindableReferenceCombo dcSanierung; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane10; private javax.swing.JScrollPane jScrollPane11; private javax.swing.JScrollPane jScrollPane12; private javax.swing.JScrollPane jScrollPane13; private javax.swing.JScrollPane jScrollPane14; private javax.swing.JScrollPane jScrollPane15; private javax.swing.JScrollPane jScrollPane17; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; private javax.swing.JScrollPane jScrollPane5; private javax.swing.JScrollPane jScrollPane6; private javax.swing.JScrollPane jScrollPane7; private javax.swing.JScrollPane jScrollPane8; private javax.swing.JScrollPane jScrollPane9; private javax.swing.JScrollPane jspAllgemeineInfos; private javax.swing.JScrollPane jspFotoList; private javax.swing.JLabel lblBauwerksbuchfertigstellung; private javax.swing.JLabel lblBeschreibungGelaender; private javax.swing.JLabel lblBesonderheiten; private org.jdesktop.swingx.JXBusyLabel lblBusy; private javax.swing.JLabel lblDauerhaftigkeit; private javax.swing.JLabel lblEigentuemer; private javax.swing.JLabel lblEingriffAnsicht; private javax.swing.JLabel lblEingriffAnsicht1; private javax.swing.JLabel lblEingriffAnsicht2; private javax.swing.JLabel lblEingriffAnsicht3; private javax.swing.JLabel lblEingriffGeleander; private javax.swing.JLabel lblEingriffKopf; private javax.swing.JLabel lblFiller; private javax.swing.JLabel lblFiller1; private javax.swing.JLabel lblFiller10; private javax.swing.JLabel lblFiller11; private javax.swing.JLabel lblFiller3; private javax.swing.JLabel lblFiller4; private javax.swing.JLabel lblFiller5; private javax.swing.JLabel lblFiller6; private javax.swing.JLabel lblFiller7; private javax.swing.JLabel lblFiller8; private javax.swing.JLabel lblFiller9; private javax.swing.JLabel lblFotos; private javax.swing.JLabel lblGelaenderHeader; private javax.swing.JLabel lblGeom; private javax.swing.JLabel lblHeaderAllgemein; private javax.swing.JLabel lblHeaderFotos; private javax.swing.JLabel lblHoeheMin; private javax.swing.JLabel lblImages; private javax.swing.JLabel lblInfo; private javax.swing.JLabel lblKofpAnsicht; private javax.swing.JLabel lblKofpAnsicht1; private javax.swing.JLabel lblKofpAnsicht2; private javax.swing.JLabel lblKofpAnsicht3; private javax.swing.JLabel lblKofpHeader; private javax.swing.JLabel lblLaenge; private javax.swing.JLabel lblLagebeschreibung; private javax.swing.JLabel lblLagebezeichnung; private javax.swing.JLabel lblLastabstand; private javax.swing.JLabel lblLastklasse; private javax.swing.JLabel lblLetztePruefung; private javax.swing.JLabel lblMaterialTyp; private javax.swing.JLabel lblMauerNummer; private javax.swing.JLabel lblMauertyp; private javax.swing.JLabel lblNaechstePruefung; private javax.swing.JLabel lblNeigung; private javax.swing.JLabel lblPicture; private javax.swing.JLabel lblPruefung1; private javax.swing.JLabel lblSanKostenAnsicht; private javax.swing.JLabel lblSanKostenAnsicht1; private javax.swing.JLabel lblSanKostenAnsicht2; private javax.swing.JLabel lblSanKostenAnsicht3; private javax.swing.JLabel lblSanKostenGelaender; private javax.swing.JLabel lblSanKostenKopf; private javax.swing.JLabel lblSanMassnahmenAnsicht; private javax.swing.JLabel lblSanMassnahmenGelaender; private javax.swing.JLabel lblSanMassnahmenGruendung; private javax.swing.JLabel lblSanMassnahmenGruendung1; private javax.swing.JLabel lblSanMassnahmenGruendung2; private javax.swing.JLabel lblSanMassnahmenKopf; private javax.swing.JLabel lblSanierung; private javax.swing.JLabel lblStaerke; private javax.swing.JLabel lblStaerkeOben; private javax.swing.JLabel lblStaerkeUnten; private javax.swing.JLabel lblStandsicherheit; private javax.swing.JLabel lblStuetzmauer; private javax.swing.JLabel lblTitle; private javax.swing.JLabel lblUmgebung; private javax.swing.JLabel lblVerkehrssicherheit; private javax.swing.JLabel lblVorschau; private javax.swing.JLabel lblZustandAnsicht; private javax.swing.JLabel lblZustandGelaender; private javax.swing.JLabel lblZustandGesamt; private javax.swing.JLabel lblZustandGruendung; private javax.swing.JLabel lblZustandGruendung1; private javax.swing.JLabel lblZustandGruendung2; private javax.swing.JLabel lblZustandKopf; private javax.swing.JLabel lblbeschreibungAnsicht; private javax.swing.JLabel lblbeschreibungGruendung; private javax.swing.JLabel lblbeschreibungGruendung1; private javax.swing.JLabel lblbeschreibungGruendung2; private javax.swing.JLabel lblbeschreibungKopf; private javax.swing.JList lstFotos; private javax.swing.JPanel panFooter; private javax.swing.JPanel panLeft; private javax.swing.JPanel panRight; private javax.swing.JPanel panTitle; private de.cismet.tools.gui.RoundedPanel pnlAllgemein; private de.cismet.tools.gui.RoundedPanel pnlAnsicht; private javax.swing.JPanel pnlCard1; private javax.swing.JPanel pnlCard2; private javax.swing.JPanel pnlCtrlBtn; private javax.swing.JPanel pnlCtrlButtons; private javax.swing.JPanel pnlFoto; private de.cismet.tools.gui.RoundedPanel pnlFotos; private de.cismet.tools.gui.RoundedPanel pnlGelaende; private de.cismet.tools.gui.RoundedPanel pnlGelaender; private de.cismet.tools.gui.SemiRoundedPanel pnlGelaenderHeader; private de.cismet.tools.gui.RoundedPanel pnlGruendung; private de.cismet.tools.gui.SemiRoundedPanel pnlGruendungHeader; private de.cismet.tools.gui.SemiRoundedPanel pnlGruendungHeader1; private de.cismet.tools.gui.SemiRoundedPanel pnlGruendungHeader2; private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderAllgemein; private de.cismet.tools.gui.SemiRoundedPanel pnlHeaderFotos; private javax.swing.JPanel pnlHoehe; private de.cismet.tools.gui.RoundedPanel pnlKopf; private de.cismet.tools.gui.SemiRoundedPanel pnlKopfAnsicht; private de.cismet.tools.gui.SemiRoundedPanel pnlKopfHeader; private javax.swing.JPanel pnlLeft; private javax.swing.JPanel pnlMap; private javax.swing.JPanel pnlScrollPane; private de.cismet.tools.gui.RoundedPanel pnlVerformung; private de.cismet.tools.gui.RoundedPanel pnlVorschau; private de.cismet.tools.gui.RoundedPanel roundedScrollPanel; private de.cismet.tools.gui.SemiRoundedPanel semiRoundedPanel2; private javax.swing.JTextArea taBeschreibungAnsicht; private javax.swing.JTextArea taBeschreibungGelaender; private javax.swing.JTextArea taBeschreibungGruendung; private javax.swing.JTextArea taBeschreibungGruendung1; private javax.swing.JTextArea taBeschreibungGruendung2; private javax.swing.JTextArea taBeschreibungKopf; private javax.swing.JTextArea taBesonderheiten; private javax.swing.JTextArea taLagebeschreibung; private javax.swing.JTextArea taNeigung; private javax.swing.JTextArea taSanMassnahmeAnsicht; private javax.swing.JTextArea taSanMassnahmeGelaender; private javax.swing.JTextArea taSanMassnahmeGruendung; private javax.swing.JTextArea taSanMassnahmeGruendung1; private javax.swing.JTextArea taSanMassnahmeGruendung2; private javax.swing.JTextArea taSanMassnahmeKopf; private javax.swing.JTextField tfHoeheMax; private javax.swing.JTextField tfHoeheMin; private javax.swing.JTextField tfLaenge; private javax.swing.JTextField tfLagebezeichnung; private javax.swing.JTextField tfLastabstand; private javax.swing.JTextField tfMauerNummer; private javax.swing.JTextField tfSanKostenAnsicht; private javax.swing.JTextField tfSanKostenGelaender; private javax.swing.JTextField tfSanKostenGruendung; private javax.swing.JTextField tfSanKostenGruendung1; private javax.swing.JTextField tfSanKostenGruendung2; private javax.swing.JTextField tfSanKostenKopf; private javax.swing.JTextField tfStaerkeOben; private javax.swing.JTextField tfStaerke_unten; private javax.swing.JTextField tfUmgebung; private javax.swing.JTextField tfZustandAnsicht; private javax.swing.JTextField tfZustandGelaender; private javax.swing.JTextField tfZustandGesamt; private javax.swing.JTextField tfZustandGruendung; private javax.swing.JTextField tfZustandGruendung1; private javax.swing.JTextField tfZustandGruendung2; private javax.swing.JTextField tfZustandKopf; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables //~ Constructors ----------------------------------------------------------- /** * Creates new form MauerEditor. */ public MauerEditor() { this(true); } /** * Creates a new MauerEditor object. * * @param editable DOCUMENT ME! */ public MauerEditor(final boolean editable) { this.editable = editable; initComponents(); if (editable) { pnlLeft.setPreferredSize(new Dimension(500, 900)); } jScrollPane3.getViewport().setOpaque(false); jspAllgemeineInfos.getViewport().setOpaque(false); map = new MappingComponent(); pnlMap.setLayout(new BorderLayout()); pnlMap.add(map, BorderLayout.CENTER); webDavHelper = new WebDavHelper(Proxy.fromPreferences(), WEB_DAV_USER, WEB_DAV_PASSWORD, true); setEditable(); final LayoutManager layout = getLayout(); if (layout instanceof CardLayout) { cardLayout = (CardLayout)layout; cardLayout.show(this, "card1"); } this.listListenerEnabled = true; fileChooser = new JFileChooser(); fileChooser.setFileFilter(new FileFilter() { @Override public boolean accept(final File f) { return f.isDirectory() || IMAGE_FILE_PATTERN.matcher(f.getName()).matches(); } @Override public String getDescription() { return "Bilddateien"; } }); fileChooser.setMultiSelectionEnabled(true); listRepaintListener = new PropertyChangeListener() { @Override public void propertyChange(final PropertyChangeEvent evt) { lstFotos.repaint(); } }; timer = new Timer(300, new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { if (resizeListenerEnabled) { // if (isShowing()) { if (currentResizeWorker != null) { currentResizeWorker.cancel(true); } currentResizeWorker = new ImageResizeWorker(); CismetThreadPool.execute(currentResizeWorker); // } else { // timer.restart(); // } } } }); timer.setRepeats(false); } //~ Methods ---------------------------------------------------------------- /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); panFooter = new javax.swing.JPanel(); panLeft = new javax.swing.JPanel(); lblInfo = new javax.swing.JLabel(); btnInfo = new javax.swing.JButton(); panRight = new javax.swing.JPanel(); btnImages = new javax.swing.JButton(); lblImages = new javax.swing.JLabel(); panTitle = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); btnReport = new javax.swing.JButton(); pnlCard1 = new javax.swing.JPanel(); pnlAllgemein = new de.cismet.tools.gui.RoundedPanel(); pnlHeaderAllgemein = new de.cismet.tools.gui.SemiRoundedPanel(); lblHeaderAllgemein = new javax.swing.JLabel(); jspAllgemeineInfos = new javax.swing.JScrollPane(); pnlLeft = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); taNeigung = new javax.swing.JTextArea(); cbMaterialtyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblStaerke = new javax.swing.JLabel(); lblStuetzmauer = new javax.swing.JLabel(); cbEigentuemer = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblLagebeschreibung = new javax.swing.JLabel(); lblHoeheMin = new javax.swing.JLabel(); tfUmgebung = new javax.swing.JTextField(); pnlHoehe = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); tfHoeheMin = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); tfHoeheMax = new javax.swing.JTextField(); lblFiller11 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); lblFiller7 = new javax.swing.JLabel(); lblEigentuemer = new javax.swing.JLabel(); lblNeigung = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); taLagebeschreibung = new javax.swing.JTextArea(); lblLaenge = new javax.swing.JLabel(); lblUmgebung = new javax.swing.JLabel(); tfLaenge = new javax.swing.JTextField(); lblMaterialTyp = new javax.swing.JLabel(); cbStuetzmauertyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel1 = new javax.swing.JPanel(); lblStaerkeUnten = new javax.swing.JLabel(); tfStaerke_unten = new javax.swing.JTextField(); lblStaerkeOben = new javax.swing.JLabel(); tfStaerkeOben = new javax.swing.JTextField(); lblBesonderheiten = new javax.swing.JLabel(); jScrollPane17 = new javax.swing.JScrollPane(); taBesonderheiten = new javax.swing.JTextArea(); lblLagebezeichnung = new javax.swing.JLabel(); tfLagebezeichnung = new javax.swing.JTextField(); lblMauerNummer = new javax.swing.JLabel(); tfMauerNummer = new javax.swing.JTextField(); lblMauertyp = new javax.swing.JLabel(); cbMauertyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblLastabstand = new javax.swing.JLabel(); tfLastabstand = new javax.swing.JTextField(); lblLastklasse = new javax.swing.JLabel(); lblDauerhaftigkeit = new javax.swing.JLabel(); lblVerkehrssicherheit = new javax.swing.JLabel(); lblStandsicherheit = new javax.swing.JLabel(); lblPruefung1 = new javax.swing.JLabel(); lblLetztePruefung = new javax.swing.JLabel(); lblNaechstePruefung = new javax.swing.JLabel(); lblBauwerksbuchfertigstellung = new javax.swing.JLabel(); lblSanierung = new javax.swing.JLabel(); if (editable) { lblGeom = new javax.swing.JLabel(); } if (editable) { cbGeom = new DefaultCismapGeometryComboBoxEditor(); } jPanel5 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); dcBauwerksbuchfertigstellung = new de.cismet.cids.editors.DefaultBindableDateChooser(); lblFiller10 = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); dcNaechstePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel16 = new javax.swing.JLabel(); cbArtNaechstePruefung1 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel6 = new javax.swing.JPanel(); jLabel13 = new javax.swing.JLabel(); dcLetztePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel14 = new javax.swing.JLabel(); cbArtLetztePruefung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel2 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); dcErstePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel6 = new javax.swing.JLabel(); cbArtErstePruefung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbStandsicherheit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbVerkehrssicherheit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbDauerhaftigkeit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbLastklasse = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblZustandGesamt = new javax.swing.JLabel(); tfZustandGesamt = new javax.swing.JTextField(); lblFiller8 = new javax.swing.JLabel(); dcSanierung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); roundedScrollPanel = new de.cismet.tools.gui.RoundedPanel(); jScrollPane3 = new javax.swing.JScrollPane(); pnlScrollPane = new javax.swing.JPanel(); pnlGelaender = new de.cismet.tools.gui.RoundedPanel(); pnlGelaenderHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblGelaenderHeader = new javax.swing.JLabel(); lblFiller = new javax.swing.JLabel(); lblBeschreibungGelaender = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); taBeschreibungGelaender = new javax.swing.JTextArea(); lblZustandGelaender = new javax.swing.JLabel(); lblSanKostenGelaender = new javax.swing.JLabel(); lblSanMassnahmenGelaender = new javax.swing.JLabel(); lblEingriffGeleander = new javax.swing.JLabel(); tfZustandGelaender = new javax.swing.JTextField(); tfSanKostenGelaender = new javax.swing.JTextField(); jScrollPane5 = new javax.swing.JScrollPane(); taSanMassnahmeGelaender = new javax.swing.JTextArea(); cbEingriffGelaender = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlKopf = new de.cismet.tools.gui.RoundedPanel(); pnlKopfHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpHeader = new javax.swing.JLabel(); lblFiller1 = new javax.swing.JLabel(); lblbeschreibungKopf = new javax.swing.JLabel(); jScrollPane6 = new javax.swing.JScrollPane(); taBeschreibungKopf = new javax.swing.JTextArea(); lblZustandKopf = new javax.swing.JLabel(); lblSanMassnahmenKopf = new javax.swing.JLabel(); lblSanKostenKopf = new javax.swing.JLabel(); lblEingriffKopf = new javax.swing.JLabel(); tfZustandKopf = new javax.swing.JTextField(); tfSanKostenKopf = new javax.swing.JTextField(); jScrollPane7 = new javax.swing.JScrollPane(); taSanMassnahmeKopf = new javax.swing.JTextArea(); cbEingriffKopf = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlAnsicht = new de.cismet.tools.gui.RoundedPanel(); pnlKopfAnsicht = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht = new javax.swing.JLabel(); lblFiller3 = new javax.swing.JLabel(); lblbeschreibungAnsicht = new javax.swing.JLabel(); jScrollPane8 = new javax.swing.JScrollPane(); taBeschreibungAnsicht = new javax.swing.JTextArea(); lblZustandAnsicht = new javax.swing.JLabel(); lblSanMassnahmenAnsicht = new javax.swing.JLabel(); lblSanKostenAnsicht = new javax.swing.JLabel(); lblEingriffAnsicht = new javax.swing.JLabel(); tfZustandAnsicht = new javax.swing.JTextField(); tfSanKostenAnsicht = new javax.swing.JTextField(); jScrollPane9 = new javax.swing.JScrollPane(); taSanMassnahmeAnsicht = new javax.swing.JTextArea(); cbEingriffAnsicht = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlGruendung = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht1 = new javax.swing.JLabel(); lblFiller4 = new javax.swing.JLabel(); lblbeschreibungGruendung = new javax.swing.JLabel(); jScrollPane10 = new javax.swing.JScrollPane(); taBeschreibungGruendung = new javax.swing.JTextArea(); lblZustandGruendung = new javax.swing.JLabel(); lblSanMassnahmenGruendung = new javax.swing.JLabel(); lblSanKostenAnsicht1 = new javax.swing.JLabel(); lblEingriffAnsicht1 = new javax.swing.JLabel(); tfZustandGruendung = new javax.swing.JTextField(); tfSanKostenGruendung = new javax.swing.JTextField(); jScrollPane11 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung = new javax.swing.JTextArea(); cbEingriffGruendung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlGelaende = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader1 = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht2 = new javax.swing.JLabel(); lblFiller5 = new javax.swing.JLabel(); lblbeschreibungGruendung1 = new javax.swing.JLabel(); jScrollPane12 = new javax.swing.JScrollPane(); taBeschreibungGruendung1 = new javax.swing.JTextArea(); lblZustandGruendung1 = new javax.swing.JLabel(); lblSanMassnahmenGruendung1 = new javax.swing.JLabel(); lblSanKostenAnsicht2 = new javax.swing.JLabel(); lblEingriffAnsicht2 = new javax.swing.JLabel(); tfZustandGruendung1 = new javax.swing.JTextField(); tfSanKostenGruendung1 = new javax.swing.JTextField(); jScrollPane13 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung1 = new javax.swing.JTextArea(); cbEingriffGelaende = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlVerformung = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht3 = new javax.swing.JLabel(); lblFiller6 = new javax.swing.JLabel(); lblbeschreibungGruendung2 = new javax.swing.JLabel(); jScrollPane14 = new javax.swing.JScrollPane(); taBeschreibungGruendung2 = new javax.swing.JTextArea(); lblZustandGruendung2 = new javax.swing.JLabel(); lblSanMassnahmenGruendung2 = new javax.swing.JLabel(); lblSanKostenAnsicht3 = new javax.swing.JLabel(); lblEingriffAnsicht3 = new javax.swing.JLabel(); tfZustandGruendung2 = new javax.swing.JTextField(); tfSanKostenGruendung2 = new javax.swing.JTextField(); jScrollPane15 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung2 = new javax.swing.JTextArea(); cbEingriffVerformung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlCard2 = new javax.swing.JPanel(); pnlFotos = new de.cismet.tools.gui.RoundedPanel(); pnlHeaderFotos = new de.cismet.tools.gui.SemiRoundedPanel(); lblHeaderFotos = new javax.swing.JLabel(); lblFiller9 = new javax.swing.JLabel(); lblFotos = new javax.swing.JLabel(); jspFotoList = new javax.swing.JScrollPane(); lstFotos = new javax.swing.JList(); pnlCtrlButtons = new javax.swing.JPanel(); btnAddImg = new javax.swing.JButton(); btnRemoveImg = new javax.swing.JButton(); pnlVorschau = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblVorschau = new javax.swing.JLabel(); pnlFoto = new javax.swing.JPanel(); lblPicture = new javax.swing.JLabel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(new Dimension(75, 75)); pnlCtrlBtn = new javax.swing.JPanel(); btnPrevImg = new javax.swing.JButton(); btnNextImg = new javax.swing.JButton(); pnlMap = new javax.swing.JPanel(); panFooter.setOpaque(false); panFooter.setLayout(new java.awt.GridBagLayout()); panLeft.setOpaque(false); lblInfo.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N lblInfo.setForeground(new java.awt.Color(255, 255, 255)); lblInfo.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblInfo.text")); // NOI18N lblInfo.setEnabled(false); panLeft.add(lblInfo); btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-left.png"))); // NOI18N btnInfo.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnInfo.text")); // NOI18N btnInfo.setBorderPainted(false); btnInfo.setContentAreaFilled(false); btnInfo.setEnabled(false); btnInfo.setFocusPainted(false); btnInfo.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnInfoActionPerformed(evt); } }); panLeft.add(btnInfo); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; panFooter.add(panLeft, gridBagConstraints); panRight.setOpaque(false); btnImages.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-right.png"))); // NOI18N btnImages.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnImages.text")); // NOI18N btnImages.setBorderPainted(false); btnImages.setContentAreaFilled(false); btnImages.setFocusPainted(false); btnImages.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnImagesActionPerformed(evt); } }); panRight.add(btnImages); lblImages.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N lblImages.setForeground(new java.awt.Color(255, 255, 255)); lblImages.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblImages.text")); // NOI18N panRight.add(lblImages); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; panFooter.add(panRight, gridBagConstraints); panTitle.setOpaque(false); panTitle.setLayout(new java.awt.GridBagLayout()); lblTitle.setFont(new java.awt.Font("DejaVu Sans", 1, 18)); // NOI18N lblTitle.setForeground(new java.awt.Color(255, 255, 255)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; panTitle.add(lblTitle, gridBagConstraints); btnReport.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/icons/printer.png"))); // NOI18N btnReport.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnReport.text")); // NOI18N btnReport.setToolTipText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.btnReport.toolTipText")); // NOI18N btnReport.setBorderPainted(false); btnReport.setContentAreaFilled(false); btnReport.setFocusPainted(false); btnReport.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnReportActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; panTitle.add(btnReport, gridBagConstraints); setMaximumSize(new java.awt.Dimension(1190, 1625)); setMinimumSize(new java.awt.Dimension(807, 485)); setVerifyInputWhenFocusTarget(false); setLayout(new java.awt.CardLayout()); pnlCard1.setOpaque(false); pnlCard1.setLayout(new java.awt.GridBagLayout()); pnlAllgemein.setMinimumSize(new java.awt.Dimension(540, 500)); pnlAllgemein.setPreferredSize(new java.awt.Dimension(540, 800)); pnlAllgemein.setLayout(new java.awt.GridBagLayout()); pnlHeaderAllgemein.setBackground(new java.awt.Color(51, 51, 51)); pnlHeaderAllgemein.setMinimumSize(new java.awt.Dimension(109, 24)); pnlHeaderAllgemein.setPreferredSize(new java.awt.Dimension(109, 24)); pnlHeaderAllgemein.setLayout(new java.awt.FlowLayout()); lblHeaderAllgemein.setForeground(new java.awt.Color(255, 255, 255)); lblHeaderAllgemein.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblHeaderAllgemein.text")); // NOI18N pnlHeaderAllgemein.add(lblHeaderAllgemein); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlAllgemein.add(pnlHeaderAllgemein, gridBagConstraints); jspAllgemeineInfos.setBorder(null); jspAllgemeineInfos.setMinimumSize(new java.awt.Dimension(500, 520)); jspAllgemeineInfos.setOpaque(false); jspAllgemeineInfos.setPreferredSize(new java.awt.Dimension(500, 880)); pnlLeft.setMinimumSize(new java.awt.Dimension(500, 790)); pnlLeft.setOpaque(false); pnlLeft.setPreferredSize(new java.awt.Dimension(500, 850)); pnlLeft.setLayout(new java.awt.GridBagLayout()); jScrollPane2.setMinimumSize(new java.awt.Dimension(26, 50)); jScrollPane2.setPreferredSize(new java.awt.Dimension(0, 50)); taNeigung.setLineWrap(true); taNeigung.setMinimumSize(new java.awt.Dimension(500, 34)); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.neigung}"), taNeigung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane2.setViewportView(taNeigung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jScrollPane2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.materialtyp}"), cbMaterialtyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbMaterialtyp, gridBagConstraints); lblStaerke.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblStaerke.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStaerke, gridBagConstraints); lblStuetzmauer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStuetzmauer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStuetzmauer, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.eigentuemer}"), cbEigentuemer, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 8; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbEigentuemer, gridBagConstraints); lblLagebeschreibung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLagebeschreibung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLagebeschreibung, gridBagConstraints); lblHoeheMin.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblHoeheMin.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 9; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblHoeheMin, gridBagConstraints); tfUmgebung.setMinimumSize(new java.awt.Dimension(100, 20)); tfUmgebung.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.umgebung}"), tfUmgebung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfUmgebung, gridBagConstraints); pnlHoehe.setOpaque(false); pnlHoehe.setLayout(new java.awt.GridBagLayout()); jLabel1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlHoehe.add(jLabel1, gridBagConstraints); tfHoeheMin.setMinimumSize(new java.awt.Dimension(50, 20)); tfHoeheMin.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_min}"), tfHoeheMin, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 20); pnlHoehe.add(tfHoeheMin, gridBagConstraints); jLabel3.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlHoehe.add(jLabel3, gridBagConstraints); tfHoeheMax.setMinimumSize(new java.awt.Dimension(50, 20)); tfHoeheMax.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_max}"), tfHoeheMax, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0); pnlHoehe.add(tfHoeheMax, gridBagConstraints); lblFiller11.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller11.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlHoehe.add(lblFiller11, gridBagConstraints); jPanel3.setOpaque(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jLabel4.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel4.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; jPanel3.add(jLabel4, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_ONCE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe}"), jLabel2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 0); jPanel3.add(jLabel2, gridBagConstraints); lblFiller7.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller7.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel3.add(lblFiller7, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlHoehe.add(jPanel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 9; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(pnlHoehe, gridBagConstraints); lblEigentuemer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEigentuemer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblEigentuemer, gridBagConstraints); lblNeigung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblNeigung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblNeigung, gridBagConstraints); jScrollPane1.setMinimumSize(new java.awt.Dimension(26, 40)); jScrollPane1.setPreferredSize(new java.awt.Dimension(0, 50)); jScrollPane1.setRequestFocusEnabled(false); taLagebeschreibung.setLineWrap(true); taLagebeschreibung.setMaximumSize(new java.awt.Dimension(500, 34)); taLagebeschreibung.setMinimumSize(new java.awt.Dimension(500, 34)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebeschreibung}"), taLagebeschreibung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane1.setViewportView(taLagebeschreibung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jScrollPane1, gridBagConstraints); lblLaenge.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblLaenge.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 11; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLaenge, gridBagConstraints); lblUmgebung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblUmgebung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblUmgebung, gridBagConstraints); tfLaenge.setMinimumSize(new java.awt.Dimension(100, 20)); tfLaenge.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laenge}"), tfLaenge, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 11; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLaenge, gridBagConstraints); lblMaterialTyp.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblMaterialTyp.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMaterialTyp, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.stuetzmauertyp}"), cbStuetzmauertyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbStuetzmauertyp, gridBagConstraints); jPanel1.setOpaque(false); jPanel1.setLayout(new java.awt.GridBagLayout()); lblStaerkeUnten.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStaerkeUnten.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(lblStaerkeUnten, gridBagConstraints); tfStaerke_unten.setMinimumSize(new java.awt.Dimension(50, 20)); tfStaerke_unten.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.staerke_unten}"), tfStaerke_unten, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); tfStaerke_unten.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { tfStaerke_untenActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel1.add(tfStaerke_unten, gridBagConstraints); lblStaerkeOben.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStaerkeOben.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(lblStaerkeOben, gridBagConstraints); tfStaerkeOben.setMinimumSize(new java.awt.Dimension(50, 20)); tfStaerkeOben.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.staerke_oben}"), tfStaerkeOben, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; jPanel1.add(tfStaerkeOben, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel1, gridBagConstraints); lblBesonderheiten.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBesonderheiten.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 12; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblBesonderheiten, gridBagConstraints); jScrollPane17.setMinimumSize(new java.awt.Dimension(26, 50)); jScrollPane17.setPreferredSize(new java.awt.Dimension(0, 50)); taBesonderheiten.setLineWrap(true); taBesonderheiten.setMinimumSize(new java.awt.Dimension(500, 34)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.besonderheiten}"), taBesonderheiten, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane17.setViewportView(taBesonderheiten); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 12; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 10); pnlLeft.add(jScrollPane17, gridBagConstraints); lblLagebezeichnung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLagebezeichnung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLagebezeichnung, gridBagConstraints); tfLagebezeichnung.setMinimumSize(new java.awt.Dimension(100, 20)); tfLagebezeichnung.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebezeichnung}"), tfLagebezeichnung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLagebezeichnung, gridBagConstraints); lblMauerNummer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblMauerNummer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMauerNummer, gridBagConstraints); tfMauerNummer.setMinimumSize(new java.awt.Dimension(150, 20)); tfMauerNummer.setPreferredSize(new java.awt.Dimension(150, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.mauer_nummer}"), tfMauerNummer, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfMauerNummer, gridBagConstraints); lblMauertyp.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblMauertyp.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMauertyp, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.mauertyp}"), cbMauertyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbMauertyp, gridBagConstraints); lblLastabstand.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLastabstand.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 13; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLastabstand, gridBagConstraints); tfLastabstand.setMinimumSize(new java.awt.Dimension(100, 20)); tfLastabstand.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lastabstand}"), tfLastabstand, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 13; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLastabstand, gridBagConstraints); lblLastklasse.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLastklasse.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 14; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLastklasse, gridBagConstraints); lblDauerhaftigkeit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblDauerhaftigkeit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 15; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblDauerhaftigkeit, gridBagConstraints); lblVerkehrssicherheit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblVerkehrssicherheit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 16; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblVerkehrssicherheit, gridBagConstraints); lblStandsicherheit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStandsicherheit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 17; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStandsicherheit, gridBagConstraints); lblPruefung1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblPruefung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 18; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblPruefung1, gridBagConstraints); lblLetztePruefung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLetztePruefung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 19; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLetztePruefung, gridBagConstraints); lblNaechstePruefung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblNaechstePruefung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 20; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblNaechstePruefung, gridBagConstraints); lblBauwerksbuchfertigstellung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBauwerksbuchfertigstellung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 21; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblBauwerksbuchfertigstellung, gridBagConstraints); lblSanierung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblSanierung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 22; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblSanierung, gridBagConstraints); if (editable) { lblGeom.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblGeom.text")); // NOI18N } if (editable) { gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 24; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblGeom, gridBagConstraints); } if (editable) { cbGeom.setMinimumSize(new java.awt.Dimension(41, 25)); cbGeom.setPreferredSize(new java.awt.Dimension(41, 25)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.georeferenz}"), cbGeom, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cbGeom).getConverter()); bindingGroup.addBinding(binding); } if (editable) { gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 24; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbGeom, gridBagConstraints); } jPanel5.setOpaque(false); jPanel5.setLayout(new java.awt.GridBagLayout()); jLabel11.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel11.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel5.add(jLabel11, gridBagConstraints); dcBauwerksbuchfertigstellung.setMinimumSize(new java.awt.Dimension(124, 20)); dcBauwerksbuchfertigstellung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bauwerksbuchfertigstellung}"), dcBauwerksbuchfertigstellung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcBauwerksbuchfertigstellung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel5.add(dcBauwerksbuchfertigstellung, gridBagConstraints); lblFiller10.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller10.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel5.add(lblFiller10, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 21; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel5, gridBagConstraints); jPanel7.setOpaque(false); jPanel7.setLayout(new java.awt.GridBagLayout()); jLabel15.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel15.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel7.add(jLabel15, gridBagConstraints); dcNaechstePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcNaechstePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_naechste_pruefung}"), dcNaechstePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcNaechstePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel7.add(dcNaechstePruefung, gridBagConstraints); jLabel16.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel16.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel7.add(jLabel16, gridBagConstraints); cbArtNaechstePruefung1.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtNaechstePruefung1.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_naechste_pruefung}"), cbArtNaechstePruefung1, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel7.add(cbArtNaechstePruefung1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 20; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel7, gridBagConstraints); jPanel6.setOpaque(false); jPanel6.setLayout(new java.awt.GridBagLayout()); jLabel13.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel13.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel6.add(jLabel13, gridBagConstraints); dcLetztePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcLetztePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_letzte_pruefung}"), dcLetztePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcLetztePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel6.add(dcLetztePruefung, gridBagConstraints); jLabel14.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel14.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel6.add(jLabel14, gridBagConstraints); cbArtLetztePruefung.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtLetztePruefung.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_letzte_pruefung}"), cbArtLetztePruefung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel6.add(cbArtLetztePruefung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 19; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel6, gridBagConstraints); jPanel2.setOpaque(false); jPanel2.setLayout(new java.awt.GridBagLayout()); jLabel5.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel5.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel2.add(jLabel5, gridBagConstraints); dcErstePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcErstePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_erste_pruefung}"), dcErstePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcErstePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel2.add(dcErstePruefung, gridBagConstraints); jLabel6.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel6.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel2.add(jLabel6, gridBagConstraints); cbArtErstePruefung.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtErstePruefung.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_erste_pruefung}"), cbArtErstePruefung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel2.add(cbArtErstePruefung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 18; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.standsicherheit}"), cbStandsicherheit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 17; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbStandsicherheit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.verkehrssicherheit}"), cbVerkehrssicherheit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 16; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbVerkehrssicherheit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.dauerhaftigkeit}"), cbDauerhaftigkeit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 15; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbDauerhaftigkeit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lastklasse}"), cbLastklasse, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 14; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbLastklasse, gridBagConstraints); lblZustandGesamt.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGesamt.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 23; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblZustandGesamt, gridBagConstraints); tfZustandGesamt.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGesamt.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gesamt}"), tfZustandGesamt, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new DoubleNumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 23; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfZustandGesamt, gridBagConstraints); lblFiller8.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller8.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 25; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; pnlLeft.add(lblFiller8, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.sanierung}"), dcSanierung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 22; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(dcSanierung, gridBagConstraints); jspAllgemeineInfos.setViewportView(pnlLeft); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlAllgemein.add(jspAllgemeineInfos, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 0.5; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCard1.add(pnlAllgemein, gridBagConstraints); roundedScrollPanel.setBackground(new java.awt.Color(254, 254, 254)); roundedScrollPanel.setForeground(new java.awt.Color(254, 254, 254)); roundedScrollPanel.setMinimumSize(new java.awt.Dimension(500, 26)); roundedScrollPanel.setPreferredSize(new java.awt.Dimension(500, 120)); roundedScrollPanel.setLayout(new java.awt.GridBagLayout()); jScrollPane3.setBackground(new java.awt.Color(254, 254, 254)); jScrollPane3.setBorder(null); jScrollPane3.setFocusable(false); jScrollPane3.setMinimumSize(new java.awt.Dimension(500, 26)); jScrollPane3.setOpaque(false); jScrollPane3.setPreferredSize(new java.awt.Dimension(600, 120)); pnlScrollPane.setBackground(new java.awt.Color(254, 254, 254)); pnlScrollPane.setFocusable(false); pnlScrollPane.setOpaque(false); pnlScrollPane.setLayout(new java.awt.GridBagLayout()); pnlGelaender.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGelaender.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGelaender.setLayout(new java.awt.GridBagLayout()); pnlGelaenderHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlGelaenderHeader.setLayout(new java.awt.FlowLayout()); lblGelaenderHeader.setForeground(new java.awt.Color(255, 255, 255)); lblGelaenderHeader.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblGelaenderHeader.text")); // NOI18N pnlGelaenderHeader.add(lblGelaenderHeader); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGelaender.add(pnlGelaenderHeader, gridBagConstraints); lblFiller.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGelaender.add(lblFiller, gridBagConstraints); lblBeschreibungGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBeschreibungGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGelaender.add(lblBeschreibungGelaender, gridBagConstraints); jScrollPane4.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane4.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGelaender.setLineWrap(true); taBeschreibungGelaender.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gelaender}"), taBeschreibungGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane4.setViewportView(taBeschreibungGelaender); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGelaender.add(jScrollPane4, gridBagConstraints); lblZustandGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblZustandGelaender, gridBagConstraints); lblSanKostenGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblSanKostenGelaender, gridBagConstraints); lblSanMassnahmenGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblSanMassnahmenGelaender, gridBagConstraints); lblEingriffGeleander.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffGeleander.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblEingriffGeleander, gridBagConstraints); tfZustandGelaender.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGelaender.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gelaender}"), tfZustandGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaender.add(tfZustandGelaender, gridBagConstraints); tfSanKostenGelaender.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGelaender.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gelaender}"), tfSanKostenGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaender.add(tfSanKostenGelaender, gridBagConstraints); jScrollPane5.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane5.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeGelaender.setLineWrap(true); taSanMassnahmeGelaender.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gelaender}"), taSanMassnahmeGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane5.setViewportView(taSanMassnahmeGelaender); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaender.add(jScrollPane5, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gelaender}"), cbEingriffGelaender, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaender.add(cbEingriffGelaender, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGelaender, gridBagConstraints); pnlKopf.setMinimumSize(new java.awt.Dimension(450, 300)); pnlKopf.setPreferredSize(new java.awt.Dimension(450, 300)); pnlKopf.setLayout(new java.awt.GridBagLayout()); pnlKopfHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlKopfHeader.setLayout(new java.awt.FlowLayout()); lblKofpHeader.setForeground(new java.awt.Color(255, 255, 255)); lblKofpHeader.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpHeader.text")); // NOI18N pnlKopfHeader.add(lblKofpHeader); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlKopf.add(pnlKopfHeader, gridBagConstraints); lblFiller1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlKopf.add(lblFiller1, gridBagConstraints); lblbeschreibungKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlKopf.add(lblbeschreibungKopf, gridBagConstraints); jScrollPane6.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane6.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungKopf.setLineWrap(true); taBeschreibungKopf.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_kopf}"), taBeschreibungKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane6.setViewportView(taBeschreibungKopf); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlKopf.add(jScrollPane6, gridBagConstraints); lblZustandKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblZustandKopf, gridBagConstraints); lblSanMassnahmenKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblSanMassnahmenKopf, gridBagConstraints); lblSanKostenKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblSanKostenKopf, gridBagConstraints); lblEingriffKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblEingriffKopf, gridBagConstraints); tfZustandKopf.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandKopf.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_kopf}"), tfZustandKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlKopf.add(tfZustandKopf, gridBagConstraints); tfSanKostenKopf.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenKopf.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_kopf}"), tfSanKostenKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlKopf.add(tfSanKostenKopf, gridBagConstraints); jScrollPane7.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane7.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeKopf.setLineWrap(true); taSanMassnahmeKopf.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_kopf}"), taSanMassnahmeKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane7.setViewportView(taSanMassnahmeKopf); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlKopf.add(jScrollPane7, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_kopf}"), cbEingriffKopf, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlKopf.add(cbEingriffKopf, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlKopf, gridBagConstraints); pnlAnsicht.setMinimumSize(new java.awt.Dimension(450, 300)); pnlAnsicht.setPreferredSize(new java.awt.Dimension(450, 300)); pnlAnsicht.setLayout(new java.awt.GridBagLayout()); pnlKopfAnsicht.setBackground(new java.awt.Color(51, 51, 51)); pnlKopfAnsicht.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht.text")); // NOI18N pnlKopfAnsicht.add(lblKofpAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlAnsicht.add(pnlKopfAnsicht, gridBagConstraints); lblFiller3.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlAnsicht.add(lblFiller3, gridBagConstraints); lblbeschreibungAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlAnsicht.add(lblbeschreibungAnsicht, gridBagConstraints); jScrollPane8.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane8.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungAnsicht.setLineWrap(true); taBeschreibungAnsicht.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_ansicht}"), taBeschreibungAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane8.setViewportView(taBeschreibungAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlAnsicht.add(jScrollPane8, gridBagConstraints); lblZustandAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblZustandAnsicht, gridBagConstraints); lblSanMassnahmenAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblSanMassnahmenAnsicht, gridBagConstraints); lblSanKostenAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblSanKostenAnsicht, gridBagConstraints); lblEingriffAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblEingriffAnsicht, gridBagConstraints); tfZustandAnsicht.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandAnsicht.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_ansicht}"), tfZustandAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAnsicht.add(tfZustandAnsicht, gridBagConstraints); tfSanKostenAnsicht.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenAnsicht.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_ansicht}"), tfSanKostenAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAnsicht.add(tfSanKostenAnsicht, gridBagConstraints); jScrollPane9.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane9.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeAnsicht.setLineWrap(true); taSanMassnahmeAnsicht.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_ansicht}"), taSanMassnahmeAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane9.setViewportView(taSanMassnahmeAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlAnsicht.add(jScrollPane9, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_ansicht}"), cbEingriffAnsicht, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlAnsicht.add(cbEingriffAnsicht, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlAnsicht, gridBagConstraints); pnlGruendung.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGruendung.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGruendung.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht1.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht1.text")); // NOI18N pnlGruendungHeader.add(lblKofpAnsicht1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGruendung.add(pnlGruendungHeader, gridBagConstraints); lblFiller4.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller4.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGruendung.add(lblFiller4, gridBagConstraints); lblbeschreibungGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGruendung.add(lblbeschreibungGruendung, gridBagConstraints); jScrollPane10.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane10.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung.setLineWrap(true); taBeschreibungGruendung.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gruendung}"), taBeschreibungGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane10.setViewportView(taBeschreibungGruendung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGruendung.add(jScrollPane10, gridBagConstraints); lblZustandGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblZustandGruendung, gridBagConstraints); lblSanMassnahmenGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblSanMassnahmenGruendung, gridBagConstraints); lblSanKostenAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblSanKostenAnsicht1, gridBagConstraints); lblEingriffAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblEingriffAnsicht1, gridBagConstraints); tfZustandGruendung.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gruendung}"), tfZustandGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGruendung.add(tfZustandGruendung, gridBagConstraints); tfSanKostenGruendung.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, - org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_Gruendung}"), + org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gruendung}"), tfSanKostenGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGruendung.add(tfSanKostenGruendung, gridBagConstraints); jScrollPane11.setMinimumSize(new java.awt.Dimension(26, 87)); jScrollPane11.setPreferredSize(new java.awt.Dimension(262, 70)); taSanMassnahmeGruendung.setLineWrap(true); taSanMassnahmeGruendung.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gruendung}"), taSanMassnahmeGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane11.setViewportView(taSanMassnahmeGruendung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGruendung.add(jScrollPane11, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gruendung}"), cbEingriffGruendung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGruendung.add(cbEingriffGruendung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGruendung, gridBagConstraints); pnlGelaende.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGelaende.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGelaende.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader1.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader1.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht2.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht2.text")); // NOI18N pnlGruendungHeader1.add(lblKofpAnsicht2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGelaende.add(pnlGruendungHeader1, gridBagConstraints); lblFiller5.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller5.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGelaende.add(lblFiller5, gridBagConstraints); lblbeschreibungGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGelaende.add(lblbeschreibungGruendung1, gridBagConstraints); jScrollPane12.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane12.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung1.setLineWrap(true); taBeschreibungGruendung1.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gelaende}"), taBeschreibungGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane12.setViewportView(taBeschreibungGruendung1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGelaende.add(jScrollPane12, gridBagConstraints); lblZustandGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblZustandGruendung1, gridBagConstraints); lblSanMassnahmenGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblSanMassnahmenGruendung1, gridBagConstraints); lblSanKostenAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblSanKostenAnsicht2, gridBagConstraints); lblEingriffAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblEingriffAnsicht2, gridBagConstraints); tfZustandGruendung1.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung1.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gelaende}"), tfZustandGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaende.add(tfZustandGruendung1, gridBagConstraints); tfSanKostenGruendung1.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung1.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gelaende}"), tfSanKostenGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaende.add(tfSanKostenGruendung1, gridBagConstraints); jScrollPane13.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane13.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeGruendung1.setLineWrap(true); taSanMassnahmeGruendung1.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gelaende}"), taSanMassnahmeGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane13.setViewportView(taSanMassnahmeGruendung1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaende.add(jScrollPane13, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gelaende}"), cbEingriffGelaende, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaende.add(cbEingriffGelaende, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGelaende, gridBagConstraints); pnlVerformung.setMinimumSize(new java.awt.Dimension(450, 300)); pnlVerformung.setPreferredSize(new java.awt.Dimension(450, 300)); pnlVerformung.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader2.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader2.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht3.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht3.text")); // NOI18N pnlGruendungHeader2.add(lblKofpAnsicht3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlVerformung.add(pnlGruendungHeader2, gridBagConstraints); lblFiller6.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller6.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVerformung.add(lblFiller6, gridBagConstraints); lblbeschreibungGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlVerformung.add(lblbeschreibungGruendung2, gridBagConstraints); jScrollPane14.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane14.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung2.setLineWrap(true); taBeschreibungGruendung2.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_verformung}"), taBeschreibungGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane14.setViewportView(taBeschreibungGruendung2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlVerformung.add(jScrollPane14, gridBagConstraints); lblZustandGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblZustandGruendung2, gridBagConstraints); lblSanMassnahmenGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblSanMassnahmenGruendung2, gridBagConstraints); lblSanKostenAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblSanKostenAnsicht3, gridBagConstraints); lblEingriffAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblEingriffAnsicht3, gridBagConstraints); tfZustandGruendung2.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung2.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_verformung}"), tfZustandGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlVerformung.add(tfZustandGruendung2, gridBagConstraints); tfSanKostenGruendung2.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung2.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_verformung}"), tfSanKostenGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlVerformung.add(tfSanKostenGruendung2, gridBagConstraints); jScrollPane15.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane15.setPreferredSize(new java.awt.Dimension(262, 70)); taSanMassnahmeGruendung2.setLineWrap(true); taSanMassnahmeGruendung2.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_verformung}"), taSanMassnahmeGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane15.setViewportView(taSanMassnahmeGruendung2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlVerformung.add(jScrollPane15, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_verformung}"), cbEingriffVerformung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlVerformung.add(cbEingriffVerformung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlVerformung, gridBagConstraints); jScrollPane3.setViewportView(pnlScrollPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedScrollPanel.add(jScrollPane3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.5; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCard1.add(roundedScrollPanel, gridBagConstraints); add(pnlCard1, "card1"); pnlCard2.setOpaque(false); pnlCard2.setLayout(new java.awt.GridBagLayout()); pnlFotos.setMinimumSize(new java.awt.Dimension(400, 200)); pnlFotos.setPreferredSize(new java.awt.Dimension(400, 200)); pnlFotos.setLayout(new java.awt.GridBagLayout()); pnlHeaderFotos.setBackground(new java.awt.Color(51, 51, 51)); pnlHeaderFotos.setForeground(new java.awt.Color(51, 51, 51)); pnlHeaderFotos.setLayout(new java.awt.FlowLayout()); lblHeaderFotos.setForeground(new java.awt.Color(255, 255, 255)); lblHeaderFotos.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblHeaderFotos.text")); // NOI18N pnlHeaderFotos.add(lblHeaderFotos); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlFotos.add(pnlHeaderFotos, gridBagConstraints); lblFiller9.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller9.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlFotos.add(lblFiller9, gridBagConstraints); lblFotos.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFotos.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlFotos.add(lblFotos, gridBagConstraints); jspFotoList.setMinimumSize(new java.awt.Dimension(250, 130)); lstFotos.setMinimumSize(new java.awt.Dimension(250, 130)); lstFotos.setPreferredSize(new java.awt.Dimension(250, 130)); final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create( "${cidsBean.bilder}"); final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings .createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFotos); bindingGroup.addBinding(jListBinding); lstFotos.addListSelectionListener(new javax.swing.event.ListSelectionListener() { @Override public void valueChanged(final javax.swing.event.ListSelectionEvent evt) { lstFotosValueChanged(evt); } }); jspFotoList.setViewportView(lstFotos); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlFotos.add(jspFotoList, gridBagConstraints); pnlCtrlButtons.setOpaque(false); pnlCtrlButtons.setLayout(new java.awt.GridBagLayout()); btnAddImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons.add(btnAddImg, gridBagConstraints); btnRemoveImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons.add(btnRemoveImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlFotos.add(pnlCtrlButtons, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 10); pnlCard2.add(pnlFotos, gridBagConstraints); pnlVorschau.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); lblVorschau.setForeground(new java.awt.Color(255, 255, 255)); lblVorschau.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblVorschau.text")); // NOI18N semiRoundedPanel2.add(lblVorschau); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlVorschau.add(semiRoundedPanel2, gridBagConstraints); pnlFoto.setOpaque(false); pnlFoto.setLayout(new java.awt.GridBagLayout()); lblPicture.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblPicture.text")); // NOI18N pnlFoto.add(lblPicture, new java.awt.GridBagConstraints()); lblBusy.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblBusy.setMaximumSize(new java.awt.Dimension(140, 40)); lblBusy.setMinimumSize(new java.awt.Dimension(140, 60)); lblBusy.setPreferredSize(new java.awt.Dimension(140, 60)); pnlFoto.add(lblBusy, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVorschau.add(pnlFoto, gridBagConstraints); pnlCtrlBtn.setOpaque(false); pnlCtrlBtn.setPreferredSize(new java.awt.Dimension(100, 50)); pnlCtrlBtn.setLayout(new java.awt.GridBagLayout()); btnPrevImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-left.png"))); // NOI18N btnPrevImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnPrevImg.setBorderPainted(false); btnPrevImg.setFocusPainted(false); btnPrevImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnPrevImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; pnlCtrlBtn.add(btnPrevImg, gridBagConstraints); btnNextImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-right.png"))); // NOI18N btnNextImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnNextImg.text")); // NOI18N btnNextImg.setBorderPainted(false); btnNextImg.setFocusPainted(false); btnNextImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnNextImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; pnlCtrlBtn.add(btnNextImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; pnlVorschau.add(pnlCtrlBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.8; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 15); pnlCard2.add(pnlVorschau, gridBagConstraints); pnlMap.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlMap.setMinimumSize(new java.awt.Dimension(400, 200)); pnlMap.setPreferredSize(new java.awt.Dimension(400, 200)); pnlMap.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 10); pnlCard2.add(pnlMap, gridBagConstraints); add(pnlCard2, "card2"); bindingGroup.bind(); } // </editor-fold>//GEN-END:initComponents /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnImagesActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnImagesActionPerformed cardLayout.show(this, "card2"); btnImages.setEnabled(false); btnInfo.setEnabled(true); lblImages.setEnabled(false); lblInfo.setEnabled(true); } //GEN-LAST:event_btnImagesActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnInfoActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnInfoActionPerformed cardLayout.show(this, "card1"); btnImages.setEnabled(true); btnInfo.setEnabled(false); lblImages.setEnabled(true); lblInfo.setEnabled(false); } //GEN-LAST:event_btnInfoActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnPrevImgActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnPrevImgActionPerformed lstFotos.setSelectedIndex(lstFotos.getSelectedIndex() - 1); } //GEN-LAST:event_btnPrevImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnNextImgActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnNextImgActionPerformed lstFotos.setSelectedIndex(lstFotos.getSelectedIndex() + 1); } //GEN-LAST:event_btnNextImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void lstFotosValueChanged(final javax.swing.event.ListSelectionEvent evt) { //GEN-FIRST:event_lstFotosValueChanged if (!evt.getValueIsAdjusting() && listListenerEnabled) { loadFoto(); } } //GEN-LAST:event_lstFotosValueChanged /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void tfStaerke_untenActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_tfStaerke_untenActionPerformed // TODO add your handling code here: } //GEN-LAST:event_tfStaerke_untenActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnAddImgActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnAddImgActionPerformed if (JFileChooser.APPROVE_OPTION == fileChooser.showOpenDialog(this)) { final File[] selFiles = fileChooser.getSelectedFiles(); if ((selFiles != null) && (selFiles.length > 0)) { CismetThreadPool.execute(new ImageUploadWorker(Arrays.asList(selFiles))); } } } //GEN-LAST:event_btnAddImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnRemoveImgActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnRemoveImgActionPerformed final Object[] selection = lstFotos.getSelectedValues(); if ((selection != null) && (selection.length > 0)) { final int answer = JOptionPane.showConfirmDialog( StaticSwingTools.getParentFrame(this), "Sollen die Fotos wirklich gelöscht werden?", "Fotos entfernen", JOptionPane.YES_NO_OPTION); if (answer == JOptionPane.YES_OPTION) { try { listListenerEnabled = false; final List<Object> removeList = Arrays.asList(selection); final List<CidsBean> fotos = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "bilder"); if (fotos != null) { fotos.removeAll(removeList); } // TODO set the laufende_nr for (int i = 0; i < lstFotos.getModel().getSize(); i++) { final CidsBean foto = (CidsBean)lstFotos.getModel().getElementAt(i); foto.setProperty("laufende_nummer", i + 1); } for (final Object toDeleteObj : removeList) { if (toDeleteObj instanceof CidsBean) { final CidsBean fotoToDelete = (CidsBean)toDeleteObj; final String file = String.valueOf(fotoToDelete.getProperty("url.object_name")); IMAGE_CACHE.remove(file); removedFotoBeans.add(fotoToDelete); } } } catch (Exception e) { log.error(e, e); showExceptionToUser(e, this); } finally { // TODO check the laufende_nummer attribute listListenerEnabled = true; final int modelSize = lstFotos.getModel().getSize(); if (modelSize > 0) { lstFotos.setSelectedIndex(0); } else { image = null; lblPicture.setIcon(FOLDER_ICON); } } } } } //GEN-LAST:event_btnRemoveImgActionPerformed /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ private void btnReportActionPerformed(final java.awt.event.ActionEvent evt) { //GEN-FIRST:event_btnReportActionPerformed final Collection<CidsBean> c = new LinkedList<CidsBean>(); c.add(cidsBean); MauernReportGenerator.generateKatasterBlatt(c, MauerEditor.this); } //GEN-LAST:event_btnReportActionPerformed /** * DOCUMENT ME! * * @param ex DOCUMENT ME! * @param parent DOCUMENT ME! */ private static void showExceptionToUser(final Exception ex, final JComponent parent) { final ErrorInfo ei = new ErrorInfo( "Fehler", "Beim Vorgang ist ein Fehler aufgetreten", null, null, ex, Level.SEVERE, null); JXErrorPane.showDialog(parent, ei); } @Override public CidsBean getCidsBean() { return cidsBean; } @Override public void setCidsBean(final CidsBean cidsBean) { bindingGroup.unbind(); if (cidsBean != null) { DefaultCustomObjectEditor.setMetaClassInformationToMetaClassStoreComponentsInBindingGroup( bindingGroup, cidsBean); this.cidsBean = cidsBean; final String lagebez = (String)cidsBean.getProperty("lagebezeichnung"); this.title = NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblTitle.prefix") + ((lagebez != null) ? lagebez : ""); lblTitle.setText(this.title); initMap(); bindingGroup.bind(); lstFotos.getModel().addListDataListener(new ListDataListener() { @Override public void intervalAdded(final ListDataEvent e) { defineButtonStatus(); } @Override public void intervalRemoved(final ListDataEvent e) { defineButtonStatus(); } @Override public void contentsChanged(final ListDataEvent e) { defineButtonStatus(); } }); if (lstFotos.getModel().getSize() > 0) { lstFotos.setSelectedIndex(0); } } } @Override public void dispose() { bindingGroup.unbind(); } @Override public String getTitle() { return String.valueOf(cidsBean); } @Override public void setTitle(String title) { if (title == null) { title = "<Error>"; } this.title = NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblTitle.prefix") + title; lblTitle.setText(this.title); } /** * DOCUMENT ME! * * @param args DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ public static void main(final String[] args) throws Exception { DevelopmentTools.createEditorInFrameFromRMIConnectionOnLocalhost( "WUNDA_BLAU", "Administratoren", "admin", "kif", "mauer", 1, 1280, 1024); } @Override public void editorClosed(final EditorClosedEvent event) { if (EditorSaveStatus.SAVE_SUCCESS == event.getStatus()) { for (final CidsBean deleteBean : removedFotoBeans) { final String fileName = (String)deleteBean.getProperty("url_object_name"); final StringBuilder fileDir = new StringBuilder(); fileDir.append(deleteBean.getProperty("url.url_base_id.prot_prefix").toString()); fileDir.append(deleteBean.getProperty("url.url_base_id.server").toString()); fileDir.append(deleteBean.getProperty("url.url_base_id.path").toString()); try { webDavHelper.deleteFileFromWebDAV(fileName, fileDir.toString()); deleteBean.delete(); } catch (Exception ex) { log.error(ex, ex); } } } else { for (final CidsBean deleteBean : removeNewAddedFotoBean) { final String fileName = (String)deleteBean.getProperty("url.object_name"); final StringBuilder fileDir = new StringBuilder(); fileDir.append(deleteBean.getProperty("url.url_base_id.prot_prefix").toString()); fileDir.append(deleteBean.getProperty("url.url_base_id.server").toString()); fileDir.append(deleteBean.getProperty("url.url_base_id.path").toString()); webDavHelper.deleteFileFromWebDAV(fileName, fileDir.toString()); } } } @Override public boolean prepareForSave() { try { log.info("prepare for save"); final String mauerNummer = (String)cidsBean.getProperty("mauer_nummer"); final String lagebezeichnung = (String)cidsBean.getProperty("lagebezeichnung"); if ((lagebezeichnung == null) || lagebezeichnung.trim().equals("")) { log.warn("lagebezeichnung must not be null or empty"); JOptionPane.showMessageDialog(StaticSwingTools.getParentFrame(this), "Das Feld Lagebezeichnung muss ausgefüllt sein.", "Fehlerhafte Eingaben", JOptionPane.ERROR_MESSAGE); return false; } // check if the mauer nummer is already used for another mauer object if (mauerNummer != null) { final CidsServerSearch search = new MauerNummerSearch(mauerNummer); final Collection res = SessionManager.getProxy() .customServerSearch(SessionManager.getSession().getUser(), search); final ArrayList<ArrayList> tmp = (ArrayList<ArrayList>)res; if (tmp.size() > 0) { final ArrayList resMauer = tmp.get(0); final Integer id = (Integer)resMauer.get(0); final Integer objId = (Integer)cidsBean.getProperty("id"); if (id.intValue() != objId.intValue()) { log.warn("mauernummer " + mauerNummer + "already exists"); JOptionPane.showMessageDialog(StaticSwingTools.getParentFrame(this), "Die angegebene Mauernummer existiert bereits.", "Fehlerhafte Eingaben", JOptionPane.ERROR_MESSAGE); return false; } } } return true; } catch (ConnectionException ex) { Exceptions.printStackTrace(ex); return false; } } /** * DOCUMENT ME! */ private void initMap() { if (cidsBean != null) { final Object geoObj = cidsBean.getProperty("georeferenz.geo_field"); if (geoObj instanceof Geometry) { final Geometry pureGeom = CrsTransformer.transformToGivenCrs((Geometry)geoObj, AlkisConstants.COMMONS.SRS_SERVICE); if (log.isDebugEnabled()) { log.debug("ALKISConstatns.Commons.GeoBUffer: " + AlkisConstants.COMMONS.GEO_BUFFER); } final XBoundingBox box = new XBoundingBox(pureGeom.getEnvelope().buffer( AlkisConstants.COMMONS.GEO_BUFFER)); final double diagonalLength = Math.sqrt((box.getWidth() * box.getWidth()) + (box.getHeight() * box.getHeight())); if (log.isDebugEnabled()) { log.debug("Buffer for map: " + diagonalLength); } final XBoundingBox bufferedBox = new XBoundingBox(box.getGeometry().buffer(diagonalLength)); final Runnable mapRunnable = new Runnable() { @Override public void run() { final ActiveLayerModel mappingModel = new ActiveLayerModel(); mappingModel.setSrs(AlkisConstants.COMMONS.SRS_SERVICE); mappingModel.addHome(new XBoundingBox( bufferedBox.getX1(), bufferedBox.getY1(), bufferedBox.getX2(), bufferedBox.getY2(), AlkisConstants.COMMONS.SRS_SERVICE, true)); final SimpleWMS swms = new SimpleWMS(new SimpleWmsGetMapUrl( AlkisConstants.COMMONS.MAP_CALL_STRING)); swms.setName("Mauer"); final StyledFeature dsf = new DefaultStyledFeature(); dsf.setGeometry(pureGeom); dsf.setFillingPaint(new Color(1, 0, 0, 0.5f)); dsf.setLineWidth(3); dsf.setLinePaint(new Color(1, 0, 0, 1f)); // add the raster layer to the model mappingModel.addLayer(swms); // set the model map.setMappingModel(mappingModel); // initial positioning of the map final int duration = map.getAnimationDuration(); map.setAnimationDuration(0); map.gotoInitialBoundingBox(); // interaction mode map.setInteractionMode(MappingComponent.ZOOM); // finally when all configurations are done ... map.unlock(); map.addCustomInputListener("MUTE", new PBasicInputEventHandler() { @Override public void mouseClicked(final PInputEvent evt) { if (evt.getClickCount() > 1) { final CidsBean bean = cidsBean; ObjectRendererUtils.switchToCismapMap(); ObjectRendererUtils.addBeanGeomAsFeatureToCismapMap(bean, false); } } }); map.setInteractionMode("MUTE"); map.getFeatureCollection().addFeature(dsf); map.setAnimationDuration(duration); } }; if (EventQueue.isDispatchThread()) { mapRunnable.run(); } else { EventQueue.invokeLater(mapRunnable); } } } } /** * DOCUMENT ME! */ private void setEditable() { if (!editable) { RendererTools.makeReadOnly(jScrollPane1); RendererTools.makeReadOnly(jScrollPane2); RendererTools.makeReadOnly(jScrollPane4); RendererTools.makeReadOnly(jScrollPane5); RendererTools.makeReadOnly(jScrollPane6); RendererTools.makeReadOnly(jScrollPane7); RendererTools.makeReadOnly(jScrollPane8); RendererTools.makeReadOnly(jScrollPane9); RendererTools.makeReadOnly(jScrollPane10); RendererTools.makeReadOnly(jScrollPane11); RendererTools.makeReadOnly(jScrollPane12); RendererTools.makeReadOnly(jScrollPane13); RendererTools.makeReadOnly(jScrollPane14); RendererTools.makeReadOnly(jScrollPane15); RendererTools.makeReadOnly(jScrollPane17); RendererTools.makeReadOnly(jspFotoList); RendererTools.makeReadOnly(taLagebeschreibung); RendererTools.makeReadOnly(taNeigung); RendererTools.makeReadOnly(tfUmgebung); RendererTools.makeReadOnly(tfLaenge); RendererTools.makeReadOnly(taBeschreibungAnsicht); RendererTools.makeReadOnly(taBeschreibungGelaender); RendererTools.makeReadOnly(taBeschreibungGruendung); RendererTools.makeReadOnly(taBeschreibungGruendung1); RendererTools.makeReadOnly(taBeschreibungGruendung2); RendererTools.makeReadOnly(taBeschreibungKopf); RendererTools.makeReadOnly(taLagebeschreibung); RendererTools.makeReadOnly(taNeigung); RendererTools.makeReadOnly(taSanMassnahmeAnsicht); RendererTools.makeReadOnly(taSanMassnahmeGelaender); RendererTools.makeReadOnly(taSanMassnahmeGruendung); RendererTools.makeReadOnly(taSanMassnahmeGruendung1); RendererTools.makeReadOnly(taSanMassnahmeGruendung2); RendererTools.makeReadOnly(taSanMassnahmeKopf); RendererTools.makeReadOnly(taBesonderheiten); RendererTools.makeReadOnly(tfLaenge); RendererTools.makeReadOnly(tfSanKostenAnsicht); RendererTools.makeReadOnly(tfSanKostenGelaender); RendererTools.makeReadOnly(tfSanKostenGruendung); RendererTools.makeReadOnly(tfSanKostenGruendung1); RendererTools.makeReadOnly(tfSanKostenGruendung2); RendererTools.makeReadOnly(tfSanKostenKopf); RendererTools.makeReadOnly(tfUmgebung); RendererTools.makeReadOnly(tfZustandAnsicht); RendererTools.makeReadOnly(tfZustandGelaender); RendererTools.makeReadOnly(tfZustandGruendung); RendererTools.makeReadOnly(tfZustandGruendung1); RendererTools.makeReadOnly(tfZustandGruendung2); RendererTools.makeReadOnly(tfZustandKopf); RendererTools.makeReadOnly(tfStaerkeOben); RendererTools.makeReadOnly(tfStaerke_unten); RendererTools.makeReadOnly(tfLastabstand); RendererTools.makeReadOnly(tfHoeheMax); RendererTools.makeReadOnly(tfHoeheMin); RendererTools.makeReadOnly(tfMauerNummer); RendererTools.makeReadOnly(tfLagebezeichnung); RendererTools.makeReadOnly(dcSanierung); RendererTools.makeReadOnly(tfZustandGesamt); RendererTools.makeReadOnly(lstFotos); RendererTools.makeReadOnly(cbEigentuemer); RendererTools.makeReadOnly(cbMaterialtyp); RendererTools.makeReadOnly(cbStuetzmauertyp); RendererTools.makeReadOnly(cbArtErstePruefung); RendererTools.makeReadOnly(cbArtLetztePruefung); RendererTools.makeReadOnly(cbArtNaechstePruefung1); RendererTools.makeReadOnly(cbStandsicherheit); RendererTools.makeReadOnly(cbVerkehrssicherheit); RendererTools.makeReadOnly(cbDauerhaftigkeit); RendererTools.makeReadOnly(cbLastklasse); RendererTools.makeReadOnly(cbMauertyp); RendererTools.makeReadOnly(cbEingriffAnsicht); RendererTools.makeReadOnly(cbEingriffGelaende); RendererTools.makeReadOnly(cbEingriffGelaender); RendererTools.makeReadOnly(cbEingriffGruendung); RendererTools.makeReadOnly(cbEingriffKopf); RendererTools.makeReadOnly(cbEingriffVerformung); RendererTools.makeReadOnly(dcErstePruefung); RendererTools.makeReadOnly(dcLetztePruefung); RendererTools.makeReadOnly(dcNaechstePruefung); RendererTools.makeReadOnly(dcBauwerksbuchfertigstellung); btnAddImg.setVisible(editable); btnRemoveImg.setVisible(editable); } } @Override public JComponent getFooterComponent() { return panFooter; } /** * DOCUMENT ME! */ private void loadFoto() { final Object fotoObj = lstFotos.getSelectedValue(); if (fotoCidsBean != null) { fotoCidsBean.removePropertyChangeListener(listRepaintListener); } if (fotoObj instanceof CidsBean) { fotoCidsBean = (CidsBean)fotoObj; fotoCidsBean.addPropertyChangeListener(listRepaintListener); final Object fileObj = fotoCidsBean.getProperty("url.object_name"); boolean cacheHit = false; if (fileObj != null) { // final String[] file = fileObj.toString().split("/"); // final String object_name = file[file.length - 1]; final SoftReference<BufferedImage> cachedImageRef = IMAGE_CACHE.get(fileObj); if (cachedImageRef != null) { final BufferedImage cachedImage = cachedImageRef.get(); if (cachedImage != null) { cacheHit = true; image = cachedImage; showWait(true); resizeListenerEnabled = true; timer.restart(); } } if (!cacheHit) { CismetThreadPool.execute(new LoadSelectedImageWorker(fileObj.toString())); } } } else { image = null; lblPicture.setIcon(FOLDER_ICON); } } /** * DOCUMENT ME! * * @param tooltip DOCUMENT ME! */ private void indicateError(final String tooltip) { lblPicture.setIcon(ERROR_ICON); lblPicture.setText("Fehler beim Übertragen des Bildes!"); lblPicture.setToolTipText(tooltip); } /** * DOCUMENT ME! * * @param wait DOCUMENT ME! */ private void showWait(final boolean wait) { if (wait) { if (!lblBusy.isBusy()) { // cardLayout.show(pnlFoto, "busy"); lblPicture.setIcon(null); lblBusy.setBusy(true); btnAddImg.setEnabled(false); btnRemoveImg.setEnabled(false); lstFotos.setEnabled(false); btnPrevImg.setEnabled(false); btnNextImg.setEnabled(false); } } else { // cardLayout.show(pnlFoto, "preview"); lblBusy.setBusy(false); lblBusy.setVisible(false); btnAddImg.setEnabled(true); btnRemoveImg.setEnabled(true); lstFotos.setEnabled(true); defineButtonStatus(); } } /** * DOCUMENT ME! * * @param fileName DOCUMENT ME! * * @return DOCUMENT ME! */ private BufferedImage downloadImageFromUrl(final String fileName) { try { final URL url = new URL(fileName); final BufferedImage img = ImageIO.read(url); return img; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; } /** * DOCUMENT ME! * * @param fileName DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! */ private BufferedImage downloadImageFromWebDAV(final String fileName) throws Exception { final InputStream iStream = webDavHelper.getFileFromWebDAV(fileName, WEB_DAV_DIRECTORY); try { final ImageInputStream iiStream = ImageIO.createImageInputStream(iStream); final Iterator<ImageReader> itReader = ImageIO.getImageReaders(iiStream); final ImageReader reader = itReader.next(); final ProgressMonitor monitor = new ProgressMonitor(this, "Bild wird übertragen...", "", 0, 100); // monitor.setMillisToPopup(500); reader.addIIOReadProgressListener(new IIOReadProgressListener() { @Override public void sequenceStarted(final ImageReader source, final int minIndex) { } @Override public void sequenceComplete(final ImageReader source) { } @Override public void imageStarted(final ImageReader source, final int imageIndex) { monitor.setProgress(monitor.getMinimum()); } @Override public void imageProgress(final ImageReader source, final float percentageDone) { if (monitor.isCanceled()) { try { iiStream.close(); } catch (IOException ex) { // NOP } } else { monitor.setProgress(Math.round(percentageDone)); } } @Override public void imageComplete(final ImageReader source) { monitor.setProgress(monitor.getMaximum()); } @Override public void thumbnailStarted(final ImageReader source, final int imageIndex, final int thumbnailIndex) { } @Override public void thumbnailProgress(final ImageReader source, final float percentageDone) { } @Override public void thumbnailComplete(final ImageReader source) { } @Override public void readAborted(final ImageReader source) { monitor.close(); } }); final ImageReadParam param = reader.getDefaultReadParam(); reader.setInput(iiStream, true, true); final BufferedImage result; try { result = reader.read(0, param); } finally { reader.dispose(); iiStream.close(); } return result; } finally { IOUtils.closeQuietly(iStream); } } /** * DOCUMENT ME! */ public void defineButtonStatus() { final int selectedIdx = lstFotos.getSelectedIndex(); btnPrevImg.setEnabled(selectedIdx > 0); btnNextImg.setEnabled((selectedIdx < (lstFotos.getModel().getSize() - 1)) && (selectedIdx > -1)); } /** * DOCUMENT ME! * * @param bi DOCUMENT ME! * @param component DOCUMENT ME! * @param insetX DOCUMENT ME! * @param insetY DOCUMENT ME! * * @return DOCUMENT ME! */ public static Image adjustScale(final BufferedImage bi, final JComponent component, final int insetX, final int insetY) { final double scalex = (double)component.getWidth() / bi.getWidth(); final double scaley = (double)component.getHeight() / bi.getHeight(); final double scale = Math.min(scalex, scaley); if (scale <= 1d) { return bi.getScaledInstance((int)(bi.getWidth() * scale) - insetX, (int)(bi.getHeight() * scale) - insetY, Image.SCALE_SMOOTH); } else { return bi; } } @Override public JComponent getTitleComponent() { return panTitle; } @Override public Border getTitleBorder() { return new EmptyBorder(new Insets(10, 20, 10, 25)); } @Override public Border getFooterBorder() { return new EmptyBorder(new Insets(0, 0, 10, 0)); } @Override public Border getCenterrBorder() { return new EmptyBorder(new Insets(10, 10, 10, 10)); } //~ Inner Classes ---------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ final class LoadSelectedImageWorker extends SwingWorker<BufferedImage, Void> { //~ Instance fields ---------------------------------------------------- private final String file; //~ Constructors ------------------------------------------------------- /** * Creates a new LoadSelectedImageWorker object. * * @param toLoad DOCUMENT ME! */ public LoadSelectedImageWorker(final String toLoad) { this.file = toLoad; lblPicture.setText(""); lblPicture.setToolTipText(null); showWait(true); } //~ Methods ------------------------------------------------------------ @Override protected BufferedImage doInBackground() throws Exception { if ((file != null) && (file.length() > 0)) { return downloadImageFromWebDAV(file); // return downloadImageFromUrl(file); } return null; } @Override protected void done() { try { image = get(); if (image != null) { IMAGE_CACHE.put(file, new SoftReference<BufferedImage>(image)); resizeListenerEnabled = true; timer.restart(); } else { indicateError("Bild konnte nicht geladen werden: Unbekanntes Bildformat"); } } catch (InterruptedException ex) { image = null; log.warn(ex, ex); } catch (ExecutionException ex) { image = null; log.error(ex, ex); String causeMessage = ""; final Throwable cause = ex.getCause(); if (cause != null) { causeMessage = cause.getMessage(); } indicateError(causeMessage); } finally { if (image == null) { showWait(false); } } } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ final class ImageResizeWorker extends SwingWorker<ImageIcon, Void> { //~ Constructors ------------------------------------------------------- /** * Creates a new ImageResizeWorker object. */ public ImageResizeWorker() { // TODO image im EDT auslesen und final speichern! if (image != null) { lblPicture.setText("Wird neu skaliert..."); lstFotos.setEnabled(false); } // log.fatal("RESIZE Image!", new Exception()); } //~ Methods ------------------------------------------------------------ @Override protected ImageIcon doInBackground() throws Exception { if (image != null) { // if (panButtons.getSize().getWidth() + 10 < panPreview.getSize().getWidth()) { // ImageIcon result = new ImageIcon(ImageUtil.adjustScale(image, panPreview, 20, 20)); final ImageIcon result = new ImageIcon(adjustScale(image, pnlFoto, 20, 20)); return result; // } else { // return new ImageIcon(image); // } } else { return null; } } @Override protected void done() { if (!isCancelled()) { try { resizeListenerEnabled = false; final ImageIcon result = get(); lblPicture.setIcon(result); lblPicture.setText(""); lblPicture.setToolTipText(null); } catch (InterruptedException ex) { log.warn(ex, ex); } catch (ExecutionException ex) { log.error(ex, ex); lblPicture.setText("Fehler beim Skalieren!"); } finally { showWait(false); if (currentResizeWorker == this) { currentResizeWorker = null; } resizeListenerEnabled = true; } } } } /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ final class ImageUploadWorker extends SwingWorker<Collection<CidsBean>, Void> { //~ Instance fields ---------------------------------------------------- private final Collection<File> fotos; //~ Constructors ------------------------------------------------------- /** * Creates a new ImageUploadWorker object. * * @param fotos DOCUMENT ME! */ public ImageUploadWorker(final Collection<File> fotos) { this.fotos = fotos; lblPicture.setText(""); lblPicture.setToolTipText(null); showWait(true); } //~ Methods ------------------------------------------------------------ @Override protected Collection<CidsBean> doInBackground() throws Exception { final Collection<CidsBean> newBeans = new ArrayList<CidsBean>(); int i = lstFotos.getModel().getSize() + 1; for (final File imageFile : fotos) { // final String webFileName = WebDavHelper.generateWebDAVFileName(FILE_PREFIX, imageFile); webDavHelper.uploadFileToWebDAV( imageFile.getName(), imageFile, WEB_DAV_DIRECTORY, MauerEditor.this); final MetaClass MB_MC = ClassCacheMultiple.getMetaClass("WUNDA_BLAU", "url_base"); String query = "SELECT " + MB_MC.getID() + ", " + MB_MC.getPrimaryKey() + " "; query += "FROM " + MB_MC.getTableName(); query += " WHERE server = 's102x003/WebDAV' and path = '/cids/mauern/bilder/'; "; final MetaObject[] metaObjects = SessionManager.getProxy().getMetaObjectByQuery(query, 0); final CidsBean url = CidsBeanSupport.createNewCidsBeanFromTableName("url"); url.setProperty("url_base_id", metaObjects[0].getBean()); url.setProperty("object_name", imageFile.getName()); final CidsBean newFotoBean = CidsBeanSupport.createNewCidsBeanFromTableName("Mauer_bilder"); newFotoBean.setProperty("laufende_nummer", i); newFotoBean.setProperty("name", imageFile.getName()); newFotoBean.setProperty("url", url); newBeans.add(newFotoBean); i++; } return newBeans; } @Override protected void done() { try { final Collection<CidsBean> newBeans = get(); if (!newBeans.isEmpty()) { final List<CidsBean> oldBeans = CidsBeanSupport.getBeanCollectionFromProperty(cidsBean, "bilder"); oldBeans.addAll(newBeans); removeNewAddedFotoBean.addAll(newBeans); lstFotos.setSelectedValue(newBeans.iterator().next(), true); } else { lblPicture.setIcon(FOLDER_ICON); } } catch (InterruptedException ex) { log.warn(ex, ex); } catch (ExecutionException ex) { log.error(ex, ex); } finally { showWait(false); } } } }
true
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); panFooter = new javax.swing.JPanel(); panLeft = new javax.swing.JPanel(); lblInfo = new javax.swing.JLabel(); btnInfo = new javax.swing.JButton(); panRight = new javax.swing.JPanel(); btnImages = new javax.swing.JButton(); lblImages = new javax.swing.JLabel(); panTitle = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); btnReport = new javax.swing.JButton(); pnlCard1 = new javax.swing.JPanel(); pnlAllgemein = new de.cismet.tools.gui.RoundedPanel(); pnlHeaderAllgemein = new de.cismet.tools.gui.SemiRoundedPanel(); lblHeaderAllgemein = new javax.swing.JLabel(); jspAllgemeineInfos = new javax.swing.JScrollPane(); pnlLeft = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); taNeigung = new javax.swing.JTextArea(); cbMaterialtyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblStaerke = new javax.swing.JLabel(); lblStuetzmauer = new javax.swing.JLabel(); cbEigentuemer = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblLagebeschreibung = new javax.swing.JLabel(); lblHoeheMin = new javax.swing.JLabel(); tfUmgebung = new javax.swing.JTextField(); pnlHoehe = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); tfHoeheMin = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); tfHoeheMax = new javax.swing.JTextField(); lblFiller11 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); lblFiller7 = new javax.swing.JLabel(); lblEigentuemer = new javax.swing.JLabel(); lblNeigung = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); taLagebeschreibung = new javax.swing.JTextArea(); lblLaenge = new javax.swing.JLabel(); lblUmgebung = new javax.swing.JLabel(); tfLaenge = new javax.swing.JTextField(); lblMaterialTyp = new javax.swing.JLabel(); cbStuetzmauertyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel1 = new javax.swing.JPanel(); lblStaerkeUnten = new javax.swing.JLabel(); tfStaerke_unten = new javax.swing.JTextField(); lblStaerkeOben = new javax.swing.JLabel(); tfStaerkeOben = new javax.swing.JTextField(); lblBesonderheiten = new javax.swing.JLabel(); jScrollPane17 = new javax.swing.JScrollPane(); taBesonderheiten = new javax.swing.JTextArea(); lblLagebezeichnung = new javax.swing.JLabel(); tfLagebezeichnung = new javax.swing.JTextField(); lblMauerNummer = new javax.swing.JLabel(); tfMauerNummer = new javax.swing.JTextField(); lblMauertyp = new javax.swing.JLabel(); cbMauertyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblLastabstand = new javax.swing.JLabel(); tfLastabstand = new javax.swing.JTextField(); lblLastklasse = new javax.swing.JLabel(); lblDauerhaftigkeit = new javax.swing.JLabel(); lblVerkehrssicherheit = new javax.swing.JLabel(); lblStandsicherheit = new javax.swing.JLabel(); lblPruefung1 = new javax.swing.JLabel(); lblLetztePruefung = new javax.swing.JLabel(); lblNaechstePruefung = new javax.swing.JLabel(); lblBauwerksbuchfertigstellung = new javax.swing.JLabel(); lblSanierung = new javax.swing.JLabel(); if (editable) { lblGeom = new javax.swing.JLabel(); } if (editable) { cbGeom = new DefaultCismapGeometryComboBoxEditor(); } jPanel5 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); dcBauwerksbuchfertigstellung = new de.cismet.cids.editors.DefaultBindableDateChooser(); lblFiller10 = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); dcNaechstePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel16 = new javax.swing.JLabel(); cbArtNaechstePruefung1 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel6 = new javax.swing.JPanel(); jLabel13 = new javax.swing.JLabel(); dcLetztePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel14 = new javax.swing.JLabel(); cbArtLetztePruefung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel2 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); dcErstePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel6 = new javax.swing.JLabel(); cbArtErstePruefung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbStandsicherheit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbVerkehrssicherheit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbDauerhaftigkeit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbLastklasse = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblZustandGesamt = new javax.swing.JLabel(); tfZustandGesamt = new javax.swing.JTextField(); lblFiller8 = new javax.swing.JLabel(); dcSanierung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); roundedScrollPanel = new de.cismet.tools.gui.RoundedPanel(); jScrollPane3 = new javax.swing.JScrollPane(); pnlScrollPane = new javax.swing.JPanel(); pnlGelaender = new de.cismet.tools.gui.RoundedPanel(); pnlGelaenderHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblGelaenderHeader = new javax.swing.JLabel(); lblFiller = new javax.swing.JLabel(); lblBeschreibungGelaender = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); taBeschreibungGelaender = new javax.swing.JTextArea(); lblZustandGelaender = new javax.swing.JLabel(); lblSanKostenGelaender = new javax.swing.JLabel(); lblSanMassnahmenGelaender = new javax.swing.JLabel(); lblEingriffGeleander = new javax.swing.JLabel(); tfZustandGelaender = new javax.swing.JTextField(); tfSanKostenGelaender = new javax.swing.JTextField(); jScrollPane5 = new javax.swing.JScrollPane(); taSanMassnahmeGelaender = new javax.swing.JTextArea(); cbEingriffGelaender = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlKopf = new de.cismet.tools.gui.RoundedPanel(); pnlKopfHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpHeader = new javax.swing.JLabel(); lblFiller1 = new javax.swing.JLabel(); lblbeschreibungKopf = new javax.swing.JLabel(); jScrollPane6 = new javax.swing.JScrollPane(); taBeschreibungKopf = new javax.swing.JTextArea(); lblZustandKopf = new javax.swing.JLabel(); lblSanMassnahmenKopf = new javax.swing.JLabel(); lblSanKostenKopf = new javax.swing.JLabel(); lblEingriffKopf = new javax.swing.JLabel(); tfZustandKopf = new javax.swing.JTextField(); tfSanKostenKopf = new javax.swing.JTextField(); jScrollPane7 = new javax.swing.JScrollPane(); taSanMassnahmeKopf = new javax.swing.JTextArea(); cbEingriffKopf = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlAnsicht = new de.cismet.tools.gui.RoundedPanel(); pnlKopfAnsicht = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht = new javax.swing.JLabel(); lblFiller3 = new javax.swing.JLabel(); lblbeschreibungAnsicht = new javax.swing.JLabel(); jScrollPane8 = new javax.swing.JScrollPane(); taBeschreibungAnsicht = new javax.swing.JTextArea(); lblZustandAnsicht = new javax.swing.JLabel(); lblSanMassnahmenAnsicht = new javax.swing.JLabel(); lblSanKostenAnsicht = new javax.swing.JLabel(); lblEingriffAnsicht = new javax.swing.JLabel(); tfZustandAnsicht = new javax.swing.JTextField(); tfSanKostenAnsicht = new javax.swing.JTextField(); jScrollPane9 = new javax.swing.JScrollPane(); taSanMassnahmeAnsicht = new javax.swing.JTextArea(); cbEingriffAnsicht = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlGruendung = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht1 = new javax.swing.JLabel(); lblFiller4 = new javax.swing.JLabel(); lblbeschreibungGruendung = new javax.swing.JLabel(); jScrollPane10 = new javax.swing.JScrollPane(); taBeschreibungGruendung = new javax.swing.JTextArea(); lblZustandGruendung = new javax.swing.JLabel(); lblSanMassnahmenGruendung = new javax.swing.JLabel(); lblSanKostenAnsicht1 = new javax.swing.JLabel(); lblEingriffAnsicht1 = new javax.swing.JLabel(); tfZustandGruendung = new javax.swing.JTextField(); tfSanKostenGruendung = new javax.swing.JTextField(); jScrollPane11 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung = new javax.swing.JTextArea(); cbEingriffGruendung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlGelaende = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader1 = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht2 = new javax.swing.JLabel(); lblFiller5 = new javax.swing.JLabel(); lblbeschreibungGruendung1 = new javax.swing.JLabel(); jScrollPane12 = new javax.swing.JScrollPane(); taBeschreibungGruendung1 = new javax.swing.JTextArea(); lblZustandGruendung1 = new javax.swing.JLabel(); lblSanMassnahmenGruendung1 = new javax.swing.JLabel(); lblSanKostenAnsicht2 = new javax.swing.JLabel(); lblEingriffAnsicht2 = new javax.swing.JLabel(); tfZustandGruendung1 = new javax.swing.JTextField(); tfSanKostenGruendung1 = new javax.swing.JTextField(); jScrollPane13 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung1 = new javax.swing.JTextArea(); cbEingriffGelaende = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlVerformung = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht3 = new javax.swing.JLabel(); lblFiller6 = new javax.swing.JLabel(); lblbeschreibungGruendung2 = new javax.swing.JLabel(); jScrollPane14 = new javax.swing.JScrollPane(); taBeschreibungGruendung2 = new javax.swing.JTextArea(); lblZustandGruendung2 = new javax.swing.JLabel(); lblSanMassnahmenGruendung2 = new javax.swing.JLabel(); lblSanKostenAnsicht3 = new javax.swing.JLabel(); lblEingriffAnsicht3 = new javax.swing.JLabel(); tfZustandGruendung2 = new javax.swing.JTextField(); tfSanKostenGruendung2 = new javax.swing.JTextField(); jScrollPane15 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung2 = new javax.swing.JTextArea(); cbEingriffVerformung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlCard2 = new javax.swing.JPanel(); pnlFotos = new de.cismet.tools.gui.RoundedPanel(); pnlHeaderFotos = new de.cismet.tools.gui.SemiRoundedPanel(); lblHeaderFotos = new javax.swing.JLabel(); lblFiller9 = new javax.swing.JLabel(); lblFotos = new javax.swing.JLabel(); jspFotoList = new javax.swing.JScrollPane(); lstFotos = new javax.swing.JList(); pnlCtrlButtons = new javax.swing.JPanel(); btnAddImg = new javax.swing.JButton(); btnRemoveImg = new javax.swing.JButton(); pnlVorschau = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblVorschau = new javax.swing.JLabel(); pnlFoto = new javax.swing.JPanel(); lblPicture = new javax.swing.JLabel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(new Dimension(75, 75)); pnlCtrlBtn = new javax.swing.JPanel(); btnPrevImg = new javax.swing.JButton(); btnNextImg = new javax.swing.JButton(); pnlMap = new javax.swing.JPanel(); panFooter.setOpaque(false); panFooter.setLayout(new java.awt.GridBagLayout()); panLeft.setOpaque(false); lblInfo.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N lblInfo.setForeground(new java.awt.Color(255, 255, 255)); lblInfo.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblInfo.text")); // NOI18N lblInfo.setEnabled(false); panLeft.add(lblInfo); btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-left.png"))); // NOI18N btnInfo.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnInfo.text")); // NOI18N btnInfo.setBorderPainted(false); btnInfo.setContentAreaFilled(false); btnInfo.setEnabled(false); btnInfo.setFocusPainted(false); btnInfo.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnInfoActionPerformed(evt); } }); panLeft.add(btnInfo); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; panFooter.add(panLeft, gridBagConstraints); panRight.setOpaque(false); btnImages.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-right.png"))); // NOI18N btnImages.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnImages.text")); // NOI18N btnImages.setBorderPainted(false); btnImages.setContentAreaFilled(false); btnImages.setFocusPainted(false); btnImages.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnImagesActionPerformed(evt); } }); panRight.add(btnImages); lblImages.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N lblImages.setForeground(new java.awt.Color(255, 255, 255)); lblImages.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblImages.text")); // NOI18N panRight.add(lblImages); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; panFooter.add(panRight, gridBagConstraints); panTitle.setOpaque(false); panTitle.setLayout(new java.awt.GridBagLayout()); lblTitle.setFont(new java.awt.Font("DejaVu Sans", 1, 18)); // NOI18N lblTitle.setForeground(new java.awt.Color(255, 255, 255)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; panTitle.add(lblTitle, gridBagConstraints); btnReport.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/icons/printer.png"))); // NOI18N btnReport.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnReport.text")); // NOI18N btnReport.setToolTipText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.btnReport.toolTipText")); // NOI18N btnReport.setBorderPainted(false); btnReport.setContentAreaFilled(false); btnReport.setFocusPainted(false); btnReport.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnReportActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; panTitle.add(btnReport, gridBagConstraints); setMaximumSize(new java.awt.Dimension(1190, 1625)); setMinimumSize(new java.awt.Dimension(807, 485)); setVerifyInputWhenFocusTarget(false); setLayout(new java.awt.CardLayout()); pnlCard1.setOpaque(false); pnlCard1.setLayout(new java.awt.GridBagLayout()); pnlAllgemein.setMinimumSize(new java.awt.Dimension(540, 500)); pnlAllgemein.setPreferredSize(new java.awt.Dimension(540, 800)); pnlAllgemein.setLayout(new java.awt.GridBagLayout()); pnlHeaderAllgemein.setBackground(new java.awt.Color(51, 51, 51)); pnlHeaderAllgemein.setMinimumSize(new java.awt.Dimension(109, 24)); pnlHeaderAllgemein.setPreferredSize(new java.awt.Dimension(109, 24)); pnlHeaderAllgemein.setLayout(new java.awt.FlowLayout()); lblHeaderAllgemein.setForeground(new java.awt.Color(255, 255, 255)); lblHeaderAllgemein.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblHeaderAllgemein.text")); // NOI18N pnlHeaderAllgemein.add(lblHeaderAllgemein); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlAllgemein.add(pnlHeaderAllgemein, gridBagConstraints); jspAllgemeineInfos.setBorder(null); jspAllgemeineInfos.setMinimumSize(new java.awt.Dimension(500, 520)); jspAllgemeineInfos.setOpaque(false); jspAllgemeineInfos.setPreferredSize(new java.awt.Dimension(500, 880)); pnlLeft.setMinimumSize(new java.awt.Dimension(500, 790)); pnlLeft.setOpaque(false); pnlLeft.setPreferredSize(new java.awt.Dimension(500, 850)); pnlLeft.setLayout(new java.awt.GridBagLayout()); jScrollPane2.setMinimumSize(new java.awt.Dimension(26, 50)); jScrollPane2.setPreferredSize(new java.awt.Dimension(0, 50)); taNeigung.setLineWrap(true); taNeigung.setMinimumSize(new java.awt.Dimension(500, 34)); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.neigung}"), taNeigung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane2.setViewportView(taNeigung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jScrollPane2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.materialtyp}"), cbMaterialtyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbMaterialtyp, gridBagConstraints); lblStaerke.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblStaerke.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStaerke, gridBagConstraints); lblStuetzmauer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStuetzmauer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStuetzmauer, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.eigentuemer}"), cbEigentuemer, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 8; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbEigentuemer, gridBagConstraints); lblLagebeschreibung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLagebeschreibung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLagebeschreibung, gridBagConstraints); lblHoeheMin.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblHoeheMin.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 9; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblHoeheMin, gridBagConstraints); tfUmgebung.setMinimumSize(new java.awt.Dimension(100, 20)); tfUmgebung.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.umgebung}"), tfUmgebung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfUmgebung, gridBagConstraints); pnlHoehe.setOpaque(false); pnlHoehe.setLayout(new java.awt.GridBagLayout()); jLabel1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlHoehe.add(jLabel1, gridBagConstraints); tfHoeheMin.setMinimumSize(new java.awt.Dimension(50, 20)); tfHoeheMin.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_min}"), tfHoeheMin, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 20); pnlHoehe.add(tfHoeheMin, gridBagConstraints); jLabel3.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlHoehe.add(jLabel3, gridBagConstraints); tfHoeheMax.setMinimumSize(new java.awt.Dimension(50, 20)); tfHoeheMax.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_max}"), tfHoeheMax, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0); pnlHoehe.add(tfHoeheMax, gridBagConstraints); lblFiller11.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller11.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlHoehe.add(lblFiller11, gridBagConstraints); jPanel3.setOpaque(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jLabel4.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel4.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; jPanel3.add(jLabel4, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_ONCE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe}"), jLabel2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 0); jPanel3.add(jLabel2, gridBagConstraints); lblFiller7.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller7.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel3.add(lblFiller7, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlHoehe.add(jPanel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 9; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(pnlHoehe, gridBagConstraints); lblEigentuemer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEigentuemer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblEigentuemer, gridBagConstraints); lblNeigung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblNeigung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblNeigung, gridBagConstraints); jScrollPane1.setMinimumSize(new java.awt.Dimension(26, 40)); jScrollPane1.setPreferredSize(new java.awt.Dimension(0, 50)); jScrollPane1.setRequestFocusEnabled(false); taLagebeschreibung.setLineWrap(true); taLagebeschreibung.setMaximumSize(new java.awt.Dimension(500, 34)); taLagebeschreibung.setMinimumSize(new java.awt.Dimension(500, 34)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebeschreibung}"), taLagebeschreibung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane1.setViewportView(taLagebeschreibung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jScrollPane1, gridBagConstraints); lblLaenge.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblLaenge.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 11; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLaenge, gridBagConstraints); lblUmgebung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblUmgebung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblUmgebung, gridBagConstraints); tfLaenge.setMinimumSize(new java.awt.Dimension(100, 20)); tfLaenge.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laenge}"), tfLaenge, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 11; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLaenge, gridBagConstraints); lblMaterialTyp.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblMaterialTyp.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMaterialTyp, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.stuetzmauertyp}"), cbStuetzmauertyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbStuetzmauertyp, gridBagConstraints); jPanel1.setOpaque(false); jPanel1.setLayout(new java.awt.GridBagLayout()); lblStaerkeUnten.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStaerkeUnten.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(lblStaerkeUnten, gridBagConstraints); tfStaerke_unten.setMinimumSize(new java.awt.Dimension(50, 20)); tfStaerke_unten.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.staerke_unten}"), tfStaerke_unten, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); tfStaerke_unten.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { tfStaerke_untenActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel1.add(tfStaerke_unten, gridBagConstraints); lblStaerkeOben.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStaerkeOben.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(lblStaerkeOben, gridBagConstraints); tfStaerkeOben.setMinimumSize(new java.awt.Dimension(50, 20)); tfStaerkeOben.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.staerke_oben}"), tfStaerkeOben, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; jPanel1.add(tfStaerkeOben, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel1, gridBagConstraints); lblBesonderheiten.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBesonderheiten.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 12; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblBesonderheiten, gridBagConstraints); jScrollPane17.setMinimumSize(new java.awt.Dimension(26, 50)); jScrollPane17.setPreferredSize(new java.awt.Dimension(0, 50)); taBesonderheiten.setLineWrap(true); taBesonderheiten.setMinimumSize(new java.awt.Dimension(500, 34)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.besonderheiten}"), taBesonderheiten, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane17.setViewportView(taBesonderheiten); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 12; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 10); pnlLeft.add(jScrollPane17, gridBagConstraints); lblLagebezeichnung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLagebezeichnung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLagebezeichnung, gridBagConstraints); tfLagebezeichnung.setMinimumSize(new java.awt.Dimension(100, 20)); tfLagebezeichnung.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebezeichnung}"), tfLagebezeichnung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLagebezeichnung, gridBagConstraints); lblMauerNummer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblMauerNummer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMauerNummer, gridBagConstraints); tfMauerNummer.setMinimumSize(new java.awt.Dimension(150, 20)); tfMauerNummer.setPreferredSize(new java.awt.Dimension(150, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.mauer_nummer}"), tfMauerNummer, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfMauerNummer, gridBagConstraints); lblMauertyp.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblMauertyp.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMauertyp, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.mauertyp}"), cbMauertyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbMauertyp, gridBagConstraints); lblLastabstand.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLastabstand.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 13; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLastabstand, gridBagConstraints); tfLastabstand.setMinimumSize(new java.awt.Dimension(100, 20)); tfLastabstand.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lastabstand}"), tfLastabstand, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 13; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLastabstand, gridBagConstraints); lblLastklasse.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLastklasse.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 14; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLastklasse, gridBagConstraints); lblDauerhaftigkeit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblDauerhaftigkeit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 15; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblDauerhaftigkeit, gridBagConstraints); lblVerkehrssicherheit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblVerkehrssicherheit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 16; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblVerkehrssicherheit, gridBagConstraints); lblStandsicherheit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStandsicherheit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 17; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStandsicherheit, gridBagConstraints); lblPruefung1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblPruefung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 18; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblPruefung1, gridBagConstraints); lblLetztePruefung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLetztePruefung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 19; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLetztePruefung, gridBagConstraints); lblNaechstePruefung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblNaechstePruefung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 20; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblNaechstePruefung, gridBagConstraints); lblBauwerksbuchfertigstellung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBauwerksbuchfertigstellung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 21; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblBauwerksbuchfertigstellung, gridBagConstraints); lblSanierung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblSanierung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 22; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblSanierung, gridBagConstraints); if (editable) { lblGeom.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblGeom.text")); // NOI18N } if (editable) { gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 24; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblGeom, gridBagConstraints); } if (editable) { cbGeom.setMinimumSize(new java.awt.Dimension(41, 25)); cbGeom.setPreferredSize(new java.awt.Dimension(41, 25)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.georeferenz}"), cbGeom, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cbGeom).getConverter()); bindingGroup.addBinding(binding); } if (editable) { gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 24; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbGeom, gridBagConstraints); } jPanel5.setOpaque(false); jPanel5.setLayout(new java.awt.GridBagLayout()); jLabel11.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel11.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel5.add(jLabel11, gridBagConstraints); dcBauwerksbuchfertigstellung.setMinimumSize(new java.awt.Dimension(124, 20)); dcBauwerksbuchfertigstellung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bauwerksbuchfertigstellung}"), dcBauwerksbuchfertigstellung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcBauwerksbuchfertigstellung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel5.add(dcBauwerksbuchfertigstellung, gridBagConstraints); lblFiller10.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller10.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel5.add(lblFiller10, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 21; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel5, gridBagConstraints); jPanel7.setOpaque(false); jPanel7.setLayout(new java.awt.GridBagLayout()); jLabel15.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel15.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel7.add(jLabel15, gridBagConstraints); dcNaechstePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcNaechstePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_naechste_pruefung}"), dcNaechstePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcNaechstePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel7.add(dcNaechstePruefung, gridBagConstraints); jLabel16.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel16.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel7.add(jLabel16, gridBagConstraints); cbArtNaechstePruefung1.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtNaechstePruefung1.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_naechste_pruefung}"), cbArtNaechstePruefung1, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel7.add(cbArtNaechstePruefung1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 20; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel7, gridBagConstraints); jPanel6.setOpaque(false); jPanel6.setLayout(new java.awt.GridBagLayout()); jLabel13.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel13.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel6.add(jLabel13, gridBagConstraints); dcLetztePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcLetztePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_letzte_pruefung}"), dcLetztePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcLetztePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel6.add(dcLetztePruefung, gridBagConstraints); jLabel14.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel14.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel6.add(jLabel14, gridBagConstraints); cbArtLetztePruefung.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtLetztePruefung.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_letzte_pruefung}"), cbArtLetztePruefung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel6.add(cbArtLetztePruefung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 19; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel6, gridBagConstraints); jPanel2.setOpaque(false); jPanel2.setLayout(new java.awt.GridBagLayout()); jLabel5.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel5.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel2.add(jLabel5, gridBagConstraints); dcErstePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcErstePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_erste_pruefung}"), dcErstePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcErstePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel2.add(dcErstePruefung, gridBagConstraints); jLabel6.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel6.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel2.add(jLabel6, gridBagConstraints); cbArtErstePruefung.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtErstePruefung.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_erste_pruefung}"), cbArtErstePruefung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel2.add(cbArtErstePruefung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 18; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.standsicherheit}"), cbStandsicherheit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 17; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbStandsicherheit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.verkehrssicherheit}"), cbVerkehrssicherheit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 16; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbVerkehrssicherheit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.dauerhaftigkeit}"), cbDauerhaftigkeit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 15; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbDauerhaftigkeit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lastklasse}"), cbLastklasse, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 14; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbLastklasse, gridBagConstraints); lblZustandGesamt.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGesamt.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 23; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblZustandGesamt, gridBagConstraints); tfZustandGesamt.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGesamt.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gesamt}"), tfZustandGesamt, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new DoubleNumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 23; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfZustandGesamt, gridBagConstraints); lblFiller8.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller8.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 25; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; pnlLeft.add(lblFiller8, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.sanierung}"), dcSanierung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 22; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(dcSanierung, gridBagConstraints); jspAllgemeineInfos.setViewportView(pnlLeft); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlAllgemein.add(jspAllgemeineInfos, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 0.5; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCard1.add(pnlAllgemein, gridBagConstraints); roundedScrollPanel.setBackground(new java.awt.Color(254, 254, 254)); roundedScrollPanel.setForeground(new java.awt.Color(254, 254, 254)); roundedScrollPanel.setMinimumSize(new java.awt.Dimension(500, 26)); roundedScrollPanel.setPreferredSize(new java.awt.Dimension(500, 120)); roundedScrollPanel.setLayout(new java.awt.GridBagLayout()); jScrollPane3.setBackground(new java.awt.Color(254, 254, 254)); jScrollPane3.setBorder(null); jScrollPane3.setFocusable(false); jScrollPane3.setMinimumSize(new java.awt.Dimension(500, 26)); jScrollPane3.setOpaque(false); jScrollPane3.setPreferredSize(new java.awt.Dimension(600, 120)); pnlScrollPane.setBackground(new java.awt.Color(254, 254, 254)); pnlScrollPane.setFocusable(false); pnlScrollPane.setOpaque(false); pnlScrollPane.setLayout(new java.awt.GridBagLayout()); pnlGelaender.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGelaender.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGelaender.setLayout(new java.awt.GridBagLayout()); pnlGelaenderHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlGelaenderHeader.setLayout(new java.awt.FlowLayout()); lblGelaenderHeader.setForeground(new java.awt.Color(255, 255, 255)); lblGelaenderHeader.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblGelaenderHeader.text")); // NOI18N pnlGelaenderHeader.add(lblGelaenderHeader); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGelaender.add(pnlGelaenderHeader, gridBagConstraints); lblFiller.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGelaender.add(lblFiller, gridBagConstraints); lblBeschreibungGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBeschreibungGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGelaender.add(lblBeschreibungGelaender, gridBagConstraints); jScrollPane4.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane4.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGelaender.setLineWrap(true); taBeschreibungGelaender.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gelaender}"), taBeschreibungGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane4.setViewportView(taBeschreibungGelaender); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGelaender.add(jScrollPane4, gridBagConstraints); lblZustandGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblZustandGelaender, gridBagConstraints); lblSanKostenGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblSanKostenGelaender, gridBagConstraints); lblSanMassnahmenGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblSanMassnahmenGelaender, gridBagConstraints); lblEingriffGeleander.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffGeleander.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblEingriffGeleander, gridBagConstraints); tfZustandGelaender.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGelaender.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gelaender}"), tfZustandGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaender.add(tfZustandGelaender, gridBagConstraints); tfSanKostenGelaender.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGelaender.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gelaender}"), tfSanKostenGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaender.add(tfSanKostenGelaender, gridBagConstraints); jScrollPane5.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane5.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeGelaender.setLineWrap(true); taSanMassnahmeGelaender.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gelaender}"), taSanMassnahmeGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane5.setViewportView(taSanMassnahmeGelaender); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaender.add(jScrollPane5, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gelaender}"), cbEingriffGelaender, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaender.add(cbEingriffGelaender, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGelaender, gridBagConstraints); pnlKopf.setMinimumSize(new java.awt.Dimension(450, 300)); pnlKopf.setPreferredSize(new java.awt.Dimension(450, 300)); pnlKopf.setLayout(new java.awt.GridBagLayout()); pnlKopfHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlKopfHeader.setLayout(new java.awt.FlowLayout()); lblKofpHeader.setForeground(new java.awt.Color(255, 255, 255)); lblKofpHeader.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpHeader.text")); // NOI18N pnlKopfHeader.add(lblKofpHeader); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlKopf.add(pnlKopfHeader, gridBagConstraints); lblFiller1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlKopf.add(lblFiller1, gridBagConstraints); lblbeschreibungKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlKopf.add(lblbeschreibungKopf, gridBagConstraints); jScrollPane6.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane6.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungKopf.setLineWrap(true); taBeschreibungKopf.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_kopf}"), taBeschreibungKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane6.setViewportView(taBeschreibungKopf); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlKopf.add(jScrollPane6, gridBagConstraints); lblZustandKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblZustandKopf, gridBagConstraints); lblSanMassnahmenKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblSanMassnahmenKopf, gridBagConstraints); lblSanKostenKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblSanKostenKopf, gridBagConstraints); lblEingriffKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblEingriffKopf, gridBagConstraints); tfZustandKopf.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandKopf.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_kopf}"), tfZustandKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlKopf.add(tfZustandKopf, gridBagConstraints); tfSanKostenKopf.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenKopf.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_kopf}"), tfSanKostenKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlKopf.add(tfSanKostenKopf, gridBagConstraints); jScrollPane7.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane7.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeKopf.setLineWrap(true); taSanMassnahmeKopf.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_kopf}"), taSanMassnahmeKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane7.setViewportView(taSanMassnahmeKopf); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlKopf.add(jScrollPane7, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_kopf}"), cbEingriffKopf, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlKopf.add(cbEingriffKopf, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlKopf, gridBagConstraints); pnlAnsicht.setMinimumSize(new java.awt.Dimension(450, 300)); pnlAnsicht.setPreferredSize(new java.awt.Dimension(450, 300)); pnlAnsicht.setLayout(new java.awt.GridBagLayout()); pnlKopfAnsicht.setBackground(new java.awt.Color(51, 51, 51)); pnlKopfAnsicht.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht.text")); // NOI18N pnlKopfAnsicht.add(lblKofpAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlAnsicht.add(pnlKopfAnsicht, gridBagConstraints); lblFiller3.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlAnsicht.add(lblFiller3, gridBagConstraints); lblbeschreibungAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlAnsicht.add(lblbeschreibungAnsicht, gridBagConstraints); jScrollPane8.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane8.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungAnsicht.setLineWrap(true); taBeschreibungAnsicht.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_ansicht}"), taBeschreibungAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane8.setViewportView(taBeschreibungAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlAnsicht.add(jScrollPane8, gridBagConstraints); lblZustandAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblZustandAnsicht, gridBagConstraints); lblSanMassnahmenAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblSanMassnahmenAnsicht, gridBagConstraints); lblSanKostenAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblSanKostenAnsicht, gridBagConstraints); lblEingriffAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblEingriffAnsicht, gridBagConstraints); tfZustandAnsicht.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandAnsicht.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_ansicht}"), tfZustandAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAnsicht.add(tfZustandAnsicht, gridBagConstraints); tfSanKostenAnsicht.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenAnsicht.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_ansicht}"), tfSanKostenAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAnsicht.add(tfSanKostenAnsicht, gridBagConstraints); jScrollPane9.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane9.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeAnsicht.setLineWrap(true); taSanMassnahmeAnsicht.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_ansicht}"), taSanMassnahmeAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane9.setViewportView(taSanMassnahmeAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlAnsicht.add(jScrollPane9, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_ansicht}"), cbEingriffAnsicht, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlAnsicht.add(cbEingriffAnsicht, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlAnsicht, gridBagConstraints); pnlGruendung.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGruendung.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGruendung.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht1.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht1.text")); // NOI18N pnlGruendungHeader.add(lblKofpAnsicht1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGruendung.add(pnlGruendungHeader, gridBagConstraints); lblFiller4.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller4.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGruendung.add(lblFiller4, gridBagConstraints); lblbeschreibungGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGruendung.add(lblbeschreibungGruendung, gridBagConstraints); jScrollPane10.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane10.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung.setLineWrap(true); taBeschreibungGruendung.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gruendung}"), taBeschreibungGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane10.setViewportView(taBeschreibungGruendung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGruendung.add(jScrollPane10, gridBagConstraints); lblZustandGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblZustandGruendung, gridBagConstraints); lblSanMassnahmenGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblSanMassnahmenGruendung, gridBagConstraints); lblSanKostenAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblSanKostenAnsicht1, gridBagConstraints); lblEingriffAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblEingriffAnsicht1, gridBagConstraints); tfZustandGruendung.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gruendung}"), tfZustandGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGruendung.add(tfZustandGruendung, gridBagConstraints); tfSanKostenGruendung.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_Gruendung}"), tfSanKostenGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGruendung.add(tfSanKostenGruendung, gridBagConstraints); jScrollPane11.setMinimumSize(new java.awt.Dimension(26, 87)); jScrollPane11.setPreferredSize(new java.awt.Dimension(262, 70)); taSanMassnahmeGruendung.setLineWrap(true); taSanMassnahmeGruendung.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gruendung}"), taSanMassnahmeGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane11.setViewportView(taSanMassnahmeGruendung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGruendung.add(jScrollPane11, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gruendung}"), cbEingriffGruendung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGruendung.add(cbEingriffGruendung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGruendung, gridBagConstraints); pnlGelaende.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGelaende.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGelaende.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader1.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader1.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht2.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht2.text")); // NOI18N pnlGruendungHeader1.add(lblKofpAnsicht2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGelaende.add(pnlGruendungHeader1, gridBagConstraints); lblFiller5.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller5.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGelaende.add(lblFiller5, gridBagConstraints); lblbeschreibungGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGelaende.add(lblbeschreibungGruendung1, gridBagConstraints); jScrollPane12.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane12.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung1.setLineWrap(true); taBeschreibungGruendung1.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gelaende}"), taBeschreibungGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane12.setViewportView(taBeschreibungGruendung1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGelaende.add(jScrollPane12, gridBagConstraints); lblZustandGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblZustandGruendung1, gridBagConstraints); lblSanMassnahmenGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblSanMassnahmenGruendung1, gridBagConstraints); lblSanKostenAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblSanKostenAnsicht2, gridBagConstraints); lblEingriffAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblEingriffAnsicht2, gridBagConstraints); tfZustandGruendung1.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung1.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gelaende}"), tfZustandGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaende.add(tfZustandGruendung1, gridBagConstraints); tfSanKostenGruendung1.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung1.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gelaende}"), tfSanKostenGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaende.add(tfSanKostenGruendung1, gridBagConstraints); jScrollPane13.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane13.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeGruendung1.setLineWrap(true); taSanMassnahmeGruendung1.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gelaende}"), taSanMassnahmeGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane13.setViewportView(taSanMassnahmeGruendung1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaende.add(jScrollPane13, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gelaende}"), cbEingriffGelaende, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaende.add(cbEingriffGelaende, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGelaende, gridBagConstraints); pnlVerformung.setMinimumSize(new java.awt.Dimension(450, 300)); pnlVerformung.setPreferredSize(new java.awt.Dimension(450, 300)); pnlVerformung.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader2.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader2.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht3.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht3.text")); // NOI18N pnlGruendungHeader2.add(lblKofpAnsicht3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlVerformung.add(pnlGruendungHeader2, gridBagConstraints); lblFiller6.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller6.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVerformung.add(lblFiller6, gridBagConstraints); lblbeschreibungGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlVerformung.add(lblbeschreibungGruendung2, gridBagConstraints); jScrollPane14.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane14.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung2.setLineWrap(true); taBeschreibungGruendung2.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_verformung}"), taBeschreibungGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane14.setViewportView(taBeschreibungGruendung2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlVerformung.add(jScrollPane14, gridBagConstraints); lblZustandGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblZustandGruendung2, gridBagConstraints); lblSanMassnahmenGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblSanMassnahmenGruendung2, gridBagConstraints); lblSanKostenAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblSanKostenAnsicht3, gridBagConstraints); lblEingriffAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblEingriffAnsicht3, gridBagConstraints); tfZustandGruendung2.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung2.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_verformung}"), tfZustandGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlVerformung.add(tfZustandGruendung2, gridBagConstraints); tfSanKostenGruendung2.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung2.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_verformung}"), tfSanKostenGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlVerformung.add(tfSanKostenGruendung2, gridBagConstraints); jScrollPane15.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane15.setPreferredSize(new java.awt.Dimension(262, 70)); taSanMassnahmeGruendung2.setLineWrap(true); taSanMassnahmeGruendung2.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_verformung}"), taSanMassnahmeGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane15.setViewportView(taSanMassnahmeGruendung2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlVerformung.add(jScrollPane15, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_verformung}"), cbEingriffVerformung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlVerformung.add(cbEingriffVerformung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlVerformung, gridBagConstraints); jScrollPane3.setViewportView(pnlScrollPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedScrollPanel.add(jScrollPane3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.5; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCard1.add(roundedScrollPanel, gridBagConstraints); add(pnlCard1, "card1"); pnlCard2.setOpaque(false); pnlCard2.setLayout(new java.awt.GridBagLayout()); pnlFotos.setMinimumSize(new java.awt.Dimension(400, 200)); pnlFotos.setPreferredSize(new java.awt.Dimension(400, 200)); pnlFotos.setLayout(new java.awt.GridBagLayout()); pnlHeaderFotos.setBackground(new java.awt.Color(51, 51, 51)); pnlHeaderFotos.setForeground(new java.awt.Color(51, 51, 51)); pnlHeaderFotos.setLayout(new java.awt.FlowLayout()); lblHeaderFotos.setForeground(new java.awt.Color(255, 255, 255)); lblHeaderFotos.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblHeaderFotos.text")); // NOI18N pnlHeaderFotos.add(lblHeaderFotos); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlFotos.add(pnlHeaderFotos, gridBagConstraints); lblFiller9.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller9.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlFotos.add(lblFiller9, gridBagConstraints); lblFotos.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFotos.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlFotos.add(lblFotos, gridBagConstraints); jspFotoList.setMinimumSize(new java.awt.Dimension(250, 130)); lstFotos.setMinimumSize(new java.awt.Dimension(250, 130)); lstFotos.setPreferredSize(new java.awt.Dimension(250, 130)); final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create( "${cidsBean.bilder}"); final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings .createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFotos); bindingGroup.addBinding(jListBinding); lstFotos.addListSelectionListener(new javax.swing.event.ListSelectionListener() { @Override public void valueChanged(final javax.swing.event.ListSelectionEvent evt) { lstFotosValueChanged(evt); } }); jspFotoList.setViewportView(lstFotos); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlFotos.add(jspFotoList, gridBagConstraints); pnlCtrlButtons.setOpaque(false); pnlCtrlButtons.setLayout(new java.awt.GridBagLayout()); btnAddImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons.add(btnAddImg, gridBagConstraints); btnRemoveImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons.add(btnRemoveImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlFotos.add(pnlCtrlButtons, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 10); pnlCard2.add(pnlFotos, gridBagConstraints); pnlVorschau.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); lblVorschau.setForeground(new java.awt.Color(255, 255, 255)); lblVorschau.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblVorschau.text")); // NOI18N semiRoundedPanel2.add(lblVorschau); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlVorschau.add(semiRoundedPanel2, gridBagConstraints); pnlFoto.setOpaque(false); pnlFoto.setLayout(new java.awt.GridBagLayout()); lblPicture.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblPicture.text")); // NOI18N pnlFoto.add(lblPicture, new java.awt.GridBagConstraints()); lblBusy.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblBusy.setMaximumSize(new java.awt.Dimension(140, 40)); lblBusy.setMinimumSize(new java.awt.Dimension(140, 60)); lblBusy.setPreferredSize(new java.awt.Dimension(140, 60)); pnlFoto.add(lblBusy, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVorschau.add(pnlFoto, gridBagConstraints); pnlCtrlBtn.setOpaque(false); pnlCtrlBtn.setPreferredSize(new java.awt.Dimension(100, 50)); pnlCtrlBtn.setLayout(new java.awt.GridBagLayout()); btnPrevImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-left.png"))); // NOI18N btnPrevImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnPrevImg.setBorderPainted(false); btnPrevImg.setFocusPainted(false); btnPrevImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnPrevImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; pnlCtrlBtn.add(btnPrevImg, gridBagConstraints); btnNextImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-right.png"))); // NOI18N btnNextImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnNextImg.text")); // NOI18N btnNextImg.setBorderPainted(false); btnNextImg.setFocusPainted(false); btnNextImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnNextImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; pnlCtrlBtn.add(btnNextImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; pnlVorschau.add(pnlCtrlBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.8; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 15); pnlCard2.add(pnlVorschau, gridBagConstraints); pnlMap.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlMap.setMinimumSize(new java.awt.Dimension(400, 200)); pnlMap.setPreferredSize(new java.awt.Dimension(400, 200)); pnlMap.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 10); pnlCard2.add(pnlMap, gridBagConstraints); add(pnlCard2, "card2"); bindingGroup.bind(); } // </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); panFooter = new javax.swing.JPanel(); panLeft = new javax.swing.JPanel(); lblInfo = new javax.swing.JLabel(); btnInfo = new javax.swing.JButton(); panRight = new javax.swing.JPanel(); btnImages = new javax.swing.JButton(); lblImages = new javax.swing.JLabel(); panTitle = new javax.swing.JPanel(); lblTitle = new javax.swing.JLabel(); btnReport = new javax.swing.JButton(); pnlCard1 = new javax.swing.JPanel(); pnlAllgemein = new de.cismet.tools.gui.RoundedPanel(); pnlHeaderAllgemein = new de.cismet.tools.gui.SemiRoundedPanel(); lblHeaderAllgemein = new javax.swing.JLabel(); jspAllgemeineInfos = new javax.swing.JScrollPane(); pnlLeft = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); taNeigung = new javax.swing.JTextArea(); cbMaterialtyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblStaerke = new javax.swing.JLabel(); lblStuetzmauer = new javax.swing.JLabel(); cbEigentuemer = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblLagebeschreibung = new javax.swing.JLabel(); lblHoeheMin = new javax.swing.JLabel(); tfUmgebung = new javax.swing.JTextField(); pnlHoehe = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); tfHoeheMin = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); tfHoeheMax = new javax.swing.JTextField(); lblFiller11 = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); lblFiller7 = new javax.swing.JLabel(); lblEigentuemer = new javax.swing.JLabel(); lblNeigung = new javax.swing.JLabel(); jScrollPane1 = new javax.swing.JScrollPane(); taLagebeschreibung = new javax.swing.JTextArea(); lblLaenge = new javax.swing.JLabel(); lblUmgebung = new javax.swing.JLabel(); tfLaenge = new javax.swing.JTextField(); lblMaterialTyp = new javax.swing.JLabel(); cbStuetzmauertyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel1 = new javax.swing.JPanel(); lblStaerkeUnten = new javax.swing.JLabel(); tfStaerke_unten = new javax.swing.JTextField(); lblStaerkeOben = new javax.swing.JLabel(); tfStaerkeOben = new javax.swing.JTextField(); lblBesonderheiten = new javax.swing.JLabel(); jScrollPane17 = new javax.swing.JScrollPane(); taBesonderheiten = new javax.swing.JTextArea(); lblLagebezeichnung = new javax.swing.JLabel(); tfLagebezeichnung = new javax.swing.JTextField(); lblMauerNummer = new javax.swing.JLabel(); tfMauerNummer = new javax.swing.JTextField(); lblMauertyp = new javax.swing.JLabel(); cbMauertyp = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblLastabstand = new javax.swing.JLabel(); tfLastabstand = new javax.swing.JTextField(); lblLastklasse = new javax.swing.JLabel(); lblDauerhaftigkeit = new javax.swing.JLabel(); lblVerkehrssicherheit = new javax.swing.JLabel(); lblStandsicherheit = new javax.swing.JLabel(); lblPruefung1 = new javax.swing.JLabel(); lblLetztePruefung = new javax.swing.JLabel(); lblNaechstePruefung = new javax.swing.JLabel(); lblBauwerksbuchfertigstellung = new javax.swing.JLabel(); lblSanierung = new javax.swing.JLabel(); if (editable) { lblGeom = new javax.swing.JLabel(); } if (editable) { cbGeom = new DefaultCismapGeometryComboBoxEditor(); } jPanel5 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); dcBauwerksbuchfertigstellung = new de.cismet.cids.editors.DefaultBindableDateChooser(); lblFiller10 = new javax.swing.JLabel(); jPanel7 = new javax.swing.JPanel(); jLabel15 = new javax.swing.JLabel(); dcNaechstePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel16 = new javax.swing.JLabel(); cbArtNaechstePruefung1 = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel6 = new javax.swing.JPanel(); jLabel13 = new javax.swing.JLabel(); dcLetztePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel14 = new javax.swing.JLabel(); cbArtLetztePruefung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); jPanel2 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); dcErstePruefung = new de.cismet.cids.editors.DefaultBindableDateChooser(); jLabel6 = new javax.swing.JLabel(); cbArtErstePruefung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbStandsicherheit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbVerkehrssicherheit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbDauerhaftigkeit = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); cbLastklasse = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); lblZustandGesamt = new javax.swing.JLabel(); tfZustandGesamt = new javax.swing.JTextField(); lblFiller8 = new javax.swing.JLabel(); dcSanierung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); roundedScrollPanel = new de.cismet.tools.gui.RoundedPanel(); jScrollPane3 = new javax.swing.JScrollPane(); pnlScrollPane = new javax.swing.JPanel(); pnlGelaender = new de.cismet.tools.gui.RoundedPanel(); pnlGelaenderHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblGelaenderHeader = new javax.swing.JLabel(); lblFiller = new javax.swing.JLabel(); lblBeschreibungGelaender = new javax.swing.JLabel(); jScrollPane4 = new javax.swing.JScrollPane(); taBeschreibungGelaender = new javax.swing.JTextArea(); lblZustandGelaender = new javax.swing.JLabel(); lblSanKostenGelaender = new javax.swing.JLabel(); lblSanMassnahmenGelaender = new javax.swing.JLabel(); lblEingriffGeleander = new javax.swing.JLabel(); tfZustandGelaender = new javax.swing.JTextField(); tfSanKostenGelaender = new javax.swing.JTextField(); jScrollPane5 = new javax.swing.JScrollPane(); taSanMassnahmeGelaender = new javax.swing.JTextArea(); cbEingriffGelaender = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlKopf = new de.cismet.tools.gui.RoundedPanel(); pnlKopfHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpHeader = new javax.swing.JLabel(); lblFiller1 = new javax.swing.JLabel(); lblbeschreibungKopf = new javax.swing.JLabel(); jScrollPane6 = new javax.swing.JScrollPane(); taBeschreibungKopf = new javax.swing.JTextArea(); lblZustandKopf = new javax.swing.JLabel(); lblSanMassnahmenKopf = new javax.swing.JLabel(); lblSanKostenKopf = new javax.swing.JLabel(); lblEingriffKopf = new javax.swing.JLabel(); tfZustandKopf = new javax.swing.JTextField(); tfSanKostenKopf = new javax.swing.JTextField(); jScrollPane7 = new javax.swing.JScrollPane(); taSanMassnahmeKopf = new javax.swing.JTextArea(); cbEingriffKopf = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlAnsicht = new de.cismet.tools.gui.RoundedPanel(); pnlKopfAnsicht = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht = new javax.swing.JLabel(); lblFiller3 = new javax.swing.JLabel(); lblbeschreibungAnsicht = new javax.swing.JLabel(); jScrollPane8 = new javax.swing.JScrollPane(); taBeschreibungAnsicht = new javax.swing.JTextArea(); lblZustandAnsicht = new javax.swing.JLabel(); lblSanMassnahmenAnsicht = new javax.swing.JLabel(); lblSanKostenAnsicht = new javax.swing.JLabel(); lblEingriffAnsicht = new javax.swing.JLabel(); tfZustandAnsicht = new javax.swing.JTextField(); tfSanKostenAnsicht = new javax.swing.JTextField(); jScrollPane9 = new javax.swing.JScrollPane(); taSanMassnahmeAnsicht = new javax.swing.JTextArea(); cbEingriffAnsicht = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlGruendung = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht1 = new javax.swing.JLabel(); lblFiller4 = new javax.swing.JLabel(); lblbeschreibungGruendung = new javax.swing.JLabel(); jScrollPane10 = new javax.swing.JScrollPane(); taBeschreibungGruendung = new javax.swing.JTextArea(); lblZustandGruendung = new javax.swing.JLabel(); lblSanMassnahmenGruendung = new javax.swing.JLabel(); lblSanKostenAnsicht1 = new javax.swing.JLabel(); lblEingriffAnsicht1 = new javax.swing.JLabel(); tfZustandGruendung = new javax.swing.JTextField(); tfSanKostenGruendung = new javax.swing.JTextField(); jScrollPane11 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung = new javax.swing.JTextArea(); cbEingriffGruendung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlGelaende = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader1 = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht2 = new javax.swing.JLabel(); lblFiller5 = new javax.swing.JLabel(); lblbeschreibungGruendung1 = new javax.swing.JLabel(); jScrollPane12 = new javax.swing.JScrollPane(); taBeschreibungGruendung1 = new javax.swing.JTextArea(); lblZustandGruendung1 = new javax.swing.JLabel(); lblSanMassnahmenGruendung1 = new javax.swing.JLabel(); lblSanKostenAnsicht2 = new javax.swing.JLabel(); lblEingriffAnsicht2 = new javax.swing.JLabel(); tfZustandGruendung1 = new javax.swing.JTextField(); tfSanKostenGruendung1 = new javax.swing.JTextField(); jScrollPane13 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung1 = new javax.swing.JTextArea(); cbEingriffGelaende = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlVerformung = new de.cismet.tools.gui.RoundedPanel(); pnlGruendungHeader2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblKofpAnsicht3 = new javax.swing.JLabel(); lblFiller6 = new javax.swing.JLabel(); lblbeschreibungGruendung2 = new javax.swing.JLabel(); jScrollPane14 = new javax.swing.JScrollPane(); taBeschreibungGruendung2 = new javax.swing.JTextArea(); lblZustandGruendung2 = new javax.swing.JLabel(); lblSanMassnahmenGruendung2 = new javax.swing.JLabel(); lblSanKostenAnsicht3 = new javax.swing.JLabel(); lblEingriffAnsicht3 = new javax.swing.JLabel(); tfZustandGruendung2 = new javax.swing.JTextField(); tfSanKostenGruendung2 = new javax.swing.JTextField(); jScrollPane15 = new javax.swing.JScrollPane(); taSanMassnahmeGruendung2 = new javax.swing.JTextArea(); cbEingriffVerformung = new de.cismet.cids.editors.DefaultBindableReferenceCombo(); pnlCard2 = new javax.swing.JPanel(); pnlFotos = new de.cismet.tools.gui.RoundedPanel(); pnlHeaderFotos = new de.cismet.tools.gui.SemiRoundedPanel(); lblHeaderFotos = new javax.swing.JLabel(); lblFiller9 = new javax.swing.JLabel(); lblFotos = new javax.swing.JLabel(); jspFotoList = new javax.swing.JScrollPane(); lstFotos = new javax.swing.JList(); pnlCtrlButtons = new javax.swing.JPanel(); btnAddImg = new javax.swing.JButton(); btnRemoveImg = new javax.swing.JButton(); pnlVorschau = new de.cismet.tools.gui.RoundedPanel(); semiRoundedPanel2 = new de.cismet.tools.gui.SemiRoundedPanel(); lblVorschau = new javax.swing.JLabel(); pnlFoto = new javax.swing.JPanel(); lblPicture = new javax.swing.JLabel(); lblBusy = new org.jdesktop.swingx.JXBusyLabel(new Dimension(75, 75)); pnlCtrlBtn = new javax.swing.JPanel(); btnPrevImg = new javax.swing.JButton(); btnNextImg = new javax.swing.JButton(); pnlMap = new javax.swing.JPanel(); panFooter.setOpaque(false); panFooter.setLayout(new java.awt.GridBagLayout()); panLeft.setOpaque(false); lblInfo.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N lblInfo.setForeground(new java.awt.Color(255, 255, 255)); lblInfo.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblInfo.text")); // NOI18N lblInfo.setEnabled(false); panLeft.add(lblInfo); btnInfo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-left.png"))); // NOI18N btnInfo.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnInfo.text")); // NOI18N btnInfo.setBorderPainted(false); btnInfo.setContentAreaFilled(false); btnInfo.setEnabled(false); btnInfo.setFocusPainted(false); btnInfo.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnInfoActionPerformed(evt); } }); panLeft.add(btnInfo); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; panFooter.add(panLeft, gridBagConstraints); panRight.setOpaque(false); btnImages.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-right.png"))); // NOI18N btnImages.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnImages.text")); // NOI18N btnImages.setBorderPainted(false); btnImages.setContentAreaFilled(false); btnImages.setFocusPainted(false); btnImages.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnImagesActionPerformed(evt); } }); panRight.add(btnImages); lblImages.setFont(new java.awt.Font("DejaVu Sans", 1, 14)); // NOI18N lblImages.setForeground(new java.awt.Color(255, 255, 255)); lblImages.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblImages.text")); // NOI18N panRight.add(lblImages); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; panFooter.add(panRight, gridBagConstraints); panTitle.setOpaque(false); panTitle.setLayout(new java.awt.GridBagLayout()); lblTitle.setFont(new java.awt.Font("DejaVu Sans", 1, 18)); // NOI18N lblTitle.setForeground(new java.awt.Color(255, 255, 255)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; panTitle.add(lblTitle, gridBagConstraints); btnReport.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/icons/printer.png"))); // NOI18N btnReport.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnReport.text")); // NOI18N btnReport.setToolTipText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.btnReport.toolTipText")); // NOI18N btnReport.setBorderPainted(false); btnReport.setContentAreaFilled(false); btnReport.setFocusPainted(false); btnReport.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnReportActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; panTitle.add(btnReport, gridBagConstraints); setMaximumSize(new java.awt.Dimension(1190, 1625)); setMinimumSize(new java.awt.Dimension(807, 485)); setVerifyInputWhenFocusTarget(false); setLayout(new java.awt.CardLayout()); pnlCard1.setOpaque(false); pnlCard1.setLayout(new java.awt.GridBagLayout()); pnlAllgemein.setMinimumSize(new java.awt.Dimension(540, 500)); pnlAllgemein.setPreferredSize(new java.awt.Dimension(540, 800)); pnlAllgemein.setLayout(new java.awt.GridBagLayout()); pnlHeaderAllgemein.setBackground(new java.awt.Color(51, 51, 51)); pnlHeaderAllgemein.setMinimumSize(new java.awt.Dimension(109, 24)); pnlHeaderAllgemein.setPreferredSize(new java.awt.Dimension(109, 24)); pnlHeaderAllgemein.setLayout(new java.awt.FlowLayout()); lblHeaderAllgemein.setForeground(new java.awt.Color(255, 255, 255)); lblHeaderAllgemein.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblHeaderAllgemein.text")); // NOI18N pnlHeaderAllgemein.add(lblHeaderAllgemein); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlAllgemein.add(pnlHeaderAllgemein, gridBagConstraints); jspAllgemeineInfos.setBorder(null); jspAllgemeineInfos.setMinimumSize(new java.awt.Dimension(500, 520)); jspAllgemeineInfos.setOpaque(false); jspAllgemeineInfos.setPreferredSize(new java.awt.Dimension(500, 880)); pnlLeft.setMinimumSize(new java.awt.Dimension(500, 790)); pnlLeft.setOpaque(false); pnlLeft.setPreferredSize(new java.awt.Dimension(500, 850)); pnlLeft.setLayout(new java.awt.GridBagLayout()); jScrollPane2.setMinimumSize(new java.awt.Dimension(26, 50)); jScrollPane2.setPreferredSize(new java.awt.Dimension(0, 50)); taNeigung.setLineWrap(true); taNeigung.setMinimumSize(new java.awt.Dimension(500, 34)); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.neigung}"), taNeigung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane2.setViewportView(taNeigung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jScrollPane2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.materialtyp}"), cbMaterialtyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 7; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbMaterialtyp, gridBagConstraints); lblStaerke.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblStaerke.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStaerke, gridBagConstraints); lblStuetzmauer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStuetzmauer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStuetzmauer, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.eigentuemer}"), cbEigentuemer, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 8; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbEigentuemer, gridBagConstraints); lblLagebeschreibung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLagebeschreibung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLagebeschreibung, gridBagConstraints); lblHoeheMin.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblHoeheMin.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 9; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblHoeheMin, gridBagConstraints); tfUmgebung.setMinimumSize(new java.awt.Dimension(100, 20)); tfUmgebung.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.umgebung}"), tfUmgebung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfUmgebung, gridBagConstraints); pnlHoehe.setOpaque(false); pnlHoehe.setLayout(new java.awt.GridBagLayout()); jLabel1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlHoehe.add(jLabel1, gridBagConstraints); tfHoeheMin.setMinimumSize(new java.awt.Dimension(50, 20)); tfHoeheMin.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_min}"), tfHoeheMin, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 0, 20); pnlHoehe.add(tfHoeheMin, gridBagConstraints); jLabel3.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); pnlHoehe.add(jLabel3, gridBagConstraints); tfHoeheMax.setMinimumSize(new java.awt.Dimension(50, 20)); tfHoeheMax.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe_max}"), tfHoeheMax, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 0); pnlHoehe.add(tfHoeheMax, gridBagConstraints); lblFiller11.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller11.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 6; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; pnlHoehe.add(lblFiller11, gridBagConstraints); jPanel3.setOpaque(false); jPanel3.setLayout(new java.awt.GridBagLayout()); jLabel4.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel4.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; jPanel3.add(jLabel4, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_ONCE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.hoehe}"), jLabel2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 20, 0, 0); jPanel3.add(jLabel2, gridBagConstraints); lblFiller7.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller7.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel3.add(lblFiller7, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlHoehe.add(jPanel3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 9; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(pnlHoehe, gridBagConstraints); lblEigentuemer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEigentuemer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblEigentuemer, gridBagConstraints); lblNeigung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblNeigung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblNeigung, gridBagConstraints); jScrollPane1.setMinimumSize(new java.awt.Dimension(26, 40)); jScrollPane1.setPreferredSize(new java.awt.Dimension(0, 50)); jScrollPane1.setRequestFocusEnabled(false); taLagebeschreibung.setLineWrap(true); taLagebeschreibung.setMaximumSize(new java.awt.Dimension(500, 34)); taLagebeschreibung.setMinimumSize(new java.awt.Dimension(500, 34)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebeschreibung}"), taLagebeschreibung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane1.setViewportView(taLagebeschreibung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jScrollPane1, gridBagConstraints); lblLaenge.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblLaenge.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 11; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLaenge, gridBagConstraints); lblUmgebung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblUmgebung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblUmgebung, gridBagConstraints); tfLaenge.setMinimumSize(new java.awt.Dimension(100, 20)); tfLaenge.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.laenge}"), tfLaenge, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 11; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLaenge, gridBagConstraints); lblMaterialTyp.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblMaterialTyp.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMaterialTyp, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.stuetzmauertyp}"), cbStuetzmauertyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbStuetzmauertyp, gridBagConstraints); jPanel1.setOpaque(false); jPanel1.setLayout(new java.awt.GridBagLayout()); lblStaerkeUnten.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStaerkeUnten.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(lblStaerkeUnten, gridBagConstraints); tfStaerke_unten.setMinimumSize(new java.awt.Dimension(50, 20)); tfStaerke_unten.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.staerke_unten}"), tfStaerke_unten, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); tfStaerke_unten.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { tfStaerke_untenActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel1.add(tfStaerke_unten, gridBagConstraints); lblStaerkeOben.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStaerkeOben.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel1.add(lblStaerkeOben, gridBagConstraints); tfStaerkeOben.setMinimumSize(new java.awt.Dimension(50, 20)); tfStaerkeOben.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.staerke_oben}"), tfStaerkeOben, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; jPanel1.add(tfStaerkeOben, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 10; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel1, gridBagConstraints); lblBesonderheiten.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBesonderheiten.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 12; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblBesonderheiten, gridBagConstraints); jScrollPane17.setMinimumSize(new java.awt.Dimension(26, 50)); jScrollPane17.setPreferredSize(new java.awt.Dimension(0, 50)); taBesonderheiten.setLineWrap(true); taBesonderheiten.setMinimumSize(new java.awt.Dimension(500, 34)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.besonderheiten}"), taBesonderheiten, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane17.setViewportView(taBesonderheiten); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 12; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 10, 10); pnlLeft.add(jScrollPane17, gridBagConstraints); lblLagebezeichnung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLagebezeichnung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLagebezeichnung, gridBagConstraints); tfLagebezeichnung.setMinimumSize(new java.awt.Dimension(100, 20)); tfLagebezeichnung.setPreferredSize(new java.awt.Dimension(50, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lagebezeichnung}"), tfLagebezeichnung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLagebezeichnung, gridBagConstraints); lblMauerNummer.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblMauerNummer.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMauerNummer, gridBagConstraints); tfMauerNummer.setMinimumSize(new java.awt.Dimension(150, 20)); tfMauerNummer.setPreferredSize(new java.awt.Dimension(150, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.mauer_nummer}"), tfMauerNummer, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfMauerNummer, gridBagConstraints); lblMauertyp.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblMauertyp.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblMauertyp, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.mauertyp}"), cbMauertyp, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbMauertyp, gridBagConstraints); lblLastabstand.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLastabstand.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 13; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLastabstand, gridBagConstraints); tfLastabstand.setMinimumSize(new java.awt.Dimension(100, 20)); tfLastabstand.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lastabstand}"), tfLastabstand, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 13; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfLastabstand, gridBagConstraints); lblLastklasse.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLastklasse.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 14; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLastklasse, gridBagConstraints); lblDauerhaftigkeit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblDauerhaftigkeit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 15; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblDauerhaftigkeit, gridBagConstraints); lblVerkehrssicherheit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblVerkehrssicherheit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 16; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblVerkehrssicherheit, gridBagConstraints); lblStandsicherheit.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblStandsicherheit.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 17; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblStandsicherheit, gridBagConstraints); lblPruefung1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblPruefung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 18; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblPruefung1, gridBagConstraints); lblLetztePruefung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblLetztePruefung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 19; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblLetztePruefung, gridBagConstraints); lblNaechstePruefung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblNaechstePruefung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 20; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblNaechstePruefung, gridBagConstraints); lblBauwerksbuchfertigstellung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBauwerksbuchfertigstellung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 21; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblBauwerksbuchfertigstellung, gridBagConstraints); lblSanierung.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblSanierung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 22; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblSanierung, gridBagConstraints); if (editable) { lblGeom.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblGeom.text")); // NOI18N } if (editable) { gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 24; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblGeom, gridBagConstraints); } if (editable) { cbGeom.setMinimumSize(new java.awt.Dimension(41, 25)); cbGeom.setPreferredSize(new java.awt.Dimension(41, 25)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.georeferenz}"), cbGeom, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); binding.setConverter(((DefaultCismapGeometryComboBoxEditor)cbGeom).getConverter()); bindingGroup.addBinding(binding); } if (editable) { gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 24; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbGeom, gridBagConstraints); } jPanel5.setOpaque(false); jPanel5.setLayout(new java.awt.GridBagLayout()); jLabel11.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel11.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel5.add(jLabel11, gridBagConstraints); dcBauwerksbuchfertigstellung.setMinimumSize(new java.awt.Dimension(124, 20)); dcBauwerksbuchfertigstellung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.bauwerksbuchfertigstellung}"), dcBauwerksbuchfertigstellung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcBauwerksbuchfertigstellung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel5.add(dcBauwerksbuchfertigstellung, gridBagConstraints); lblFiller10.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller10.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; jPanel5.add(lblFiller10, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 21; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel5, gridBagConstraints); jPanel7.setOpaque(false); jPanel7.setLayout(new java.awt.GridBagLayout()); jLabel15.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel15.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel7.add(jLabel15, gridBagConstraints); dcNaechstePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcNaechstePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_naechste_pruefung}"), dcNaechstePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcNaechstePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel7.add(dcNaechstePruefung, gridBagConstraints); jLabel16.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel16.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel7.add(jLabel16, gridBagConstraints); cbArtNaechstePruefung1.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtNaechstePruefung1.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_naechste_pruefung}"), cbArtNaechstePruefung1, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel7.add(cbArtNaechstePruefung1, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 20; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel7, gridBagConstraints); jPanel6.setOpaque(false); jPanel6.setLayout(new java.awt.GridBagLayout()); jLabel13.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel13.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel6.add(jLabel13, gridBagConstraints); dcLetztePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcLetztePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_letzte_pruefung}"), dcLetztePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcLetztePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel6.add(dcLetztePruefung, gridBagConstraints); jLabel14.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel14.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel6.add(jLabel14, gridBagConstraints); cbArtLetztePruefung.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtLetztePruefung.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_letzte_pruefung}"), cbArtLetztePruefung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel6.add(cbArtLetztePruefung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 19; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel6, gridBagConstraints); jPanel2.setOpaque(false); jPanel2.setLayout(new java.awt.GridBagLayout()); jLabel5.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel5.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel2.add(jLabel5, gridBagConstraints); dcErstePruefung.setMinimumSize(new java.awt.Dimension(124, 20)); dcErstePruefung.setPreferredSize(new java.awt.Dimension(124, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.datum_erste_pruefung}"), dcErstePruefung, org.jdesktop.beansbinding.BeanProperty.create("date")); binding.setConverter(dcErstePruefung.getConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 20); jPanel2.add(dcErstePruefung, gridBagConstraints); jLabel6.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.jLabel6.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); jPanel2.add(jLabel6, gridBagConstraints); cbArtErstePruefung.setMinimumSize(new java.awt.Dimension(120, 20)); cbArtErstePruefung.setPreferredSize(new java.awt.Dimension(120, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.art_erste_pruefung}"), cbArtErstePruefung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 3; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; jPanel2.add(cbArtErstePruefung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 18; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(jPanel2, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.standsicherheit}"), cbStandsicherheit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 17; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbStandsicherheit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.verkehrssicherheit}"), cbVerkehrssicherheit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 16; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbVerkehrssicherheit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.dauerhaftigkeit}"), cbDauerhaftigkeit, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 15; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbDauerhaftigkeit, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.lastklasse}"), cbLastklasse, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 14; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(cbLastklasse, gridBagConstraints); lblZustandGesamt.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGesamt.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 23; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(lblZustandGesamt, gridBagConstraints); tfZustandGesamt.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGesamt.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gesamt}"), tfZustandGesamt, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new DoubleNumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 23; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(tfZustandGesamt, gridBagConstraints); lblFiller8.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller8.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 25; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; pnlLeft.add(lblFiller8, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.sanierung}"), dcSanierung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 22; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlLeft.add(dcSanierung, gridBagConstraints); jspAllgemeineInfos.setViewportView(pnlLeft); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlAllgemein.add(jspAllgemeineInfos, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.weightx = 0.5; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCard1.add(pnlAllgemein, gridBagConstraints); roundedScrollPanel.setBackground(new java.awt.Color(254, 254, 254)); roundedScrollPanel.setForeground(new java.awt.Color(254, 254, 254)); roundedScrollPanel.setMinimumSize(new java.awt.Dimension(500, 26)); roundedScrollPanel.setPreferredSize(new java.awt.Dimension(500, 120)); roundedScrollPanel.setLayout(new java.awt.GridBagLayout()); jScrollPane3.setBackground(new java.awt.Color(254, 254, 254)); jScrollPane3.setBorder(null); jScrollPane3.setFocusable(false); jScrollPane3.setMinimumSize(new java.awt.Dimension(500, 26)); jScrollPane3.setOpaque(false); jScrollPane3.setPreferredSize(new java.awt.Dimension(600, 120)); pnlScrollPane.setBackground(new java.awt.Color(254, 254, 254)); pnlScrollPane.setFocusable(false); pnlScrollPane.setOpaque(false); pnlScrollPane.setLayout(new java.awt.GridBagLayout()); pnlGelaender.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGelaender.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGelaender.setLayout(new java.awt.GridBagLayout()); pnlGelaenderHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlGelaenderHeader.setLayout(new java.awt.FlowLayout()); lblGelaenderHeader.setForeground(new java.awt.Color(255, 255, 255)); lblGelaenderHeader.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblGelaenderHeader.text")); // NOI18N pnlGelaenderHeader.add(lblGelaenderHeader); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGelaender.add(pnlGelaenderHeader, gridBagConstraints); lblFiller.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGelaender.add(lblFiller, gridBagConstraints); lblBeschreibungGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblBeschreibungGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGelaender.add(lblBeschreibungGelaender, gridBagConstraints); jScrollPane4.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane4.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGelaender.setLineWrap(true); taBeschreibungGelaender.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gelaender}"), taBeschreibungGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane4.setViewportView(taBeschreibungGelaender); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGelaender.add(jScrollPane4, gridBagConstraints); lblZustandGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblZustandGelaender, gridBagConstraints); lblSanKostenGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblSanKostenGelaender, gridBagConstraints); lblSanMassnahmenGelaender.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGelaender.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblSanMassnahmenGelaender, gridBagConstraints); lblEingriffGeleander.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffGeleander.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaender.add(lblEingriffGeleander, gridBagConstraints); tfZustandGelaender.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGelaender.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gelaender}"), tfZustandGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaender.add(tfZustandGelaender, gridBagConstraints); tfSanKostenGelaender.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGelaender.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gelaender}"), tfSanKostenGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaender.add(tfSanKostenGelaender, gridBagConstraints); jScrollPane5.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane5.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeGelaender.setLineWrap(true); taSanMassnahmeGelaender.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gelaender}"), taSanMassnahmeGelaender, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane5.setViewportView(taSanMassnahmeGelaender); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaender.add(jScrollPane5, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gelaender}"), cbEingriffGelaender, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaender.add(cbEingriffGelaender, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGelaender, gridBagConstraints); pnlKopf.setMinimumSize(new java.awt.Dimension(450, 300)); pnlKopf.setPreferredSize(new java.awt.Dimension(450, 300)); pnlKopf.setLayout(new java.awt.GridBagLayout()); pnlKopfHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlKopfHeader.setLayout(new java.awt.FlowLayout()); lblKofpHeader.setForeground(new java.awt.Color(255, 255, 255)); lblKofpHeader.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpHeader.text")); // NOI18N pnlKopfHeader.add(lblKofpHeader); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlKopf.add(pnlKopfHeader, gridBagConstraints); lblFiller1.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlKopf.add(lblFiller1, gridBagConstraints); lblbeschreibungKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlKopf.add(lblbeschreibungKopf, gridBagConstraints); jScrollPane6.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane6.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungKopf.setLineWrap(true); taBeschreibungKopf.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_kopf}"), taBeschreibungKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane6.setViewportView(taBeschreibungKopf); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlKopf.add(jScrollPane6, gridBagConstraints); lblZustandKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblZustandKopf, gridBagConstraints); lblSanMassnahmenKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblSanMassnahmenKopf, gridBagConstraints); lblSanKostenKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblSanKostenKopf, gridBagConstraints); lblEingriffKopf.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffKopf.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlKopf.add(lblEingriffKopf, gridBagConstraints); tfZustandKopf.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandKopf.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_kopf}"), tfZustandKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlKopf.add(tfZustandKopf, gridBagConstraints); tfSanKostenKopf.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenKopf.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_kopf}"), tfSanKostenKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlKopf.add(tfSanKostenKopf, gridBagConstraints); jScrollPane7.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane7.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeKopf.setLineWrap(true); taSanMassnahmeKopf.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_kopf}"), taSanMassnahmeKopf, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane7.setViewportView(taSanMassnahmeKopf); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlKopf.add(jScrollPane7, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_kopf}"), cbEingriffKopf, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlKopf.add(cbEingriffKopf, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlKopf, gridBagConstraints); pnlAnsicht.setMinimumSize(new java.awt.Dimension(450, 300)); pnlAnsicht.setPreferredSize(new java.awt.Dimension(450, 300)); pnlAnsicht.setLayout(new java.awt.GridBagLayout()); pnlKopfAnsicht.setBackground(new java.awt.Color(51, 51, 51)); pnlKopfAnsicht.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht.text")); // NOI18N pnlKopfAnsicht.add(lblKofpAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlAnsicht.add(pnlKopfAnsicht, gridBagConstraints); lblFiller3.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlAnsicht.add(lblFiller3, gridBagConstraints); lblbeschreibungAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlAnsicht.add(lblbeschreibungAnsicht, gridBagConstraints); jScrollPane8.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane8.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungAnsicht.setLineWrap(true); taBeschreibungAnsicht.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_ansicht}"), taBeschreibungAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane8.setViewportView(taBeschreibungAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlAnsicht.add(jScrollPane8, gridBagConstraints); lblZustandAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblZustandAnsicht, gridBagConstraints); lblSanMassnahmenAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblSanMassnahmenAnsicht, gridBagConstraints); lblSanKostenAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblSanKostenAnsicht, gridBagConstraints); lblEingriffAnsicht.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlAnsicht.add(lblEingriffAnsicht, gridBagConstraints); tfZustandAnsicht.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandAnsicht.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_ansicht}"), tfZustandAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAnsicht.add(tfZustandAnsicht, gridBagConstraints); tfSanKostenAnsicht.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenAnsicht.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_ansicht}"), tfSanKostenAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlAnsicht.add(tfSanKostenAnsicht, gridBagConstraints); jScrollPane9.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane9.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeAnsicht.setLineWrap(true); taSanMassnahmeAnsicht.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_ansicht}"), taSanMassnahmeAnsicht, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane9.setViewportView(taSanMassnahmeAnsicht); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlAnsicht.add(jScrollPane9, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_ansicht}"), cbEingriffAnsicht, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlAnsicht.add(cbEingriffAnsicht, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlAnsicht, gridBagConstraints); pnlGruendung.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGruendung.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGruendung.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht1.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht1.text")); // NOI18N pnlGruendungHeader.add(lblKofpAnsicht1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGruendung.add(pnlGruendungHeader, gridBagConstraints); lblFiller4.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller4.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGruendung.add(lblFiller4, gridBagConstraints); lblbeschreibungGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGruendung.add(lblbeschreibungGruendung, gridBagConstraints); jScrollPane10.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane10.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung.setLineWrap(true); taBeschreibungGruendung.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gruendung}"), taBeschreibungGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane10.setViewportView(taBeschreibungGruendung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGruendung.add(jScrollPane10, gridBagConstraints); lblZustandGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblZustandGruendung, gridBagConstraints); lblSanMassnahmenGruendung.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblSanMassnahmenGruendung, gridBagConstraints); lblSanKostenAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblSanKostenAnsicht1, gridBagConstraints); lblEingriffAnsicht1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGruendung.add(lblEingriffAnsicht1, gridBagConstraints); tfZustandGruendung.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gruendung}"), tfZustandGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGruendung.add(tfZustandGruendung, gridBagConstraints); tfSanKostenGruendung.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gruendung}"), tfSanKostenGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGruendung.add(tfSanKostenGruendung, gridBagConstraints); jScrollPane11.setMinimumSize(new java.awt.Dimension(26, 87)); jScrollPane11.setPreferredSize(new java.awt.Dimension(262, 70)); taSanMassnahmeGruendung.setLineWrap(true); taSanMassnahmeGruendung.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gruendung}"), taSanMassnahmeGruendung, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane11.setViewportView(taSanMassnahmeGruendung); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGruendung.add(jScrollPane11, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gruendung}"), cbEingriffGruendung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGruendung.add(cbEingriffGruendung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGruendung, gridBagConstraints); pnlGelaende.setMinimumSize(new java.awt.Dimension(450, 300)); pnlGelaende.setPreferredSize(new java.awt.Dimension(450, 300)); pnlGelaende.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader1.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader1.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht2.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht2.text")); // NOI18N pnlGruendungHeader1.add(lblKofpAnsicht2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlGelaende.add(pnlGruendungHeader1, gridBagConstraints); lblFiller5.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller5.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlGelaende.add(lblFiller5, gridBagConstraints); lblbeschreibungGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlGelaende.add(lblbeschreibungGruendung1, gridBagConstraints); jScrollPane12.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane12.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung1.setLineWrap(true); taBeschreibungGruendung1.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_gelaende}"), taBeschreibungGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane12.setViewportView(taBeschreibungGruendung1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlGelaende.add(jScrollPane12, gridBagConstraints); lblZustandGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblZustandGruendung1, gridBagConstraints); lblSanMassnahmenGruendung1.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblSanMassnahmenGruendung1, gridBagConstraints); lblSanKostenAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblSanKostenAnsicht2, gridBagConstraints); lblEingriffAnsicht2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlGelaende.add(lblEingriffAnsicht2, gridBagConstraints); tfZustandGruendung1.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung1.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_gelaende}"), tfZustandGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaende.add(tfZustandGruendung1, gridBagConstraints); tfSanKostenGruendung1.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung1.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_gelaende}"), tfSanKostenGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlGelaende.add(tfSanKostenGruendung1, gridBagConstraints); jScrollPane13.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane13.setPreferredSize(new java.awt.Dimension(0, 70)); taSanMassnahmeGruendung1.setLineWrap(true); taSanMassnahmeGruendung1.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_gelaende}"), taSanMassnahmeGruendung1, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane13.setViewportView(taSanMassnahmeGruendung1); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaende.add(jScrollPane13, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_gelaende}"), cbEingriffGelaende, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlGelaende.add(cbEingriffGelaende, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlGelaende, gridBagConstraints); pnlVerformung.setMinimumSize(new java.awt.Dimension(450, 300)); pnlVerformung.setPreferredSize(new java.awt.Dimension(450, 300)); pnlVerformung.setLayout(new java.awt.GridBagLayout()); pnlGruendungHeader2.setBackground(new java.awt.Color(51, 51, 51)); pnlGruendungHeader2.setLayout(new java.awt.FlowLayout()); lblKofpAnsicht3.setForeground(new java.awt.Color(255, 255, 255)); lblKofpAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblKofpAnsicht3.text")); // NOI18N pnlGruendungHeader2.add(lblKofpAnsicht3); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlVerformung.add(pnlGruendungHeader2, gridBagConstraints); lblFiller6.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller6.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = 2; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVerformung.add(lblFiller6, gridBagConstraints); lblbeschreibungGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblbeschreibungGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(10, 10, 5, 5); pnlVerformung.add(lblbeschreibungGruendung2, gridBagConstraints); jScrollPane14.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane14.setPreferredSize(new java.awt.Dimension(0, 70)); taBeschreibungGruendung2.setLineWrap(true); taBeschreibungGruendung2.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.beschreibung_verformung}"), taBeschreibungGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane14.setViewportView(taBeschreibungGruendung2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(10, 5, 5, 10); pnlVerformung.add(jScrollPane14, gridBagConstraints); lblZustandGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblZustandGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblZustandGruendung2, gridBagConstraints); lblSanMassnahmenGruendung2.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanMassnahmenGruendung2.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblSanMassnahmenGruendung2, gridBagConstraints); lblSanKostenAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblSanKostenAnsicht3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblSanKostenAnsicht3, gridBagConstraints); lblEingriffAnsicht3.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblEingriffAnsicht3.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlVerformung.add(lblEingriffAnsicht3, gridBagConstraints); tfZustandGruendung2.setMinimumSize(new java.awt.Dimension(100, 20)); tfZustandGruendung2.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.zustand_verformung}"), tfZustandGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); binding.setConverter(new NumberConverter()); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlVerformung.add(tfZustandGruendung2, gridBagConstraints); tfSanKostenGruendung2.setMinimumSize(new java.awt.Dimension(100, 20)); tfSanKostenGruendung2.setPreferredSize(new java.awt.Dimension(100, 20)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_kosten_verformung}"), tfSanKostenGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlVerformung.add(tfSanKostenGruendung2, gridBagConstraints); jScrollPane15.setMinimumSize(new java.awt.Dimension(26, 70)); jScrollPane15.setPreferredSize(new java.awt.Dimension(262, 70)); taSanMassnahmeGruendung2.setLineWrap(true); taSanMassnahmeGruendung2.setMinimumSize(new java.awt.Dimension(500, 70)); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_massnahme_verformung}"), taSanMassnahmeGruendung2, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jScrollPane15.setViewportView(taSanMassnahmeGruendung2); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlVerformung.add(jScrollPane15, gridBagConstraints); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${cidsBean.san_eingriff_verformung}"), cbEingriffVerformung, org.jdesktop.beansbinding.BeanProperty.create("selectedItem")); bindingGroup.addBinding(binding); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 10); pnlVerformung.add(cbEingriffVerformung, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.5; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlScrollPane.add(pnlVerformung, gridBagConstraints); jScrollPane3.setViewportView(pnlScrollPane); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; roundedScrollPanel.add(jScrollPane3, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.5; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCard1.add(roundedScrollPanel, gridBagConstraints); add(pnlCard1, "card1"); pnlCard2.setOpaque(false); pnlCard2.setLayout(new java.awt.GridBagLayout()); pnlFotos.setMinimumSize(new java.awt.Dimension(400, 200)); pnlFotos.setPreferredSize(new java.awt.Dimension(400, 200)); pnlFotos.setLayout(new java.awt.GridBagLayout()); pnlHeaderFotos.setBackground(new java.awt.Color(51, 51, 51)); pnlHeaderFotos.setForeground(new java.awt.Color(51, 51, 51)); pnlHeaderFotos.setLayout(new java.awt.FlowLayout()); lblHeaderFotos.setForeground(new java.awt.Color(255, 255, 255)); lblHeaderFotos.setText(org.openide.util.NbBundle.getMessage( MauerEditor.class, "MauerEditor.lblHeaderFotos.text")); // NOI18N pnlHeaderFotos.add(lblHeaderFotos); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlFotos.add(pnlHeaderFotos, gridBagConstraints); lblFiller9.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFiller9.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlFotos.add(lblFiller9, gridBagConstraints); lblFotos.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblFotos.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 10); pnlFotos.add(lblFotos, gridBagConstraints); jspFotoList.setMinimumSize(new java.awt.Dimension(250, 130)); lstFotos.setMinimumSize(new java.awt.Dimension(250, 130)); lstFotos.setPreferredSize(new java.awt.Dimension(250, 130)); final org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create( "${cidsBean.bilder}"); final org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings .createJListBinding( org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, lstFotos); bindingGroup.addBinding(jListBinding); lstFotos.addListSelectionListener(new javax.swing.event.ListSelectionListener() { @Override public void valueChanged(final javax.swing.event.ListSelectionEvent evt) { lstFotosValueChanged(evt); } }); jspFotoList.setViewportView(lstFotos); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 5); pnlFotos.add(jspFotoList, gridBagConstraints); pnlCtrlButtons.setOpaque(false); pnlCtrlButtons.setLayout(new java.awt.GridBagLayout()); btnAddImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_add_mini.png"))); // NOI18N btnAddImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnAddImg.text")); // NOI18N btnAddImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnAddImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5); pnlCtrlButtons.add(btnAddImg, gridBagConstraints); btnRemoveImg.setIcon(new javax.swing.ImageIcon( getClass().getResource("/de/cismet/cids/custom/objecteditors/wunda_blau/edit_remove_mini.png"))); // NOI18N btnRemoveImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnRemoveImg.text")); // NOI18N btnRemoveImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnRemoveImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridy = 1; pnlCtrlButtons.add(btnRemoveImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; pnlFotos.add(pnlCtrlButtons, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH; gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 10); pnlCard2.add(pnlFotos, gridBagConstraints); pnlVorschau.setLayout(new java.awt.GridBagLayout()); semiRoundedPanel2.setBackground(new java.awt.Color(51, 51, 51)); semiRoundedPanel2.setLayout(new java.awt.FlowLayout()); lblVorschau.setForeground(new java.awt.Color(255, 255, 255)); lblVorschau.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblVorschau.text")); // NOI18N semiRoundedPanel2.add(lblVorschau); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; pnlVorschau.add(semiRoundedPanel2, gridBagConstraints); pnlFoto.setOpaque(false); pnlFoto.setLayout(new java.awt.GridBagLayout()); lblPicture.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.lblPicture.text")); // NOI18N pnlFoto.add(lblPicture, new java.awt.GridBagConstraints()); lblBusy.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblBusy.setMaximumSize(new java.awt.Dimension(140, 40)); lblBusy.setMinimumSize(new java.awt.Dimension(140, 60)); lblBusy.setPreferredSize(new java.awt.Dimension(140, 60)); pnlFoto.add(lblBusy, new java.awt.GridBagConstraints()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; pnlVorschau.add(pnlFoto, gridBagConstraints); pnlCtrlBtn.setOpaque(false); pnlCtrlBtn.setPreferredSize(new java.awt.Dimension(100, 50)); pnlCtrlBtn.setLayout(new java.awt.GridBagLayout()); btnPrevImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-left.png"))); // NOI18N btnPrevImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnPrevImg.text")); // NOI18N btnPrevImg.setBorderPainted(false); btnPrevImg.setFocusPainted(false); btnPrevImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnPrevImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; pnlCtrlBtn.add(btnPrevImg, gridBagConstraints); btnNextImg.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/arrow-right.png"))); // NOI18N btnNextImg.setText(org.openide.util.NbBundle.getMessage(MauerEditor.class, "MauerEditor.btnNextImg.text")); // NOI18N btnNextImg.setBorderPainted(false); btnNextImg.setFocusPainted(false); btnNextImg.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(final java.awt.event.ActionEvent evt) { btnNextImgActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; pnlCtrlBtn.add(btnNextImg, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; pnlVorschau.add(pnlCtrlBtn, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridheight = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 0.8; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 10, 5, 15); pnlCard2.add(pnlVorschau, gridBagConstraints); pnlMap.setBorder(javax.swing.BorderFactory.createEtchedBorder()); pnlMap.setMinimumSize(new java.awt.Dimension(400, 200)); pnlMap.setPreferredSize(new java.awt.Dimension(400, 200)); pnlMap.setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridheight = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.VERTICAL; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 15, 5, 10); pnlCard2.add(pnlMap, gridBagConstraints); add(pnlCard2, "card2"); bindingGroup.bind(); } // </editor-fold>//GEN-END:initComponents
diff --git a/src/ro/zg/netcell/vaadin/action/application/CreateEntityHandler.java b/src/ro/zg/netcell/vaadin/action/application/CreateEntityHandler.java index 588b404..9b2cffb 100644 --- a/src/ro/zg/netcell/vaadin/action/application/CreateEntityHandler.java +++ b/src/ro/zg/netcell/vaadin/action/application/CreateEntityHandler.java @@ -1,191 +1,192 @@ /******************************************************************************* * Copyright 2011 Adrian Cristian Ionescu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package ro.zg.netcell.vaadin.action.application; import java.util.List; import java.util.Map; import ro.zg.netcell.control.CommandResponse; import ro.zg.netcell.vaadin.DataTranslationUtils; import ro.zg.netcell.vaadin.DefaultForm; import ro.zg.netcell.vaadin.DefaultForm.FormCommitEvent; import ro.zg.netcell.vaadin.DefaultForm.FormListener; import ro.zg.netcell.vaadin.action.ActionContext; import ro.zg.netcell.vaadin.action.ActionsManager; import ro.zg.netcell.vaadin.action.OpenGroupsActionHandler; import ro.zg.open_groups.OpenGroupsApplication; import ro.zg.opengroups.constants.ComplexEntityParam; import ro.zg.opengroups.vo.Entity; import ro.zg.opengroups.vo.User; import ro.zg.opengroups.vo.UserAction; import com.vaadin.terminal.UserError; import com.vaadin.ui.Button; import com.vaadin.ui.ComponentContainer; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; public class CreateEntityHandler extends OpenGroupsActionHandler { /** * */ private static final long serialVersionUID = -6631433190447717139L; @Override public void handle(ActionContext actionContext) throws Exception { ComponentContainer targetContainer = actionContext.getTargetContainer(); Entity entity = actionContext.getEntity(); targetContainer.removeAllComponents(); UserAction ua = actionContext.getUserAction(); List<String> currentUserTypes = getCurrentUserTypes(entity, actionContext.getApp()); if (!currentUserTypes.contains(ua.getUserType())) { /* current user is not allowed to execute this action */ displayLoginRequired("create." + ua.getTargetEntityComplexType().toLowerCase() + ".login.required", targetContainer); return; } DefaultForm form = getForm(entity, actionContext.getUserAction(), actionContext.getApp(), targetContainer,actionContext); targetContainer.addComponent(form); } private DefaultForm getForm(final Entity entity, final UserAction ua, final OpenGroupsApplication application, final ComponentContainer targetComponent, final ActionContext ac) { final DefaultForm form = ua.generateForm(); final Entity parentEntity = ac.getMainEntity(); // EntityDefinitionSummary actionDef = getActionsManager().getFlowDefinitionSummary(ua.getAction()); // List<InputParameter> actionInputParams = actionDef.getInputParameters(); // List<InputParameter> userInputParams = ua.getUserInputParamsList(actionInputParams); // // form.setFormFieldFactory(new DefaultFormFieldFactory(userInputParams)); // form.populateFromInputParameterList(userInputParams); form.addListener(new FormListener() { @Override public void onCommit(FormCommitEvent event) { Map<String, Object> paramsMap = DataTranslationUtils.getFormFieldsAsMap(event.getForm()); String tags = ((String) paramsMap.get("tags")); if (tags != null) { tags = tags.toLowerCase(); tags.replaceAll("\\s", ""); tags = "[" + tags + "]"; } paramsMap.put("tags", tags); User user = application.getCurrentUser(); paramsMap.put("userId", user.getUserId()); paramsMap.put("parentId", parentEntity.getId()); paramsMap.put("entityType", ua.getTargetEntityType()); String complexType = ua.getTargetEntityComplexType(); paramsMap.put("complexType", complexType); paramsMap.put("allowDuplicateTitle", getAppConfigManager().getComplexEntityBooleanParam(complexType, ComplexEntityParam.ALLOW_DUPLICATE_TITLE)); CommandResponse response = executeAction(new ActionContext(ua, application, entity), paramsMap); if (response.isSuccessful()) { if ("titleExists".equals(response.getValue("exit"))) { String message = application.getMessage(ua.getTargetEntityType().toLowerCase() + ".already.exists.with.title"); form.setComponentError(new UserError(message)); } else { long entityId = (Long) response.getValue("currentEntityId"); displaySuccessfulMessage(entity, ua, application, targetComponent, entityId,ac); } } /* refresh parent */ application.refreshEntity(parentEntity,ac); } }); return form; } private void displaySuccessfulMessage(final Entity entity, final UserAction ua, final OpenGroupsApplication app, final ComponentContainer targetComponent, final long entityId, final ActionContext ac) { /* store current target component */ // final ComponentContainer targetComponent = app.getTargetComponent(); String entityTypeLowerCase = ua.getTargetEntityType().toLowerCase(); String createdSuccessfullyMessage = app.getMessage(entityTypeLowerCase + ".created.successfully"); String createNewMessage = app.getMessage("create.new." + entityTypeLowerCase); String openCreatedMessage = app.getMessage("open.created." + entityTypeLowerCase); VerticalLayout container = new VerticalLayout(); container.setSizeFull(); Label success = new Label(createdSuccessfullyMessage); container.addComponent(success); HorizontalLayout linksContainer = new HorizontalLayout(); linksContainer.setSpacing(true); Button openCreated = new Button(openCreatedMessage); linksContainer.addComponent(openCreated); openCreated.addListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { List<String> subtypesList = getAppConfigManager().getSubtypesForComplexType( ua.getTargetEntityComplexType()); if (subtypesList != null) { Entity entity = new Entity(entityId); // getActionsManager().executeAction(ActionsManager.REFRESH_SELECTED_ENTITY, entity, app, null, false,ac); // getActionsManager().executeAction(ActionsManager.OPEN_ENTITY_IN_TAB, entity, app, null, false,ac); app.openInActiveWindow(entity); } /* if no subtypes open the parent entity */ else { Entity parentEntity = ac.getMainEntity(); parentEntity.getState().setEntityTypeVisible(true); parentEntity.getState().setDesiredActionsPath(ua.getTargetEntityComplexType() + "/LIST"); // app.getTemporaryTab(parentEntity).setRefreshOn(true); - getActionsManager().executeAction(ActionsManager.OPEN_ENTITY_IN_TAB, parentEntity, app, null, false,ac); +// getActionsManager().executeAction(ActionsManager.OPEN_ENTITY_IN_TAB, parentEntity, app, null, false,ac); + app.openInActiveWindow(parentEntity); } } }); Button createNew = new Button(createNewMessage); linksContainer.addComponent(createNew); createNew.addListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { /* recall the handle method on this handler */ // app.setTargetComponent(targetComponent); ua.executeHandler(entity, app, targetComponent,ac); } }); container.addComponent(linksContainer); targetComponent.removeAllComponents(); targetComponent.addComponent(container); } private void displayLoginRequired(String messageKey, ComponentContainer targetContainer) { String msg = getMessage(messageKey); Label l = new Label(msg); targetContainer.addComponent(l); } }
true
true
private void displaySuccessfulMessage(final Entity entity, final UserAction ua, final OpenGroupsApplication app, final ComponentContainer targetComponent, final long entityId, final ActionContext ac) { /* store current target component */ // final ComponentContainer targetComponent = app.getTargetComponent(); String entityTypeLowerCase = ua.getTargetEntityType().toLowerCase(); String createdSuccessfullyMessage = app.getMessage(entityTypeLowerCase + ".created.successfully"); String createNewMessage = app.getMessage("create.new." + entityTypeLowerCase); String openCreatedMessage = app.getMessage("open.created." + entityTypeLowerCase); VerticalLayout container = new VerticalLayout(); container.setSizeFull(); Label success = new Label(createdSuccessfullyMessage); container.addComponent(success); HorizontalLayout linksContainer = new HorizontalLayout(); linksContainer.setSpacing(true); Button openCreated = new Button(openCreatedMessage); linksContainer.addComponent(openCreated); openCreated.addListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { List<String> subtypesList = getAppConfigManager().getSubtypesForComplexType( ua.getTargetEntityComplexType()); if (subtypesList != null) { Entity entity = new Entity(entityId); // getActionsManager().executeAction(ActionsManager.REFRESH_SELECTED_ENTITY, entity, app, null, false,ac); // getActionsManager().executeAction(ActionsManager.OPEN_ENTITY_IN_TAB, entity, app, null, false,ac); app.openInActiveWindow(entity); } /* if no subtypes open the parent entity */ else { Entity parentEntity = ac.getMainEntity(); parentEntity.getState().setEntityTypeVisible(true); parentEntity.getState().setDesiredActionsPath(ua.getTargetEntityComplexType() + "/LIST"); // app.getTemporaryTab(parentEntity).setRefreshOn(true); getActionsManager().executeAction(ActionsManager.OPEN_ENTITY_IN_TAB, parentEntity, app, null, false,ac); } } }); Button createNew = new Button(createNewMessage); linksContainer.addComponent(createNew); createNew.addListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { /* recall the handle method on this handler */ // app.setTargetComponent(targetComponent); ua.executeHandler(entity, app, targetComponent,ac); } }); container.addComponent(linksContainer); targetComponent.removeAllComponents(); targetComponent.addComponent(container); }
private void displaySuccessfulMessage(final Entity entity, final UserAction ua, final OpenGroupsApplication app, final ComponentContainer targetComponent, final long entityId, final ActionContext ac) { /* store current target component */ // final ComponentContainer targetComponent = app.getTargetComponent(); String entityTypeLowerCase = ua.getTargetEntityType().toLowerCase(); String createdSuccessfullyMessage = app.getMessage(entityTypeLowerCase + ".created.successfully"); String createNewMessage = app.getMessage("create.new." + entityTypeLowerCase); String openCreatedMessage = app.getMessage("open.created." + entityTypeLowerCase); VerticalLayout container = new VerticalLayout(); container.setSizeFull(); Label success = new Label(createdSuccessfullyMessage); container.addComponent(success); HorizontalLayout linksContainer = new HorizontalLayout(); linksContainer.setSpacing(true); Button openCreated = new Button(openCreatedMessage); linksContainer.addComponent(openCreated); openCreated.addListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { List<String> subtypesList = getAppConfigManager().getSubtypesForComplexType( ua.getTargetEntityComplexType()); if (subtypesList != null) { Entity entity = new Entity(entityId); // getActionsManager().executeAction(ActionsManager.REFRESH_SELECTED_ENTITY, entity, app, null, false,ac); // getActionsManager().executeAction(ActionsManager.OPEN_ENTITY_IN_TAB, entity, app, null, false,ac); app.openInActiveWindow(entity); } /* if no subtypes open the parent entity */ else { Entity parentEntity = ac.getMainEntity(); parentEntity.getState().setEntityTypeVisible(true); parentEntity.getState().setDesiredActionsPath(ua.getTargetEntityComplexType() + "/LIST"); // app.getTemporaryTab(parentEntity).setRefreshOn(true); // getActionsManager().executeAction(ActionsManager.OPEN_ENTITY_IN_TAB, parentEntity, app, null, false,ac); app.openInActiveWindow(parentEntity); } } }); Button createNew = new Button(createNewMessage); linksContainer.addComponent(createNew); createNew.addListener(new ClickListener() { @Override public void buttonClick(ClickEvent event) { /* recall the handle method on this handler */ // app.setTargetComponent(targetComponent); ua.executeHandler(entity, app, targetComponent,ac); } }); container.addComponent(linksContainer); targetComponent.removeAllComponents(); targetComponent.addComponent(container); }
diff --git a/component/src/main/java/com/celements/calendar/search/EventSearchResult.java b/component/src/main/java/com/celements/calendar/search/EventSearchResult.java index fce5656..bf2ab63 100644 --- a/component/src/main/java/com/celements/calendar/search/EventSearchResult.java +++ b/component/src/main/java/com/celements/calendar/search/EventSearchResult.java @@ -1,158 +1,159 @@ package com.celements.calendar.search; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.celements.calendar.Event; import com.celements.calendar.IEvent; import com.celements.web.service.IWebUtilsService; import com.xpn.xwiki.XWikiContext; import com.xpn.xwiki.plugin.lucene.LucenePlugin; import com.xpn.xwiki.plugin.lucene.SearchResult; import com.xpn.xwiki.plugin.lucene.SearchResults; import com.xpn.xwiki.web.Utils; public class EventSearchResult { private IWebUtilsService webUtils; private static Log LOGGER = LogFactory.getFactory().getInstance( EventSearchResult.class); private SearchResults searchResultsCache; private LucenePlugin lucenePlugin; private final String luceneQuery; private final List<String> sortFields; private final boolean skipChecks; private final XWikiContext context; EventSearchResult(String luceneQuery, List<String> sortFields, boolean skipChecks, XWikiContext context) { this.luceneQuery = luceneQuery; this.sortFields = (sortFields != null ? Collections.unmodifiableList( new ArrayList<String>(sortFields)) : null); this.skipChecks = skipChecks; this.context = context; } public String getLuceneQuery() { return luceneQuery; } public List<String> getSortFields() { return sortFields; } boolean getSkipChecks() { return skipChecks; } /** * * @return all events */ public List<IEvent> getEventList() { return getEventList(0, 0); } /** * * @param offset from 0 to (size - 1) * @param limit all remaining events are returned for values < 0 or >= (size - 1) * @return selected events */ public List<IEvent> getEventList(int offset, int limit) { SearchResults results = luceneSearch(); if (results != null) { List<SearchResult> list; if (limit > 0) { list = results.getResults(offset + 1, limit); } else { list = results.getResults(offset + 1, results.getHitcount()); } List<IEvent> eventList = convertToEventList(list); if (eventList == null) { LOGGER.error("prevent returning null in getEventList of EvemtSearchResult for" + " offset [" + offset + "], limit [" + limit + "], list [" + list + "], luceneQuery [" + luceneQuery + "]."); eventList = Collections.emptyList(); } return eventList; } else { LOGGER.warn("getEventList: luceneSearch returned 'null' value for offset [" + offset + "] and limit [" + limit + "] on luceneQuery [" + luceneQuery +"]."); return null; } } private List<IEvent> convertToEventList(List<SearchResult> results) { List<IEvent> eventList = new ArrayList<IEvent>(); for (SearchResult result : results) { eventList.add(new Event(getWebUtils().resolveDocumentReference( result.getFullName()))); } return eventList; } public int getSize() { int hitcount = luceneSearch().getHitcount(); LOGGER.debug("EventSearchResult got hitcount [" + hitcount + "] for query [" + luceneQuery + "]."); return hitcount; } SearchResults luceneSearch() { if (searchResultsCache == null) { try { String[] sortFieldsArray = (sortFields != null ? sortFields.toArray( new String[sortFields.size()]) : null); if (skipChecks) { searchResultsCache = getLucenePlugin().getSearchResultsWithoutChecks( - luceneQuery, sortFieldsArray, null, "default,de", context); + luceneQuery, sortFieldsArray, null, "default," + context.getLanguage(), + context); } else { searchResultsCache = getLucenePlugin().getSearchResults(luceneQuery, - sortFieldsArray, null, "default,de", context); + sortFieldsArray, null, "default," + context.getLanguage(), context); } LOGGER.trace("luceneSearch: created new searchResults for query [" + luceneQuery + "]."); } catch (Exception exception) { LOGGER.error("Unable to get lucene search results for query '" + luceneQuery + "'", exception); } } else { LOGGER.trace("luceneSearch: returning cached searchResults for query [" + luceneQuery + "]."); } return searchResultsCache; } private LucenePlugin getLucenePlugin() { if (lucenePlugin == null) { lucenePlugin = (LucenePlugin) context.getWiki().getPlugin("lucene", context); } return lucenePlugin; } private IWebUtilsService getWebUtils() { if(webUtils == null){ webUtils = Utils.getComponent(IWebUtilsService.class); } return webUtils; } @Override public String toString() { return "EventSearchResult [luceneQuery=" + luceneQuery + ", sortFields=" + sortFields + "]"; } void injectLucenePlugin(LucenePlugin lucenePlugin) { this.lucenePlugin = lucenePlugin; } }
false
true
SearchResults luceneSearch() { if (searchResultsCache == null) { try { String[] sortFieldsArray = (sortFields != null ? sortFields.toArray( new String[sortFields.size()]) : null); if (skipChecks) { searchResultsCache = getLucenePlugin().getSearchResultsWithoutChecks( luceneQuery, sortFieldsArray, null, "default,de", context); } else { searchResultsCache = getLucenePlugin().getSearchResults(luceneQuery, sortFieldsArray, null, "default,de", context); } LOGGER.trace("luceneSearch: created new searchResults for query [" + luceneQuery + "]."); } catch (Exception exception) { LOGGER.error("Unable to get lucene search results for query '" + luceneQuery + "'", exception); } } else { LOGGER.trace("luceneSearch: returning cached searchResults for query [" + luceneQuery + "]."); } return searchResultsCache; }
SearchResults luceneSearch() { if (searchResultsCache == null) { try { String[] sortFieldsArray = (sortFields != null ? sortFields.toArray( new String[sortFields.size()]) : null); if (skipChecks) { searchResultsCache = getLucenePlugin().getSearchResultsWithoutChecks( luceneQuery, sortFieldsArray, null, "default," + context.getLanguage(), context); } else { searchResultsCache = getLucenePlugin().getSearchResults(luceneQuery, sortFieldsArray, null, "default," + context.getLanguage(), context); } LOGGER.trace("luceneSearch: created new searchResults for query [" + luceneQuery + "]."); } catch (Exception exception) { LOGGER.error("Unable to get lucene search results for query '" + luceneQuery + "'", exception); } } else { LOGGER.trace("luceneSearch: returning cached searchResults for query [" + luceneQuery + "]."); } return searchResultsCache; }
diff --git a/src/de/avdclan/arma2mapconverter/SQM.java b/src/de/avdclan/arma2mapconverter/SQM.java index 08e3c50..49b4dd3 100644 --- a/src/de/avdclan/arma2mapconverter/SQM.java +++ b/src/de/avdclan/arma2mapconverter/SQM.java @@ -1,358 +1,363 @@ package de.avdclan.arma2mapconverter; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.DateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.UUID; import org.apache.log4j.Logger; public class SQM { private TypeClass rootType = new TypeClass("units", null); private TypeClass markers = new TypeClass("markers", null); private static Logger logger = Logger.getLogger(SQM.class); private BufferedReader reader; private int groupCountWest = 0; private int groupCountEast = 0; private int groupCountGuer = 0; private int groupCountCiv = 0; private File source; public void load(File mission) throws FileNotFoundException { logger.debug("Loading SQM Mission: " + mission.getAbsolutePath()); this.source = mission; reader = new BufferedReader(new FileReader(mission)); String line; try { while((line = reader.readLine()) != null) { String input = line.replaceAll("^\\s+", ""); String type = null; if(input.startsWith("class")) { String[] spl = line.split(" ", 2); type = spl[1]; } if(type != null) { if(type.equals("Groups")) { logger.debug("Processing groups... "); parse(line, rootType); logger.debug("Groups processed. " + rootType.getFullCount() + " Groups processed."); } if(type.equals("Markers")) { logger.debug("Processing markers... "); parse(line, markers); logger.debug("Markers processed. " + markers.getFullCount() + " Markers processed."); } } } } catch (IOException e) { // TODO Auto-generated catch block logger.error(e); } logger.debug("Loaded."); } /** * This is the parsing algorithm. * If you know a better way, feel free to change it. * * Please also send your changes to the author. * * * @param input * @throws IOException */ private void parse(String input, TypeClass parent) throws IOException { String line = input.replaceAll("^\\s+", ""); if(line.startsWith("class")) { String[] spl = line.split(" ", 2); TypeClass typeClass = new TypeClass(spl[1], parent); parent.getChilds().add(typeClass); while(! (line = reader.readLine().replaceAll("^\\s+", "")).startsWith("}")) { parse(line, typeClass); } } if(parent.toString().startsWith("Vehicles")) { if(parent.getObject() == null) { parent.setObject(new Vehicle()); } TypeClass p = parent.getParent(); if(p.toString().startsWith("Item")) { ((Vehicle)parent.getObject()).setSide(((Item)p.getObject()).getSide()); } } else if(parent.toString().startsWith("Markers")) { if(parent.getObject() == null) { parent.setObject(new Markers()); } TypeClass p = parent.getParent(); if(p.toString().startsWith("Item")) { ((Markers)parent.getObject()).setSide(((Item)p.getObject()).getSide()); } } else if(parent.toString().startsWith("Item")) { if(parent.getObject() == null) { parent.setObject(new Item(parent.toString())); } if(line.startsWith("position[]=")) { String[] tmp = line.split("=", 2); tmp = tmp[1].split(",", 3); String x, y, z; x = tmp[0].replaceAll("\\{", ""); z = tmp[1]; y = tmp[2].replaceAll("\\}\\;", ""); ((Item)parent.getObject()).setPosition(new Position(x, y, "0")); } if(line.startsWith("id=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setId(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("side=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setSide(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("vehicle=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setVehicle(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("skill=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setSkill(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("leader=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setLeader(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("init=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setInit(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("name=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("markerType=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setMarkerType(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("type=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setType(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("rank=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setRank(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("presenceCondition=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setPresenceCondition(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("azimut=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setAzimut(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("colorName=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setColorName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("fillName=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setFillName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("a=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setA(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("b=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setB(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("angle=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setAngle(tmp[1].replaceAll("\\;", "")); } + else + if(line.startsWith("text=")) { + String[] tmp = line.split("=", 2); + ((Item)parent.getObject()).setText(tmp[1].replaceAll("\\;", "")); + } } else { // unsupported class } } public SQF toSQF() { SQF sqf = new SQF(); String code = "" + "/* converted with Arma2MapConverter v" + Arma2MapConverter.VERSION + "\n" + " *\n" + " * Source: " + source.getAbsolutePath() + "\n" + " * Date: " + DateFormat.getInstance().format(Calendar.getInstance().getTime()) + "\n" + " */\n\n"; code += "_westHQ = createCenter west;\n" + "_eastHQ = createCenter east;\n" + "_guerHQ = createCenter resistance;\n" + "_civHQ = createCenter civilian;\n"; code += "\n\n// UNIT CREATION\n"; code += generateSQF(rootType); code += "\n\n// MARKER CREATION\n"; code += generateSQF(markers); sqf.setCode(code); return sqf; } private String generateSQF(TypeClass typeClass) { String code = ""; int groupCount = 0; for(TypeClass tc : typeClass.getChilds()) { if(tc.equals("Markers")) { String side = ((Markers)tc.getObject()).getSide().toLowerCase(); for(TypeClass items : tc.getChilds()) { Item item = (Item) items.getObject(); if(item.getName() == null) { // generate unique unit name item.setName("marker_" + UUID.randomUUID().toString().replaceAll("-", "")); } code += "_marker = createMarker[" + item.getName() + ", [" + item.getPosition().getX() + ", " + item.getPosition().getY() + "]];\n" + "_marker setMarkerShape " + item.getType() + ";\n" + "_marker setMarkerType " + item.getMarkerType() + ";\n" + "_marker setMarkerSize [" + item.getA() + ", " + item.getB() + "];\n"; /* _this setMarkerText "This is a Text"; _this setMarkerType "Faction_BLUFOR_EP1"; _this setMarkerColor "ColorYellow"; _this setMarkerBrush "Horizontal"; _this setMarkerSize [12, 144]; */ if(item.getText() != null) { code += "_marker setMarkerText " + item.getText() + ";\n"; } if(item.getColorName() != null) { code += "_marker setMarkerColor " + item.getColorName() +";\n"; } if(item.getFillName() != null) { code += "_marker setMarkerBrush " + item.getFillName() +";\n"; } } } if(tc.equals("Vehicles")) { String side = ((Vehicle)tc.getObject()).getSide().toLowerCase(); String group = "_group_" + side + "_" + getGroupCound(side); code += "\n// group " + group + "\n" + group + " = createGroup _" + side +"HQ;\n"; for(TypeClass items : tc.getChilds()) { Item item = (Item) items.getObject(); if(item.getName() == null) { // generate unique unit name item.setName("autogen_" + UUID.randomUUID().toString().replaceAll("-", "")); } code += "\n// begin " + item.getName() +", part of group " + group + "\n"; code += "if (" + item.getPresenceCondition() + ") then\n{"; if(item.getSide().equals("EMPTY")) { code += "\n" + "\t" + item.getName() + " = createVehicle [" + item.getVehicle() + ", " + item.getPosition() + ", [], 0, \"CAN_COLLIDE\"];\n"; } else { code += "\n" + "\t" + item.getName() + " = " + group + " createUnit [" + item.getVehicle() + ", " + item.getPosition() + ", [], 0, \"CAN_COLLIDE\"];\n" + // this is VERY dirty.... "\t// this is VERY dirty and only used because I don't want to create\n" + "\t// arrays for vehicles, units and stuff to check if the classname\n" + "\t// is a vehicle, an unit, and so on. this just works.\n" + "\t// what it does is if the unit is not alive after creation (because it should be a manned vehicle)\n" + "\t// it will be created with createVehicle and manned with the BIS_fnc_spawnCrew function.\n" + "\tif(!alive " + item.getName() + ") then {\n" + "\t\t" + item.getName() + " = createVehicle [" + item.getVehicle() + ", " + item.getPosition() + ", [], 0, \"CAN_COLLIDE\"];\n" + "\t\t_group = createGroup _" + item.getSide().toLowerCase() + "HQ;\n" + "\t\t[" + item.getName() + ", _group] call BIS_fnc_spawnCrew;\n" + "\t};\n"; } if(item.getInit() != null) { code += "\t" + item.getName() + " setVehicleInit " + item.getInit() + ";\n"; } if(item.getAzimut() != null) { code += "\t" + item.getName() + " setDir " + item.getAzimut() + ";\n"; } if(item.getSkill() != null && !item.getSide().equals("EMPTY")) { code += "\t" + item.getName() + " setUnitAbility " + item.getSkill() +";\n"; } if(item.getRank() != null && !item.getSide().equals("EMPTY")) { code += "\t" + item.getName() + " setRank " + item.getRank() + ";\n"; } if(item.getLeader() != null && !item.getSide().equals("EMPTY")) { code += "\tif(true) then { " + group + " selectLeader " + item.getName() + "; };\n"; } code += "};\n// end of " + item.getName() + "\n"; } } else { code += generateSQF(tc); } } return code; } private String getGroupCound(String side) { if(side.equals("west")) { ++groupCountWest; return String.valueOf(groupCountWest); } if(side.equals("east")) { ++groupCountEast; return String.valueOf(groupCountEast); } if(side.equals("guer")) { ++groupCountGuer; return String.valueOf(groupCountGuer); } ++groupCountCiv; return String.valueOf(groupCountCiv); } }
true
true
private void parse(String input, TypeClass parent) throws IOException { String line = input.replaceAll("^\\s+", ""); if(line.startsWith("class")) { String[] spl = line.split(" ", 2); TypeClass typeClass = new TypeClass(spl[1], parent); parent.getChilds().add(typeClass); while(! (line = reader.readLine().replaceAll("^\\s+", "")).startsWith("}")) { parse(line, typeClass); } } if(parent.toString().startsWith("Vehicles")) { if(parent.getObject() == null) { parent.setObject(new Vehicle()); } TypeClass p = parent.getParent(); if(p.toString().startsWith("Item")) { ((Vehicle)parent.getObject()).setSide(((Item)p.getObject()).getSide()); } } else if(parent.toString().startsWith("Markers")) { if(parent.getObject() == null) { parent.setObject(new Markers()); } TypeClass p = parent.getParent(); if(p.toString().startsWith("Item")) { ((Markers)parent.getObject()).setSide(((Item)p.getObject()).getSide()); } } else if(parent.toString().startsWith("Item")) { if(parent.getObject() == null) { parent.setObject(new Item(parent.toString())); } if(line.startsWith("position[]=")) { String[] tmp = line.split("=", 2); tmp = tmp[1].split(",", 3); String x, y, z; x = tmp[0].replaceAll("\\{", ""); z = tmp[1]; y = tmp[2].replaceAll("\\}\\;", ""); ((Item)parent.getObject()).setPosition(new Position(x, y, "0")); } if(line.startsWith("id=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setId(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("side=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setSide(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("vehicle=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setVehicle(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("skill=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setSkill(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("leader=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setLeader(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("init=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setInit(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("name=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("markerType=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setMarkerType(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("type=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setType(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("rank=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setRank(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("presenceCondition=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setPresenceCondition(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("azimut=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setAzimut(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("colorName=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setColorName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("fillName=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setFillName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("a=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setA(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("b=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setB(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("angle=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setAngle(tmp[1].replaceAll("\\;", "")); } } else { // unsupported class } }
private void parse(String input, TypeClass parent) throws IOException { String line = input.replaceAll("^\\s+", ""); if(line.startsWith("class")) { String[] spl = line.split(" ", 2); TypeClass typeClass = new TypeClass(spl[1], parent); parent.getChilds().add(typeClass); while(! (line = reader.readLine().replaceAll("^\\s+", "")).startsWith("}")) { parse(line, typeClass); } } if(parent.toString().startsWith("Vehicles")) { if(parent.getObject() == null) { parent.setObject(new Vehicle()); } TypeClass p = parent.getParent(); if(p.toString().startsWith("Item")) { ((Vehicle)parent.getObject()).setSide(((Item)p.getObject()).getSide()); } } else if(parent.toString().startsWith("Markers")) { if(parent.getObject() == null) { parent.setObject(new Markers()); } TypeClass p = parent.getParent(); if(p.toString().startsWith("Item")) { ((Markers)parent.getObject()).setSide(((Item)p.getObject()).getSide()); } } else if(parent.toString().startsWith("Item")) { if(parent.getObject() == null) { parent.setObject(new Item(parent.toString())); } if(line.startsWith("position[]=")) { String[] tmp = line.split("=", 2); tmp = tmp[1].split(",", 3); String x, y, z; x = tmp[0].replaceAll("\\{", ""); z = tmp[1]; y = tmp[2].replaceAll("\\}\\;", ""); ((Item)parent.getObject()).setPosition(new Position(x, y, "0")); } if(line.startsWith("id=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setId(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("side=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setSide(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("vehicle=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setVehicle(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("skill=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setSkill(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("leader=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setLeader(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("init=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setInit(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("name=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("markerType=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setMarkerType(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("type=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setType(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("rank=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setRank(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("presenceCondition=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setPresenceCondition(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("azimut=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setAzimut(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("colorName=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setColorName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("fillName=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setFillName(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("a=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setA(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("b=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setB(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("angle=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setAngle(tmp[1].replaceAll("\\;", "")); } else if(line.startsWith("text=")) { String[] tmp = line.split("=", 2); ((Item)parent.getObject()).setText(tmp[1].replaceAll("\\;", "")); } } else { // unsupported class } }
diff --git a/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java b/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java index 6a5dc58..5a0a937 100644 --- a/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java +++ b/src/main/java/de/hydrox/bukkit/DroxPerms/DroxPlayerCommands.java @@ -1,98 +1,95 @@ package de.hydrox.bukkit.DroxPerms; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class DroxPlayerCommands implements CommandExecutor { private DroxPerms plugin; public DroxPlayerCommands(DroxPerms plugin) { this.plugin = plugin; } public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { Player caller = null; if (sender instanceof Player) { caller = (Player) sender; } boolean result = false; if (split.length == 0) { return false; } else if (caller != null && caller.getName().equalsIgnoreCase(split[1]) && !(sender.hasPermission("droxperms.players.self"))) { sender.sendMessage("You don't have permission to modify your Permissions."); return true; - } else if (!(sender.hasPermission("droxperms.players.others"))) { - sender.sendMessage("You don't have permission to modify other Players Permissions."); - return true; } // add permission if (split[0].equalsIgnoreCase("addperm")) { if (split.length == 3) { // add global permission result = plugin.dataProvider.addPlayerPermission(sender, split[1], null, split[2]); } else if (split.length == 4) { // add world permission result = plugin.dataProvider.addPlayerPermission(sender, split[1], split[3], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // remove permission if (split[0].equalsIgnoreCase("remperm")) { if (split.length == 3) { // remove global permission result = plugin.dataProvider.removePlayerPermission(sender, split[1], null, split[2]); } else if (split.length == 4) { // remove world permission result = plugin.dataProvider.removePlayerPermission(sender, split[1], split[3], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // add subgroup if (split[0].equalsIgnoreCase("addsub")) { if (split.length == 3) { result = plugin.dataProvider.addPlayerSubgroup(sender, split[1], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // remove subgroup if (split[0].equalsIgnoreCase("remperm")) { if (split.length == 3) { result = plugin.dataProvider.removePlayerSubgroup(sender, split[1],split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // set group if (split[0].equalsIgnoreCase("setgroup")) { if (split.length == 3) { result = plugin.dataProvider.setPlayerGroup(sender, split[1],split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // set group if (split[0].equalsIgnoreCase("has")) { if (split.length == 3) { result = plugin.getServer().getPlayer(split[1]).hasPermission(split[2]); if (result) { sender.sendMessage(split[1] + " has permission for " + split[2]); } else { sender.sendMessage(split[1] + " doesn't have permission for " + split[2]); } } } return true; } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { Player caller = null; if (sender instanceof Player) { caller = (Player) sender; } boolean result = false; if (split.length == 0) { return false; } else if (caller != null && caller.getName().equalsIgnoreCase(split[1]) && !(sender.hasPermission("droxperms.players.self"))) { sender.sendMessage("You don't have permission to modify your Permissions."); return true; } else if (!(sender.hasPermission("droxperms.players.others"))) { sender.sendMessage("You don't have permission to modify other Players Permissions."); return true; } // add permission if (split[0].equalsIgnoreCase("addperm")) { if (split.length == 3) { // add global permission result = plugin.dataProvider.addPlayerPermission(sender, split[1], null, split[2]); } else if (split.length == 4) { // add world permission result = plugin.dataProvider.addPlayerPermission(sender, split[1], split[3], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // remove permission if (split[0].equalsIgnoreCase("remperm")) { if (split.length == 3) { // remove global permission result = plugin.dataProvider.removePlayerPermission(sender, split[1], null, split[2]); } else if (split.length == 4) { // remove world permission result = plugin.dataProvider.removePlayerPermission(sender, split[1], split[3], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // add subgroup if (split[0].equalsIgnoreCase("addsub")) { if (split.length == 3) { result = plugin.dataProvider.addPlayerSubgroup(sender, split[1], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // remove subgroup if (split[0].equalsIgnoreCase("remperm")) { if (split.length == 3) { result = plugin.dataProvider.removePlayerSubgroup(sender, split[1],split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // set group if (split[0].equalsIgnoreCase("setgroup")) { if (split.length == 3) { result = plugin.dataProvider.setPlayerGroup(sender, split[1],split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // set group if (split[0].equalsIgnoreCase("has")) { if (split.length == 3) { result = plugin.getServer().getPlayer(split[1]).hasPermission(split[2]); if (result) { sender.sendMessage(split[1] + " has permission for " + split[2]); } else { sender.sendMessage(split[1] + " doesn't have permission for " + split[2]); } } } return true; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] split) { Player caller = null; if (sender instanceof Player) { caller = (Player) sender; } boolean result = false; if (split.length == 0) { return false; } else if (caller != null && caller.getName().equalsIgnoreCase(split[1]) && !(sender.hasPermission("droxperms.players.self"))) { sender.sendMessage("You don't have permission to modify your Permissions."); return true; } // add permission if (split[0].equalsIgnoreCase("addperm")) { if (split.length == 3) { // add global permission result = plugin.dataProvider.addPlayerPermission(sender, split[1], null, split[2]); } else if (split.length == 4) { // add world permission result = plugin.dataProvider.addPlayerPermission(sender, split[1], split[3], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // remove permission if (split[0].equalsIgnoreCase("remperm")) { if (split.length == 3) { // remove global permission result = plugin.dataProvider.removePlayerPermission(sender, split[1], null, split[2]); } else if (split.length == 4) { // remove world permission result = plugin.dataProvider.removePlayerPermission(sender, split[1], split[3], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // add subgroup if (split[0].equalsIgnoreCase("addsub")) { if (split.length == 3) { result = plugin.dataProvider.addPlayerSubgroup(sender, split[1], split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // remove subgroup if (split[0].equalsIgnoreCase("remperm")) { if (split.length == 3) { result = plugin.dataProvider.removePlayerSubgroup(sender, split[1],split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // set group if (split[0].equalsIgnoreCase("setgroup")) { if (split.length == 3) { result = plugin.dataProvider.setPlayerGroup(sender, split[1],split[2]); } plugin.refreshPlayer(plugin.getServer().getPlayer(split[1])); return result; } // set group if (split[0].equalsIgnoreCase("has")) { if (split.length == 3) { result = plugin.getServer().getPlayer(split[1]).hasPermission(split[2]); if (result) { sender.sendMessage(split[1] + " has permission for " + split[2]); } else { sender.sendMessage(split[1] + " doesn't have permission for " + split[2]); } } } return true; }
diff --git a/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java b/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java index 3942a11a..bd502978 100644 --- a/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java +++ b/patientview-parent/patientview/src/main/java/org/patientview/repository/impl/PatientDaoImpl.java @@ -1,374 +1,374 @@ /* * PatientView * * Copyright (c) Worth Solutions Limited 2004-2013 * * This file is part of PatientView. * * PatientView is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * PatientView is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with PatientView in a file * titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package PatientView * @link http://www.patientview.org * @author PatientView <[email protected]> * @copyright Copyright (c) 2004-2013, Worth Solutions Limited * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ package org.patientview.repository.impl; import org.patientview.model.Patient; import org.patientview.model.Patient_; import org.patientview.model.Specialty; import org.patientview.patientview.logon.PatientLogonWithTreatment; import org.patientview.repository.AbstractHibernateDAO; import org.patientview.repository.PatientDao; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @Repository(value = "patientDao") public class PatientDaoImpl extends AbstractHibernateDAO<Patient> implements PatientDao { private JdbcTemplate jdbcTemplate; @Inject private DataSource dataSource; @PostConstruct public void init() { jdbcTemplate = new JdbcTemplate(dataSource); } @Override public Patient get(Long id) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class); Root<Patient> from = criteria.from(Patient.class); List<Predicate> wherePredicates = new ArrayList<Predicate>(); wherePredicates.add(builder.equal(from.get(Patient_.id), id)); buildWhereClause(criteria, wherePredicates); try { return getEntityManager().createQuery(criteria).getSingleResult(); } catch (Exception e) { return null; } } @Override public Patient get(String nhsno, String unitcode) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class); Root<Patient> from = criteria.from(Patient.class); List<Predicate> wherePredicates = new ArrayList<Predicate>(); wherePredicates.add(builder.equal(from.get(Patient_.nhsno), nhsno)); wherePredicates.add(builder.equal(from.get(Patient_.unitcode), unitcode)); buildWhereClause(criteria, wherePredicates); try { return getEntityManager().createQuery(criteria).getSingleResult(); } catch (Exception e) { return null; } } @Override public List<Patient> getByNhsNo(String nhsNo) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class); Root<Patient> from = criteria.from(Patient.class); List<Predicate> wherePredicates = new ArrayList<Predicate>(); wherePredicates.add(builder.equal(from.get(Patient_.nhsno), nhsNo)); buildWhereClause(criteria, wherePredicates); try { return getEntityManager().createQuery(criteria).getResultList(); } catch (Exception e) { return null; } } @Override public void delete(String nhsno, String unitcode) { // TODO Change this for 1.3 if (nhsno == null || nhsno.length() == 0 || unitcode == null || unitcode.length() == 0) { throw new IllegalArgumentException("Required parameters nhsno and unitcode to delete patient"); } Patient patient = get(nhsno, unitcode); if (patient != null) { delete(patient); } } @Override public List<Patient> get(String centreCode) { CriteriaBuilder builder = getEntityManager().getCriteriaBuilder(); CriteriaQuery<Patient> criteria = builder.createQuery(Patient.class); Root<Patient> from = criteria.from(Patient.class); List<Predicate> wherePredicates = new ArrayList<Predicate>(); wherePredicates.add(builder.equal(from.get(Patient_.unitcode), centreCode)); buildWhereClause(criteria, wherePredicates); return getEntityManager().createQuery(criteria).getResultList(); } //todo refactor into one query with the one below //todo PERFORMANCE FIX: commented out the emailverification table to improve query speed. @Override public List getUnitPatientsWithTreatmentDao(String unitcode, String nhsno, String name, boolean showgps, Specialty specialty) { StringBuilder query = new StringBuilder(); query.append("SELECT usr.username "); query.append(", usr.password "); query.append(", usr.name "); query.append(", usr.email "); query.append(", usr.emailverified "); query.append(", usr.accountlocked "); query.append(", usm.nhsno "); query.append(", usm.unitcode "); query.append(", null lastverificationdate "); query.append(", usr.firstlogon "); query.append(", usr.lastlogon "); query.append(", ptt.treatment "); query.append(", ptt.dateofbirth "); query.append(", ptt.rrtModality "); query.append(", psl.lastdatadate "); query.append("FROM USER usr "); query.append("INNER JOIN usermapping usm ON usm.username = usr.username "); - query.append("INNER JOIN patient ptt ON usm.nhsno = ptt.nhsno "); + query.append("LEFT JOIN patient ptt ON usm.nhsno = ptt.nhsno "); query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id "); // query.append("LEFT JOIN emailverification emv ON usr.username = emv.username "); query.append("LEFT JOIN pv_user_log psl ON usm.nhsno = psl.nhsno "); query.append("WHERE str.role = 'patient' "); query.append("AND usr.username = usm.username "); query.append("AND usr.id = str.user_id "); query.append("AND usm.unitcode <> 'PATIENT' "); query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL "); query.append("AND usm.unitcode = ? "); if (StringUtils.hasText(nhsno)) { query.append("AND usm.nhsno LIKE ? "); } if (StringUtils.hasText(name)) { query.append("AND usr.name LIKE ? "); } if (!showgps) { query.append("AND usr.name NOT LIKE '%-GP' "); } query.append("AND str.specialty_id = ? ORDER BY usr.name ASC "); List<Object> params = new ArrayList<Object>(); params.add(unitcode); if (nhsno != null && nhsno.length() > 0) { params.add('%' + nhsno + '%'); } if (name != null && name.length() > 0) { params.add('%' + name + '%'); } params.add(specialty.getId()); return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper()); } //todo refactor into one query with the one above //todo PERFORMANCE FIX: commented out the emailverification table to improve query speed. @Override public List getAllUnitPatientsWithTreatmentDao(String nhsno, String name, boolean showgps, Specialty specialty) { StringBuilder query = new StringBuilder(); query.append("SELECT DISTINCT "); query.append(" usr.username "); query.append(", usr.password "); query.append(", usr.name "); query.append(", usr.email "); query.append(", usr.emailverified "); query.append(", usr.accountlocked "); query.append(", ptt.nhsno "); query.append(", ptt.unitcode "); query.append(", null lastverificationdate "); query.append(", usr.firstlogon "); query.append(", usr.lastlogon "); query.append(", ptt.treatment "); query.append(", ptt.dateofbirth "); query.append(", ptt.rrtModality "); query.append(", pvl.lastdatadate "); query.append("FROM user usr "); query.append("INNER JOIN usermapping usm ON usm.username = usr.username "); query.append("INNER JOIN patient ptt ON usm.nhsno = ptt.nhsno "); // query.append("LEFT JOIN emailverification em ON usr.username = em.username "); query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id "); query.append("LEFT JOIN pv_user_log pvl ON ptt.nhsno = pvl.nhsno "); query.append("WHERE str.role = 'patient' "); query.append("AND usr.id = str.user_id "); query.append("AND usm.unitcode <> 'PATIENT' "); query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL "); if (nhsno != null && nhsno.length() > 0) { query.append("AND usm.nhsno LIKE ? "); } if (name != null && name.length() > 0) { query.append("AND usr.name LIKE ? "); } if (!showgps) { query.append("AND usr.name NOT LIKE '%-GP' "); } query.append("AND str.specialty_id = ? ORDER BY usr.name ASC "); List<Object> params = new ArrayList<Object>(); if (nhsno != null && nhsno.length() > 0) { params.add('%' + nhsno + '%'); } if (name != null && name.length() > 0) { params.add('%' + name + '%'); } params.add(specialty.getId()); return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper()); } @Override public List<PatientLogonWithTreatment> getUnitPatientsAllWithTreatmentDao(String unitcode, Specialty specialty) { String sql = "SELECT " + " user.username, " + " user.password, " + " user.name, " + " user.email, " + " user.emailverified, " + " user.lastlogon, " + " usermapping.nhsno, " + " usermapping.unitcode, " + " user.firstlogon, " + " user.accountlocked, " + " patient.treatment, " + " patient.dateofbirth " + "FROM " + " user, " + " specialtyuserrole, " + " usermapping " + "LEFT JOIN " + " patient ON usermapping.nhsno = patient.nhsno " + "WHERE " + " usermapping.username = user.username " + "AND " + " user.id = specialtyuserrole.user_id " + "AND " + " usermapping.unitcode = ? " + "AND " + " specialtyuserrole.role = 'patient' " + "AND " + " user.name NOT LIKE '%-GP' " + "AND " + " specialtyuserrole.specialty_id = ? " + "ORDER BY " + " user.name ASC"; List<Object> params = new ArrayList<Object>(); params.add(unitcode); params.add(specialty.getId()); return jdbcTemplate.query(sql, params.toArray(), new PatientLogonWithTreatmentMapper()); } @Override public List<Patient> getUktPatients() { String sql = "SELECT DISTINCT patient.nhsno, patient.surname, patient.forename, " + " patient.dateofbirth, patient.postcode FROM patient, user, usermapping " + " WHERE patient.nhsno REGEXP '^[0-9]{10}$' AND patient.nhsno = usermapping.nhsno " + "AND user.username = usermapping.username " + " AND usermapping.username NOT LIKE '%-GP' AND user.dummypatient = 0"; return jdbcTemplate.query(sql, new PatientMapper()); } private class PatientMapper implements RowMapper<Patient> { @Override public Patient mapRow(ResultSet resultSet, int i) throws SQLException { Patient patient = new Patient(); patient.setNhsno(resultSet.getString("nhsno")); patient.setSurname(resultSet.getString("surname")); patient.setForename(resultSet.getString("forename")); patient.setDateofbirth(resultSet.getString("dateofbirth")); patient.setPostcode(resultSet.getString("postcode")); return patient; } } private class PatientLogonWithTreatmentMapper implements RowMapper<PatientLogonWithTreatment> { @Override public PatientLogonWithTreatment mapRow(ResultSet resultSet, int i) throws SQLException { PatientLogonWithTreatment patientLogonWithTreatment = new PatientLogonWithTreatment(); patientLogonWithTreatment.setUsername(resultSet.getString("username")); patientLogonWithTreatment.setPassword(resultSet.getString("password")); patientLogonWithTreatment.setName(resultSet.getString("name")); patientLogonWithTreatment.setEmail(resultSet.getString("email")); patientLogonWithTreatment.setEmailverified(resultSet.getBoolean("emailverified")); patientLogonWithTreatment.setAccountlocked(resultSet.getBoolean("accountlocked")); patientLogonWithTreatment.setNhsno(resultSet.getString("nhsno")); patientLogonWithTreatment.setFirstlogon(resultSet.getBoolean("firstlogon")); patientLogonWithTreatment.setLastlogon(resultSet.getDate("lastlogon")); patientLogonWithTreatment.setUnitcode(resultSet.getString("unitcode")); patientLogonWithTreatment.setTreatment(resultSet.getString("treatment")); patientLogonWithTreatment.setDateofbirth(resultSet.getString("dateofbirth")); return patientLogonWithTreatment; } } private class PatientLogonWithTreatmentExtendMapper extends PatientLogonWithTreatmentMapper { @Override public PatientLogonWithTreatment mapRow(ResultSet resultSet, int i) throws SQLException { PatientLogonWithTreatment patientLogonWithTreatment = super.mapRow(resultSet, i); patientLogonWithTreatment.setLastverificationdate(resultSet.getDate("lastverificationdate")); patientLogonWithTreatment.setRrtModality(resultSet.getInt("rrtModality")); patientLogonWithTreatment.setLastdatadate(resultSet.getDate("lastdatadate")); return patientLogonWithTreatment; } } }
true
true
public List getUnitPatientsWithTreatmentDao(String unitcode, String nhsno, String name, boolean showgps, Specialty specialty) { StringBuilder query = new StringBuilder(); query.append("SELECT usr.username "); query.append(", usr.password "); query.append(", usr.name "); query.append(", usr.email "); query.append(", usr.emailverified "); query.append(", usr.accountlocked "); query.append(", usm.nhsno "); query.append(", usm.unitcode "); query.append(", null lastverificationdate "); query.append(", usr.firstlogon "); query.append(", usr.lastlogon "); query.append(", ptt.treatment "); query.append(", ptt.dateofbirth "); query.append(", ptt.rrtModality "); query.append(", psl.lastdatadate "); query.append("FROM USER usr "); query.append("INNER JOIN usermapping usm ON usm.username = usr.username "); query.append("INNER JOIN patient ptt ON usm.nhsno = ptt.nhsno "); query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id "); // query.append("LEFT JOIN emailverification emv ON usr.username = emv.username "); query.append("LEFT JOIN pv_user_log psl ON usm.nhsno = psl.nhsno "); query.append("WHERE str.role = 'patient' "); query.append("AND usr.username = usm.username "); query.append("AND usr.id = str.user_id "); query.append("AND usm.unitcode <> 'PATIENT' "); query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL "); query.append("AND usm.unitcode = ? "); if (StringUtils.hasText(nhsno)) { query.append("AND usm.nhsno LIKE ? "); } if (StringUtils.hasText(name)) { query.append("AND usr.name LIKE ? "); } if (!showgps) { query.append("AND usr.name NOT LIKE '%-GP' "); } query.append("AND str.specialty_id = ? ORDER BY usr.name ASC "); List<Object> params = new ArrayList<Object>(); params.add(unitcode); if (nhsno != null && nhsno.length() > 0) { params.add('%' + nhsno + '%'); } if (name != null && name.length() > 0) { params.add('%' + name + '%'); } params.add(specialty.getId()); return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper()); }
public List getUnitPatientsWithTreatmentDao(String unitcode, String nhsno, String name, boolean showgps, Specialty specialty) { StringBuilder query = new StringBuilder(); query.append("SELECT usr.username "); query.append(", usr.password "); query.append(", usr.name "); query.append(", usr.email "); query.append(", usr.emailverified "); query.append(", usr.accountlocked "); query.append(", usm.nhsno "); query.append(", usm.unitcode "); query.append(", null lastverificationdate "); query.append(", usr.firstlogon "); query.append(", usr.lastlogon "); query.append(", ptt.treatment "); query.append(", ptt.dateofbirth "); query.append(", ptt.rrtModality "); query.append(", psl.lastdatadate "); query.append("FROM USER usr "); query.append("INNER JOIN usermapping usm ON usm.username = usr.username "); query.append("LEFT JOIN patient ptt ON usm.nhsno = ptt.nhsno "); query.append("INNER JOIN specialtyuserrole str ON str.user_id = usr.id "); // query.append("LEFT JOIN emailverification emv ON usr.username = emv.username "); query.append("LEFT JOIN pv_user_log psl ON usm.nhsno = psl.nhsno "); query.append("WHERE str.role = 'patient' "); query.append("AND usr.username = usm.username "); query.append("AND usr.id = str.user_id "); query.append("AND usm.unitcode <> 'PATIENT' "); query.append("AND IF(ptt.patientLinkId = 0, NULL, ptt.patientLinkId) IS NULL "); query.append("AND usm.unitcode = ? "); if (StringUtils.hasText(nhsno)) { query.append("AND usm.nhsno LIKE ? "); } if (StringUtils.hasText(name)) { query.append("AND usr.name LIKE ? "); } if (!showgps) { query.append("AND usr.name NOT LIKE '%-GP' "); } query.append("AND str.specialty_id = ? ORDER BY usr.name ASC "); List<Object> params = new ArrayList<Object>(); params.add(unitcode); if (nhsno != null && nhsno.length() > 0) { params.add('%' + nhsno + '%'); } if (name != null && name.length() > 0) { params.add('%' + name + '%'); } params.add(specialty.getId()); return jdbcTemplate.query(query.toString(), params.toArray(), new PatientLogonWithTreatmentExtendMapper()); }
diff --git a/src/radlab/rain/workload/olio/OlioConfiguration.java b/src/radlab/rain/workload/olio/OlioConfiguration.java index 4c1a1cc..9ea65b0 100644 --- a/src/radlab/rain/workload/olio/OlioConfiguration.java +++ b/src/radlab/rain/workload/olio/OlioConfiguration.java @@ -1,189 +1,201 @@ /* * Copyright (c) 2010, Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley * nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Author: Marco Guazzone ([email protected]), 2013 */ package radlab.rain.workload.olio; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; //import java.util.Arrays; import java.util.List; import org.json.JSONObject; import org.json.JSONException; /** * Handle the configuration related to Olio. * * @author <a href="mailto:[email protected]">Marco Guazzone</a> */ public final class OlioConfiguration { // Possible Java incarnation public static final int JAVA_INCARNATION = 0; public static final int PHP_INCARNATION = 1; public static final int RAILS_INCARNATION = 2; // Configuration keys private static final String CFG_INCARNATION_KEY = "olio.incarnation"; private static final String CFG_RNG_SEED_KEY = "olio.rngSeed"; private static final String CFG_NUM_PRELOADED_EVENTS_KEY = "olio.numPreloadedEvents"; private static final String CFG_NUM_PRELOADED_PERSONS_KEY = "olio.numPreloadedPersons"; private static final String CFG_NUM_PRELOADED_TAGS_KEY = "olio.numPreloadedTags"; // Default values private static final int DEFAULT_INCARNATION = RAILS_INCARNATION; private static final long DEFAULT_RNG_SEED = -1; private static final int DEFAULT_NUM_PRELOADED_EVENTS = 0; private static final int DEFAULT_NUM_PRELOADED_PERSONS = 0; private static final int DEFAULT_NUM_PRELOADED_TAGS = 0; // Members to hold configuration values private int _incarnation = DEFAULT_INCARNATION; ///< Olio incarnation private long _rngSeed = DEFAULT_RNG_SEED; ///< The seed used for the Random Number Generator; a value <= 0 means that no special seed is used. private int _numPreloadEvents = DEFAULT_NUM_PRELOADED_EVENTS; ///< Number of events that have been already preloaded in the Olio database private int _numPreloadPersons = DEFAULT_NUM_PRELOADED_PERSONS; ///< Number of persons that have been already preloaded in the Olio database private int _numPreloadTags = DEFAULT_NUM_PRELOADED_TAGS; ///< Number of tags that have been already preloaded in the Olio database public OlioConfiguration() { } public OlioConfiguration(JSONObject config) throws JSONException { configure(config); } public void configure(JSONObject config) throws JSONException { if (config.has(CFG_INCARNATION_KEY)) { String str = config.getString(CFG_INCARNATION_KEY).toLowerCase(); if (str.equals("java")) { this._incarnation = JAVA_INCARNATION; } else if (str.equals("php")) { this._incarnation = PHP_INCARNATION; } else if (str.equals("rails")) { this._incarnation = RAILS_INCARNATION; } else { throw new JSONException("Unknown Olio incarnation"); } } if (config.has(CFG_RNG_SEED_KEY)) { this._rngSeed = config.getLong(CFG_RNG_SEED_KEY); } + if (config.has(CFG_NUM_PRELOADED_EVENTS_KEY)) + { + this._numPreloadEvents = config.getInt(CFG_NUM_PRELOADED_EVENTS_KEY); + } + if (config.has(CFG_NUM_PRELOADED_PERSONS_KEY)) + { + this._numPreloadPersons = config.getInt(CFG_NUM_PRELOADED_PERSONS_KEY); + } + if (config.has(CFG_NUM_PRELOADED_TAGS_KEY)) + { + this._numPreloadTags = config.getInt(CFG_NUM_PRELOADED_TAGS_KEY); + } //TODO: check parameters values if (this._rngSeed <= 0) { this._rngSeed = DEFAULT_RNG_SEED; } } /** * Get the Olio incarnation type. * * @return the Olio incarnation type. */ public int getIncarnation() { return this._incarnation; } /** * Get the seed for the random number generator used by the Olio generator. * * @return the seed for the random number generator */ public long getRngSeed() { return this._rngSeed; } /** * Get the number of events that have been already preloaded inside the * Olio database. * * @return the number of preloaded events. */ public int getNumOfPreloadedEvents() { return this._numPreloadEvents; } /** * Get the number of persons that have been already preloaded inside the * Olio database. * * @return the number of preloaded persons. */ public int getNumOfPreloadedPersons() { return this._numPreloadPersons; } /** * Get the number of tags that have been already preloaded inside the * Olio database. * * @return the tags of preloaded persons. */ public int getNumOfPreloadedTags() { return this._numPreloadTags; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append( " Incarnation: " + this.getIncarnation()); sb.append(", Random Number Generator Seed: " + this.getRngSeed()); sb.append(", Number of Preloaded Events: " + this.getNumOfPreloadedEvents()); sb.append(", Number of Preloaded Persons: " + this.getNumOfPreloadedPersons()); sb.append(", Number of Preloaded Tags: " + this.getNumOfPreloadedTags()); return sb.toString(); } }
true
true
public void configure(JSONObject config) throws JSONException { if (config.has(CFG_INCARNATION_KEY)) { String str = config.getString(CFG_INCARNATION_KEY).toLowerCase(); if (str.equals("java")) { this._incarnation = JAVA_INCARNATION; } else if (str.equals("php")) { this._incarnation = PHP_INCARNATION; } else if (str.equals("rails")) { this._incarnation = RAILS_INCARNATION; } else { throw new JSONException("Unknown Olio incarnation"); } } if (config.has(CFG_RNG_SEED_KEY)) { this._rngSeed = config.getLong(CFG_RNG_SEED_KEY); } //TODO: check parameters values if (this._rngSeed <= 0) { this._rngSeed = DEFAULT_RNG_SEED; } }
public void configure(JSONObject config) throws JSONException { if (config.has(CFG_INCARNATION_KEY)) { String str = config.getString(CFG_INCARNATION_KEY).toLowerCase(); if (str.equals("java")) { this._incarnation = JAVA_INCARNATION; } else if (str.equals("php")) { this._incarnation = PHP_INCARNATION; } else if (str.equals("rails")) { this._incarnation = RAILS_INCARNATION; } else { throw new JSONException("Unknown Olio incarnation"); } } if (config.has(CFG_RNG_SEED_KEY)) { this._rngSeed = config.getLong(CFG_RNG_SEED_KEY); } if (config.has(CFG_NUM_PRELOADED_EVENTS_KEY)) { this._numPreloadEvents = config.getInt(CFG_NUM_PRELOADED_EVENTS_KEY); } if (config.has(CFG_NUM_PRELOADED_PERSONS_KEY)) { this._numPreloadPersons = config.getInt(CFG_NUM_PRELOADED_PERSONS_KEY); } if (config.has(CFG_NUM_PRELOADED_TAGS_KEY)) { this._numPreloadTags = config.getInt(CFG_NUM_PRELOADED_TAGS_KEY); } //TODO: check parameters values if (this._rngSeed <= 0) { this._rngSeed = DEFAULT_RNG_SEED; } }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java index 3dd771f73..ff4fecc57 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java +++ b/java/modules/core/src/main/java/org/apache/synapse/core/axis2/Axis2FlexibleMEPClient.java @@ -1,326 +1,332 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.core.axis2; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.soap.SOAPFactory; import org.apache.axis2.AxisFault; import org.apache.axis2.Constants; import org.apache.axis2.addressing.AddressingConstants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.OperationClient; import org.apache.axis2.client.Options; import org.apache.axis2.context.ConfigurationContext; import org.apache.axis2.context.MessageContext; import org.apache.axis2.context.ServiceContext; import org.apache.axis2.context.ServiceGroupContext; import org.apache.axis2.description.AxisOperation; import org.apache.axis2.description.AxisService; import org.apache.axis2.description.AxisServiceGroup; import org.apache.axis2.description.WSDL2Constants; import org.apache.axis2.engine.AxisConfiguration; import org.apache.axis2.wsdl.WSDLConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.synapse.SynapseConstants; import org.apache.synapse.endpoints.EndpointDefinition; import org.apache.synapse.util.MessageHelper; import javax.xml.namespace.QName; /** * This is a simple client that handles both in only and in out */ public class Axis2FlexibleMEPClient { private static final Log log = LogFactory.getLog(Axis2FlexibleMEPClient.class); /** * Based on the Axis2 client code. Sends the Axis2 Message context out and returns * the Axis2 message context for the response. * * Here Synapse works as a Client to the service. It would expect 200 ok, 202 ok and * 500 internal server error as possible responses. * * @param endpoint the endpoint being sent to, maybe null * @param synapseOutMessageContext the outgoing synapse message * @throws AxisFault on errors */ public static void send( EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext) throws AxisFault { boolean separateListener = false; boolean wsSecurityEnabled = false; String wsSecPolicyKey = null; String inboundWsSecPolicyKey = null; String outboundWsSecPolicyKey = null; boolean wsRMEnabled = false; String wsRMPolicyKey = null; boolean wsAddressingEnabled = false; String wsAddressingVersion = null; if (endpoint != null) { separateListener = endpoint.isUseSeparateListener(); wsSecurityEnabled = endpoint.isSecurityOn(); wsSecPolicyKey = endpoint.getWsSecPolicyKey(); inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey(); outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey(); wsRMEnabled = endpoint.isReliableMessagingOn(); wsRMPolicyKey = endpoint.getWsRMPolicyKey(); wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled; wsAddressingVersion = endpoint.getAddressingVersion(); } if (log.isDebugEnabled()) { log.debug( "Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled + "] [rm = " + wsRMEnabled + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa() + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11() + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX() + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding() : "") + "] [to " + synapseOutMessageContext.getTo() + "]"); } // save the original message context wihout altering it, so we can tie the response MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext(); // create a new MessageContext to be sent out as this should not corrupt the original // we need to create the response to the original message later on MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx); if (log.isDebugEnabled()) { log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]" + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]"); } // set all the details of the endpoint only to the cloned message context // so that we can use the original message context for resending through different endpoints if (endpoint != null) { if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); + // We need to set this ezplicitly here in case the requset was not a POST + axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, + Constants.Configuration.HTTP_METHOD_POST); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(!axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx); } } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); - axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); + axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); + // We need to set this ezplicitly here in case the requset was not a POST + axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, + Constants.Configuration.HTTP_METHOD_POST); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx); } } if (endpoint.isUseMTOM()) { axisOutMsgCtx.setDoingMTOM(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingMTOM(true); } else if (endpoint.isUseSwa()) { axisOutMsgCtx.setDoingSwA(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingSwA(true); } if (endpoint.getCharSetEncoding() != null) { axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding()); } if (endpoint.getAddress() != null) { axisOutMsgCtx.setTo(new EndpointReference(endpoint.getAddress())); } if (endpoint.isUseSeparateListener()) { axisOutMsgCtx.getOptions().setUseSeparateListener(true); } } if (wsAddressingEnabled) { if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE); } else if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE); } axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE); } else { axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE); } ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext(); AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration(); AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled, wsSecurityEnabled); // mark the anon services created to be used in the client side of synapse as hidden // from the server side of synapse point of view anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true"); ServiceGroupContext sgc = new ServiceGroupContext( axisCfgCtx, (AxisServiceGroup) anoymousService.getParent()); ServiceContext serviceCtx = sgc.getServiceContext(anoymousService); boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty( SynapseConstants.OUT_ONLY)) || WSDL2Constants.MEP_URI_IN_ONLY.equals( originalInMsgCtx.getOperationContext() .getAxisOperation().getMessageExchangePattern()); // get a reference to the DYNAMIC operation of the Anonymous Axis2 service AxisOperation axisAnonymousOperation = anoymousService.getOperation( outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION) : new QName(AnonymousServiceFactory.OUT_IN_OPERATION)); Options clientOptions = new Options(); clientOptions.setUseSeparateListener(separateListener); // if RM is requested, if (wsRMEnabled) { // if a WS-RM policy is specified, use it if (wsRMPolicyKey != null) { clientOptions.setProperty( SynapseConstants.SANDESHA_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsRMPolicyKey)); } MessageHelper.copyRMOptions(originalInMsgCtx, clientOptions); } // if security is enabled, if (wsSecurityEnabled) { // if a WS-Sec policy is specified, use it if (wsSecPolicyKey != null) { clientOptions.setProperty( SynapseConstants.RAMPART_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey)); } else { if (inboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, inboundWsSecPolicyKey)); } if (outboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, outboundWsSecPolicyKey)); } } // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197 if (axisOutMsgCtx.getEnvelope().getHeader() == null) { SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory(); fac.createSOAPHeader(axisOutMsgCtx.getEnvelope()); } } OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions); mepClient.addMessageContext(axisOutMsgCtx); axisOutMsgCtx.setAxisMessage( axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)); // set the SEND_TIMEOUT for transport sender if (endpoint != null && endpoint.getTimeoutDuration() > 0) { axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration()); } if (!outOnlyMessage) { // always set a callback as we decide if the send it blocking or non blocking within // the MEP client. This does not cause an overhead, as we simply create a 'holder' // object with a reference to the outgoing synapse message context // synapseOutMessageContext AsyncCallback callback = new AsyncCallback(synapseOutMessageContext); if (endpoint != null) { // set the timeout time and the timeout action to the callback, so that the // TimeoutHandler can detect timed out callbacks and take approprite action. callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration()); callback.setTimeOutAction(endpoint.getTimeoutAction()); } else { callback.setTimeOutOn(System.currentTimeMillis()); } mepClient.setCallback(callback); } // with the nio transport, this causes the listener not to write a 202 // Accepted response, as this implies that Synapse does not yet know if // a 202 or 200 response would be written back. originalInMsgCtx.getOperationContext().setProperty( org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP"); mepClient.execute(true); } private static MessageContext cloneForSend(MessageContext ori) throws AxisFault { MessageContext newMC = MessageHelper.clonePartially(ori); newMC.setEnvelope(ori.getEnvelope()); MessageHelper.removeAddressingHeaders(newMC); newMC.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, ori.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS)); return newMC; } }
false
true
public static void send( EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext) throws AxisFault { boolean separateListener = false; boolean wsSecurityEnabled = false; String wsSecPolicyKey = null; String inboundWsSecPolicyKey = null; String outboundWsSecPolicyKey = null; boolean wsRMEnabled = false; String wsRMPolicyKey = null; boolean wsAddressingEnabled = false; String wsAddressingVersion = null; if (endpoint != null) { separateListener = endpoint.isUseSeparateListener(); wsSecurityEnabled = endpoint.isSecurityOn(); wsSecPolicyKey = endpoint.getWsSecPolicyKey(); inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey(); outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey(); wsRMEnabled = endpoint.isReliableMessagingOn(); wsRMPolicyKey = endpoint.getWsRMPolicyKey(); wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled; wsAddressingVersion = endpoint.getAddressingVersion(); } if (log.isDebugEnabled()) { log.debug( "Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled + "] [rm = " + wsRMEnabled + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa() + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11() + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX() + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding() : "") + "] [to " + synapseOutMessageContext.getTo() + "]"); } // save the original message context wihout altering it, so we can tie the response MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext(); // create a new MessageContext to be sent out as this should not corrupt the original // we need to create the response to the original message later on MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx); if (log.isDebugEnabled()) { log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]" + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]"); } // set all the details of the endpoint only to the cloned message context // so that we can use the original message context for resending through different endpoints if (endpoint != null) { if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(!axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx); } } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx); } } if (endpoint.isUseMTOM()) { axisOutMsgCtx.setDoingMTOM(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingMTOM(true); } else if (endpoint.isUseSwa()) { axisOutMsgCtx.setDoingSwA(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingSwA(true); } if (endpoint.getCharSetEncoding() != null) { axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding()); } if (endpoint.getAddress() != null) { axisOutMsgCtx.setTo(new EndpointReference(endpoint.getAddress())); } if (endpoint.isUseSeparateListener()) { axisOutMsgCtx.getOptions().setUseSeparateListener(true); } } if (wsAddressingEnabled) { if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE); } else if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE); } axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE); } else { axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE); } ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext(); AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration(); AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled, wsSecurityEnabled); // mark the anon services created to be used in the client side of synapse as hidden // from the server side of synapse point of view anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true"); ServiceGroupContext sgc = new ServiceGroupContext( axisCfgCtx, (AxisServiceGroup) anoymousService.getParent()); ServiceContext serviceCtx = sgc.getServiceContext(anoymousService); boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty( SynapseConstants.OUT_ONLY)) || WSDL2Constants.MEP_URI_IN_ONLY.equals( originalInMsgCtx.getOperationContext() .getAxisOperation().getMessageExchangePattern()); // get a reference to the DYNAMIC operation of the Anonymous Axis2 service AxisOperation axisAnonymousOperation = anoymousService.getOperation( outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION) : new QName(AnonymousServiceFactory.OUT_IN_OPERATION)); Options clientOptions = new Options(); clientOptions.setUseSeparateListener(separateListener); // if RM is requested, if (wsRMEnabled) { // if a WS-RM policy is specified, use it if (wsRMPolicyKey != null) { clientOptions.setProperty( SynapseConstants.SANDESHA_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsRMPolicyKey)); } MessageHelper.copyRMOptions(originalInMsgCtx, clientOptions); } // if security is enabled, if (wsSecurityEnabled) { // if a WS-Sec policy is specified, use it if (wsSecPolicyKey != null) { clientOptions.setProperty( SynapseConstants.RAMPART_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey)); } else { if (inboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, inboundWsSecPolicyKey)); } if (outboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, outboundWsSecPolicyKey)); } } // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197 if (axisOutMsgCtx.getEnvelope().getHeader() == null) { SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory(); fac.createSOAPHeader(axisOutMsgCtx.getEnvelope()); } } OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions); mepClient.addMessageContext(axisOutMsgCtx); axisOutMsgCtx.setAxisMessage( axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)); // set the SEND_TIMEOUT for transport sender if (endpoint != null && endpoint.getTimeoutDuration() > 0) { axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration()); } if (!outOnlyMessage) { // always set a callback as we decide if the send it blocking or non blocking within // the MEP client. This does not cause an overhead, as we simply create a 'holder' // object with a reference to the outgoing synapse message context // synapseOutMessageContext AsyncCallback callback = new AsyncCallback(synapseOutMessageContext); if (endpoint != null) { // set the timeout time and the timeout action to the callback, so that the // TimeoutHandler can detect timed out callbacks and take approprite action. callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration()); callback.setTimeOutAction(endpoint.getTimeoutAction()); } else { callback.setTimeOutOn(System.currentTimeMillis()); } mepClient.setCallback(callback); } // with the nio transport, this causes the listener not to write a 202 // Accepted response, as this implies that Synapse does not yet know if // a 202 or 200 response would be written back. originalInMsgCtx.getOperationContext().setProperty( org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP"); mepClient.execute(true); }
public static void send( EndpointDefinition endpoint, org.apache.synapse.MessageContext synapseOutMessageContext) throws AxisFault { boolean separateListener = false; boolean wsSecurityEnabled = false; String wsSecPolicyKey = null; String inboundWsSecPolicyKey = null; String outboundWsSecPolicyKey = null; boolean wsRMEnabled = false; String wsRMPolicyKey = null; boolean wsAddressingEnabled = false; String wsAddressingVersion = null; if (endpoint != null) { separateListener = endpoint.isUseSeparateListener(); wsSecurityEnabled = endpoint.isSecurityOn(); wsSecPolicyKey = endpoint.getWsSecPolicyKey(); inboundWsSecPolicyKey = endpoint.getInboundWsSecPolicyKey(); outboundWsSecPolicyKey = endpoint.getOutboundWsSecPolicyKey(); wsRMEnabled = endpoint.isReliableMessagingOn(); wsRMPolicyKey = endpoint.getWsRMPolicyKey(); wsAddressingEnabled = endpoint.isAddressingOn() || wsRMEnabled; wsAddressingVersion = endpoint.getAddressingVersion(); } if (log.isDebugEnabled()) { log.debug( "Sending [add = " + wsAddressingEnabled + "] [sec = " + wsSecurityEnabled + "] [rm = " + wsRMEnabled + (endpoint != null ? "] [mtom = " + endpoint.isUseMTOM() + "] [swa = " + endpoint.isUseSwa() + "] [format = " + endpoint.getFormat() + "] [force soap11=" + endpoint.isForceSOAP11() + "] [force soap12=" + endpoint.isForceSOAP12() + "] [pox=" + endpoint.isForcePOX() + "] [get=" + endpoint.isForceGET() + "] [encoding=" + endpoint.getCharSetEncoding() : "") + "] [to " + synapseOutMessageContext.getTo() + "]"); } // save the original message context wihout altering it, so we can tie the response MessageContext originalInMsgCtx = ((Axis2MessageContext) synapseOutMessageContext).getAxis2MessageContext(); // create a new MessageContext to be sent out as this should not corrupt the original // we need to create the response to the original message later on MessageContext axisOutMsgCtx = cloneForSend(originalInMsgCtx); if (log.isDebugEnabled()) { log.debug("Message [Original Request Message ID : " + synapseOutMessageContext.getMessageID() + "]" + " [New Cloned Request Message ID : " + axisOutMsgCtx.getMessageID() + "]"); } // set all the details of the endpoint only to the cloned message context // so that we can use the original message context for resending through different endpoints if (endpoint != null) { if (SynapseConstants.FORMAT_POX.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_GET.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(true); axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_GET); axisOutMsgCtx.setProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE, org.apache.axis2.transport.http.HTTPConstants.MEDIA_TYPE_APPLICATION_XML); } else if (SynapseConstants.FORMAT_SOAP11.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); // We need to set this ezplicitly here in case the requset was not a POST axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(!axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP12toSOAP11(axisOutMsgCtx); } } else if (SynapseConstants.FORMAT_SOAP12.equals(endpoint.getFormat())) { axisOutMsgCtx.setDoingREST(false); axisOutMsgCtx.removeProperty(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE); // We need to set this ezplicitly here in case the requset was not a POST axisOutMsgCtx.setProperty(Constants.Configuration.HTTP_METHOD, Constants.Configuration.HTTP_METHOD_POST); if (axisOutMsgCtx.getSoapAction() == null && axisOutMsgCtx.getWSAAction() != null) { axisOutMsgCtx.setSoapAction(axisOutMsgCtx.getWSAAction()); } if(axisOutMsgCtx.isSOAP11()) { SOAPUtils.convertSOAP11toSOAP12(axisOutMsgCtx); } } if (endpoint.isUseMTOM()) { axisOutMsgCtx.setDoingMTOM(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_MTOM, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingMTOM(true); } else if (endpoint.isUseSwa()) { axisOutMsgCtx.setDoingSwA(true); // fix / workaround for AXIS2-1798 axisOutMsgCtx.setProperty( org.apache.axis2.Constants.Configuration.ENABLE_SWA, org.apache.axis2.Constants.VALUE_TRUE); axisOutMsgCtx.setDoingSwA(true); } if (endpoint.getCharSetEncoding() != null) { axisOutMsgCtx.setProperty(Constants.Configuration.CHARACTER_SET_ENCODING, endpoint.getCharSetEncoding()); } if (endpoint.getAddress() != null) { axisOutMsgCtx.setTo(new EndpointReference(endpoint.getAddress())); } if (endpoint.isUseSeparateListener()) { axisOutMsgCtx.getOptions().setUseSeparateListener(true); } } if (wsAddressingEnabled) { if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_SUBMISSION.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Submission.WSA_NAMESPACE); } else if (wsAddressingVersion != null && SynapseConstants.ADDRESSING_VERSION_FINAL.equals(wsAddressingVersion)) { axisOutMsgCtx.setProperty(AddressingConstants.WS_ADDRESSING_VERSION, AddressingConstants.Final.WSA_NAMESPACE); } axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.FALSE); } else { axisOutMsgCtx.setProperty (AddressingConstants.DISABLE_ADDRESSING_FOR_OUT_MESSAGES, Boolean.TRUE); } ConfigurationContext axisCfgCtx = axisOutMsgCtx.getConfigurationContext(); AxisConfiguration axisCfg = axisCfgCtx.getAxisConfiguration(); AxisService anoymousService = AnonymousServiceFactory.getAnonymousService(synapseOutMessageContext.getConfiguration(), axisCfg, wsAddressingEnabled, wsRMEnabled, wsSecurityEnabled); // mark the anon services created to be used in the client side of synapse as hidden // from the server side of synapse point of view anoymousService.getParent().addParameter(SynapseConstants.HIDDEN_SERVICE_PARAM, "true"); ServiceGroupContext sgc = new ServiceGroupContext( axisCfgCtx, (AxisServiceGroup) anoymousService.getParent()); ServiceContext serviceCtx = sgc.getServiceContext(anoymousService); boolean outOnlyMessage = "true".equals(synapseOutMessageContext.getProperty( SynapseConstants.OUT_ONLY)) || WSDL2Constants.MEP_URI_IN_ONLY.equals( originalInMsgCtx.getOperationContext() .getAxisOperation().getMessageExchangePattern()); // get a reference to the DYNAMIC operation of the Anonymous Axis2 service AxisOperation axisAnonymousOperation = anoymousService.getOperation( outOnlyMessage ? new QName(AnonymousServiceFactory.OUT_ONLY_OPERATION) : new QName(AnonymousServiceFactory.OUT_IN_OPERATION)); Options clientOptions = new Options(); clientOptions.setUseSeparateListener(separateListener); // if RM is requested, if (wsRMEnabled) { // if a WS-RM policy is specified, use it if (wsRMPolicyKey != null) { clientOptions.setProperty( SynapseConstants.SANDESHA_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsRMPolicyKey)); } MessageHelper.copyRMOptions(originalInMsgCtx, clientOptions); } // if security is enabled, if (wsSecurityEnabled) { // if a WS-Sec policy is specified, use it if (wsSecPolicyKey != null) { clientOptions.setProperty( SynapseConstants.RAMPART_POLICY, MessageHelper.getPolicy(synapseOutMessageContext, wsSecPolicyKey)); } else { if (inboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_IN_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, inboundWsSecPolicyKey)); } if (outboundWsSecPolicyKey != null) { clientOptions.setProperty(SynapseConstants.RAMPART_OUT_POLICY, MessageHelper.getPolicy( synapseOutMessageContext, outboundWsSecPolicyKey)); } } // temporary workaround for https://issues.apache.org/jira/browse/WSCOMMONS-197 if (axisOutMsgCtx.getEnvelope().getHeader() == null) { SOAPFactory fac = axisOutMsgCtx.isSOAP11() ? OMAbstractFactory.getSOAP11Factory() : OMAbstractFactory.getSOAP12Factory(); fac.createSOAPHeader(axisOutMsgCtx.getEnvelope()); } } OperationClient mepClient = axisAnonymousOperation.createClient(serviceCtx, clientOptions); mepClient.addMessageContext(axisOutMsgCtx); axisOutMsgCtx.setAxisMessage( axisAnonymousOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE)); // set the SEND_TIMEOUT for transport sender if (endpoint != null && endpoint.getTimeoutDuration() > 0) { axisOutMsgCtx.setProperty(SynapseConstants.SEND_TIMEOUT, endpoint.getTimeoutDuration()); } if (!outOnlyMessage) { // always set a callback as we decide if the send it blocking or non blocking within // the MEP client. This does not cause an overhead, as we simply create a 'holder' // object with a reference to the outgoing synapse message context // synapseOutMessageContext AsyncCallback callback = new AsyncCallback(synapseOutMessageContext); if (endpoint != null) { // set the timeout time and the timeout action to the callback, so that the // TimeoutHandler can detect timed out callbacks and take approprite action. callback.setTimeOutOn(System.currentTimeMillis() + endpoint.getTimeoutDuration()); callback.setTimeOutAction(endpoint.getTimeoutAction()); } else { callback.setTimeOutOn(System.currentTimeMillis()); } mepClient.setCallback(callback); } // with the nio transport, this causes the listener not to write a 202 // Accepted response, as this implies that Synapse does not yet know if // a 202 or 200 response would be written back. originalInMsgCtx.getOperationContext().setProperty( org.apache.axis2.Constants.RESPONSE_WRITTEN, "SKIP"); mepClient.execute(true); }
diff --git a/com/fluendo/player/VideoConsumer.java b/com/fluendo/player/VideoConsumer.java index ae7d0e7..1ec45ba 100644 --- a/com/fluendo/player/VideoConsumer.java +++ b/com/fluendo/player/VideoConsumer.java @@ -1,163 +1,169 @@ package com.fluendo.player; import java.applet.*; import java.io.*; import java.awt.*; import java.awt.image.*; import java.net.*; import java.util.*; import com.jcraft.jogg.*; import com.fluendo.codecs.*; import com.fluendo.jtheora.*; import com.fluendo.utils.*; public class VideoConsumer implements DataConsumer, Runnable { private ImageTarget target; private Component component; private Toolkit toolkit; private MediaTracker mt; private int queueid; private int framenr; private Clock clock; private boolean ready; private static final int MAX_BUFFER = 1; private double framerate; private double frameperiod; private double aspect = 1.; private boolean stopping = false; private double avgratio; private SmokeCodec smoke; private String currentType; private Info ti; private Comment tc; private State ts; private Packet op = new Packet(); private int packet = 0; private YUVBuffer yuv; public VideoConsumer(Clock newClock, ImageTarget target, double framerate) { this.target = target; component = target.getComponent(); toolkit = component.getToolkit(); mt = new MediaTracker(component); //queueid = QueueManager.registerQueue((int)framerate); queueid = QueueManager.registerQueue(MAX_BUFFER); clock = newClock; frameperiod = 1000.0 / framerate; smoke = new SmokeCodec(component, mt); ti = new Info(); tc = new Comment(); ts = new State(); yuv = new YUVBuffer(); } public void setFramerate (double framerate) { this.framerate = framerate; frameperiod = 1000.0 / framerate; } public void setType(String type) { currentType = type;; } public boolean isReady() { return ready; } public void consume(byte[] data, int offset, int length) { Image newImage = null; try { if (currentType.equals("image/x-smoke")) { newImage = smoke.decode (data, offset, length); setFramerate(smoke.fps_num/(double)smoke.fps_denom); aspect = 1.0; } else if (currentType.equals("image/jpeg")) { newImage = toolkit.createImage(data, offset, length); mt.addImage(newImage, 0); mt.waitForID(0); mt.removeImage(newImage, 0); } else if (currentType.equals("video/x-theora")) { //System.out.println ("creating packet"); op.packet_base = data; op.packet = offset; op.bytes = length; op.b_o_s = (packet == 0 ? 1 : 0); op.e_o_s = 0; op.packetno = packet; if (packet < 3) { //System.out.println ("decoding header"); if(ti.decodeHeader(tc, op) < 0){ // error case; not a theora header System.err.println("does not contain Theora video data."); return; } if (packet == 2) { ts.decodeInit(ti); System.out.println("theora dimension: "+ti.width+"x"+ti.height); - System.out.println("theora aspect: "+ti.aspect_numerator+"x"+ti.aspect_denominator); - System.out.println("theora framerate: "+ti.fps_numerator+"x"+ti.fps_denominator); + if (ti.aspect_denominator == 0) { + ti.aspect_numerator = 1; + ti.aspect_denominator = 1; + } + System.out.println("theora offset: "+ti.offset_x+","+ti.offset_y); + System.out.println("theora frame: "+ti.frame_width+","+ti.frame_height); + System.out.println("theora aspect: "+ti.aspect_numerator+"/"+ti.aspect_denominator); + System.out.println("theora framerate: "+ti.fps_numerator+"/"+ti.fps_denominator); setFramerate(ti.fps_numerator/(double)ti.fps_denominator); aspect = ti.aspect_numerator/(double)ti.aspect_denominator; } } else { if (ts.decodePacketin(op) != 0) { System.err.println("Error Decoding Theora."); return; } if (ts.decodeYUVout(yuv) != 0) { System.err.println("Error getting the picture."); return; } - newImage = yuv.getAsImage(toolkit); + newImage = yuv.getAsImage(toolkit, ti.offset_x, ti.offset_y, ti.frame_width, ti.frame_height); } packet++; } if (newImage != null) QueueManager.enqueue(queueid, newImage); } catch (Exception e) { e.printStackTrace();} } public void stop() { stopping = true; } public void run() { System.out.println("entering video thread"); while (!stopping) { //System.out.println("dequeue image"); Image image = (Image) QueueManager.dequeue(queueid); //System.out.println("dequeued image"); try { if (framenr == 0) { // first frame, wait for signal synchronized (clock) { ready = true; System.out.println("video preroll wait"); clock.wait(); System.out.println("video preroll go!"); } } else { clock.waitForMediaTime((long) (framenr * frameperiod)); } } catch (Exception e) { e.printStackTrace(); } target.setImage(image, framerate, aspect); framenr++; } } }
false
true
public void consume(byte[] data, int offset, int length) { Image newImage = null; try { if (currentType.equals("image/x-smoke")) { newImage = smoke.decode (data, offset, length); setFramerate(smoke.fps_num/(double)smoke.fps_denom); aspect = 1.0; } else if (currentType.equals("image/jpeg")) { newImage = toolkit.createImage(data, offset, length); mt.addImage(newImage, 0); mt.waitForID(0); mt.removeImage(newImage, 0); } else if (currentType.equals("video/x-theora")) { //System.out.println ("creating packet"); op.packet_base = data; op.packet = offset; op.bytes = length; op.b_o_s = (packet == 0 ? 1 : 0); op.e_o_s = 0; op.packetno = packet; if (packet < 3) { //System.out.println ("decoding header"); if(ti.decodeHeader(tc, op) < 0){ // error case; not a theora header System.err.println("does not contain Theora video data."); return; } if (packet == 2) { ts.decodeInit(ti); System.out.println("theora dimension: "+ti.width+"x"+ti.height); System.out.println("theora aspect: "+ti.aspect_numerator+"x"+ti.aspect_denominator); System.out.println("theora framerate: "+ti.fps_numerator+"x"+ti.fps_denominator); setFramerate(ti.fps_numerator/(double)ti.fps_denominator); aspect = ti.aspect_numerator/(double)ti.aspect_denominator; } } else { if (ts.decodePacketin(op) != 0) { System.err.println("Error Decoding Theora."); return; } if (ts.decodeYUVout(yuv) != 0) { System.err.println("Error getting the picture."); return; } newImage = yuv.getAsImage(toolkit); } packet++; } if (newImage != null) QueueManager.enqueue(queueid, newImage); } catch (Exception e) { e.printStackTrace();} }
public void consume(byte[] data, int offset, int length) { Image newImage = null; try { if (currentType.equals("image/x-smoke")) { newImage = smoke.decode (data, offset, length); setFramerate(smoke.fps_num/(double)smoke.fps_denom); aspect = 1.0; } else if (currentType.equals("image/jpeg")) { newImage = toolkit.createImage(data, offset, length); mt.addImage(newImage, 0); mt.waitForID(0); mt.removeImage(newImage, 0); } else if (currentType.equals("video/x-theora")) { //System.out.println ("creating packet"); op.packet_base = data; op.packet = offset; op.bytes = length; op.b_o_s = (packet == 0 ? 1 : 0); op.e_o_s = 0; op.packetno = packet; if (packet < 3) { //System.out.println ("decoding header"); if(ti.decodeHeader(tc, op) < 0){ // error case; not a theora header System.err.println("does not contain Theora video data."); return; } if (packet == 2) { ts.decodeInit(ti); System.out.println("theora dimension: "+ti.width+"x"+ti.height); if (ti.aspect_denominator == 0) { ti.aspect_numerator = 1; ti.aspect_denominator = 1; } System.out.println("theora offset: "+ti.offset_x+","+ti.offset_y); System.out.println("theora frame: "+ti.frame_width+","+ti.frame_height); System.out.println("theora aspect: "+ti.aspect_numerator+"/"+ti.aspect_denominator); System.out.println("theora framerate: "+ti.fps_numerator+"/"+ti.fps_denominator); setFramerate(ti.fps_numerator/(double)ti.fps_denominator); aspect = ti.aspect_numerator/(double)ti.aspect_denominator; } } else { if (ts.decodePacketin(op) != 0) { System.err.println("Error Decoding Theora."); return; } if (ts.decodeYUVout(yuv) != 0) { System.err.println("Error getting the picture."); return; } newImage = yuv.getAsImage(toolkit, ti.offset_x, ti.offset_y, ti.frame_width, ti.frame_height); } packet++; } if (newImage != null) QueueManager.enqueue(queueid, newImage); } catch (Exception e) { e.printStackTrace();} }
diff --git a/core/src/main/java/xdi2/core/impl/file/FileGraphFactory.java b/core/src/main/java/xdi2/core/impl/file/FileGraphFactory.java index 9c9ce0fcc..22f33262e 100644 --- a/core/src/main/java/xdi2/core/impl/file/FileGraphFactory.java +++ b/core/src/main/java/xdi2/core/impl/file/FileGraphFactory.java @@ -1,88 +1,88 @@ package xdi2.core.impl.file; import java.io.IOException; import xdi2.core.Graph; import xdi2.core.GraphFactory; import xdi2.core.impl.AbstractGraphFactory; import xdi2.core.impl.memory.MemoryGraph; import xdi2.core.impl.memory.MemoryGraphFactory; import xdi2.core.io.MimeType; import xdi2.core.io.XDIReader; import xdi2.core.io.XDIReaderRegistry; import xdi2.core.io.XDIWriter; import xdi2.core.io.XDIWriterRegistry; /** * GraphFactory that creates file-based graphs. * * @author markus */ public class FileGraphFactory extends AbstractGraphFactory implements GraphFactory { public static final String DEFAULT_PATH = "xdi2-graph.properties"; public static final String DEFAULT_MIMETYPE = null; private String path; private String mimeType; private MemoryGraphFactory memoryGraphFactory; public FileGraphFactory() { super(); this.path = DEFAULT_PATH; this.mimeType = DEFAULT_MIMETYPE; this.memoryGraphFactory = MemoryGraphFactory.getInstance(); } @Override public Graph openGraph(String identifier) throws IOException { // check identifier if (identifier != null) { this.setPath("xdi2-graph." + identifier + ".xdi"); } // initialize graph XDIReader xdiReader = XDIReaderRegistry.forMimeType(this.mimeType == null ? null : new MimeType(this.mimeType)); XDIWriter xdiWriter = XDIWriterRegistry.forMimeType(this.mimeType == null ? null : new MimeType(this.mimeType)); - MemoryGraph memoryGraph = (MemoryGraph) this.memoryGraphFactory.openGraph(); + MemoryGraph memoryGraph = this.memoryGraphFactory.openGraph(); return new FileGraph(this.path, xdiReader, xdiWriter, memoryGraph); } public String getPath() { return this.path; } public void setPath(String path) { this.path = path; } public String getMimeType() { return this.mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public MemoryGraphFactory getMemoryGraphFactory() { return this.memoryGraphFactory; } public void setMemoryGraphFactory(MemoryGraphFactory memoryGraphFactory) { this.memoryGraphFactory = memoryGraphFactory; } }
true
true
public Graph openGraph(String identifier) throws IOException { // check identifier if (identifier != null) { this.setPath("xdi2-graph." + identifier + ".xdi"); } // initialize graph XDIReader xdiReader = XDIReaderRegistry.forMimeType(this.mimeType == null ? null : new MimeType(this.mimeType)); XDIWriter xdiWriter = XDIWriterRegistry.forMimeType(this.mimeType == null ? null : new MimeType(this.mimeType)); MemoryGraph memoryGraph = (MemoryGraph) this.memoryGraphFactory.openGraph(); return new FileGraph(this.path, xdiReader, xdiWriter, memoryGraph); }
public Graph openGraph(String identifier) throws IOException { // check identifier if (identifier != null) { this.setPath("xdi2-graph." + identifier + ".xdi"); } // initialize graph XDIReader xdiReader = XDIReaderRegistry.forMimeType(this.mimeType == null ? null : new MimeType(this.mimeType)); XDIWriter xdiWriter = XDIWriterRegistry.forMimeType(this.mimeType == null ? null : new MimeType(this.mimeType)); MemoryGraph memoryGraph = this.memoryGraphFactory.openGraph(); return new FileGraph(this.path, xdiReader, xdiWriter, memoryGraph); }
diff --git a/src/strictmode-app/src/com/robomorphine/strictmode/violation/ViolationParser.java b/src/strictmode-app/src/com/robomorphine/strictmode/violation/ViolationParser.java index 6f87ba5..695e3ae 100644 --- a/src/strictmode-app/src/com/robomorphine/strictmode/violation/ViolationParser.java +++ b/src/strictmode-app/src/com/robomorphine/strictmode/violation/ViolationParser.java @@ -1,298 +1,301 @@ package com.robomorphine.strictmode.violation; import com.google.common.annotations.VisibleForTesting; import com.robomorphine.strictmode.violation.Violation.ViolationFactory; import android.text.TextUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class ViolationParser { //NOPMD private static final String STACK_TRACE_ENTRY_PREFIX = "at"; private static final String STACK_TRACE_COMMENT_PREFIX = "#"; private static final String STACK_TRACE_NATIVE_METHOD = "Native Method"; private static final String STACK_TRACE_UNKNOWN_SOURCE = "Unknown Source"; private static final List<Violation.ViolationFactory> sFactoryRegistry; static { List<Violation.ViolationFactory> factoryRegistry = new LinkedList<Violation.ViolationFactory>(); factoryRegistry.add(new DiskReadThreadViolation.DiskReadThreadViolationFactory()); factoryRegistry.add(new DiskWriteThreadViolation.DiskWriteThreadViolationFactory()); factoryRegistry.add(new NetworkThreadViolation.NetworkThreadViolationFactory()); factoryRegistry.add(new CustomThreadViolation.CustomThreadViolationFactory()); factoryRegistry.add(new ThreadViolation.ThreadViolationFactory()); factoryRegistry.add(new ExplicitTerminationVmViolation.ExplicitTerminationVmViolationFactory()); factoryRegistry.add(new InstanceCountVmViolation.InstanceCountVmViolationFactory()); factoryRegistry.add(new Violation.ViolationFactory()); sFactoryRegistry = Collections.unmodifiableList(factoryRegistry); } public Violation createViolation(String data) { List<String> headers = new LinkedList<String>(); List<String> stackTrace = new LinkedList<String>(); extractHeadersAndException(data, headers, stackTrace); return createViolation(headers, stackTrace); } @VisibleForTesting protected Violation createViolation(List<String> rawHeaders, List<String> stackTrace) { Violation violation = null; Map<String, String> headers = parseHeaders(rawHeaders); ViolationException exception = parseException(stackTrace); for(ViolationFactory factory : sFactoryRegistry) { violation = factory.create(headers, exception); if(violation != null) { return violation; } } return null; } @VisibleForTesting protected void extractHeadersAndException(String data, List<String> headers, List<String> stackTrace) { List<String> lines = headers; BufferedReader reader = new BufferedReader(new StringReader(data)); try { String line = null; while((line = reader.readLine()) != null) { line = line.trim(); if(line.length() == 0) { lines = stackTrace; } else { lines.add(line); } } } catch(IOException ex) { throw new IllegalArgumentException("Failed to parse violation data", ex); } } /** * Format: * header-name: header-values */ @VisibleForTesting protected Map<String, String> parseHeaders(List<String> headers) { final Character separator = ':'; //NOPMD HashMap<String, String> map = new HashMap<String, String>(); for(String line : headers) { line = line.trim(); if(TextUtils.isEmpty(line) || line.equals(Character.toString(separator))) { //ignore empty line or line that consists only of separator (":") continue; } int separatorIndex = line.indexOf(separator); if(separatorIndex < 0) { map.put(line, null); } else { String key = line.substring(0, separatorIndex).trim(); String value = null; if(separatorIndex < line.length() - 1) { value = line.substring(separatorIndex + 1).trim(); } if(TextUtils.isEmpty(value)) { value = null; } map.put(key, value); } } return map; } /** * The exception is represented as sequence of lines, with first line describing * details about exception and all following lines being stack trace. * * For example: * android.os.StrictMode$StrictModeDiskWriteViolation: policy=415 violation=1 * at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1063) * at com.android.strictmodetest.ServiceBase$1.doDiskWrite(ServiceBase.java:72) * at com.android.strictmodetest.ServiceBase$1.doDiskWrite(ServiceBase.java:67) * * Sometimes violation can be detected in call to binder. * * For example: * android.os.StrictMode$StrictModeDiskWriteViolation: policy=415 violation=1 * at android.os.StrictMode$AndroidBlockGuardPolicy.onWriteToDisk(StrictMode.java:1063) * at com.android.strictmodetest.ServiceBase$1.doDiskWrite(ServiceBase.java:72) * at com.android.strictmodetest.ServiceBase$1.doDiskWrite(ServiceBase.java:67) * #via Binder call with stack: * android.os.StrictMode$LogStackTrace * at android.os.StrictMode.readAndHandleBinderCallViolations(StrictMode.java:1617) * at android.os.Parcel.readExceptionCode(Parcel.java:1309) * at android.os.Parcel.readException(Parcel.java:1278) * * This function will detect both cases. When second case is detected, the second exception * will be stored as "cause" exception. It can be retrieved via "getCause()" function. */ @VisibleForTesting protected ViolationException parseException(List<String> stackTrace) { ViolationException exception = null; LinkedList<String> exceptionStackTrace = new LinkedList<String>(); for(int i = stackTrace.size() - 1; i >= 0; i--) { String line = stackTrace.get(i).trim(); if(line.startsWith(STACK_TRACE_COMMENT_PREFIX)) { //NOPMD //just a comment, do nothing } else if(line.startsWith(STACK_TRACE_ENTRY_PREFIX)) { exceptionStackTrace.push(line); } else { exception = parseExceptionTitle(line, exception); exception.setStackTrace(parseExceptionStackTrace(exceptionStackTrace)); exceptionStackTrace.clear(); } } if(exception == null) { exception = new ViolationException(null, null); exception.setStackTrace(new StackTraceElement[0]); } return exception; } /** * Exception title: "classname: message". * For example: "android.os.StrictMode$StrictModeCustomViolation: policy=159 violation=8" * * This function extracts class name and message. * From example above: * Class Name: "android.os.StrictMode$StrictModeCustomViolation" * Message: "policy=159 violation=8" */ @VisibleForTesting protected ViolationException parseExceptionTitle(String title, ViolationException cause) { String className = null; String message = null; title = title.trim(); int separatorIndex = title.indexOf(':'); if(separatorIndex < 0) { className = title; } else { if(separatorIndex > 0) { className = title.substring(0, separatorIndex).trim(); } if(separatorIndex < title.length() - 1) { message = title.substring(separatorIndex + 1).trim(); } } if(TextUtils.isEmpty(className)) { className = null; } if(TextUtils.isEmpty(message)) { message = null; } return new ViolationException(className, message, cause); } @VisibleForTesting protected static List<String> fastSplit(String str, char...separators) { LinkedList<String> parts = new LinkedList<String>(); int lastSeparatorIndex = -1; int length = str.length(); for(int i = 0; i < length; i++) { boolean separator = false; char symbol = str.charAt(i); for(int separatorIndex = 0; separatorIndex < separators.length; separatorIndex++) { if(separators[separatorIndex] == symbol) { separator = true; break; } } if(separator) { parts.add(str.substring(lastSeparatorIndex + 1, i)); lastSeparatorIndex=i; } } parts.add(str.substring(lastSeparatorIndex + 1)); return parts; } /** * Stack trace has next format: * at android.os.Handler.handleCallback(Handler.java:605) * at android.os.Handler.dispatchMessage(Handler.java:92) * at android.os.Looper.loop(Looper.java:137) * at dalvik.system.NativeStart.main(Native Method) * * File name or line number might not be available. */ protected StackTraceElement[] parseExceptionStackTrace(List<String> stackTrace) { //NOPMD StackTraceElement [] elements = new StackTraceElement[stackTrace.size()]; for(int i = 0; i < stackTrace.size(); i++) { String line = stackTrace.get(i).trim(); if(line.startsWith(STACK_TRACE_ENTRY_PREFIX)) { line = line.substring(STACK_TRACE_ENTRY_PREFIX.length()); line = line.trim(); } /* format: package.name.className.func(file:line) */ List<String> parts = fastSplit(line, '(', ')'); String className = "";//default is an empty class name String method = "";//default is an empty function name String locationFileName = null; int locationLine = -1; if(parts.size() > 0) { //NOPMD String fullName = parts.get(0).trim(); int separator = fullName.lastIndexOf('.'); if(separator < 0) { /* no method name */ className = fullName; } else { /* class name and method are available */ className = fullName.substring(0, separator).trim(); if(separator < fullName.length() - 1) { method = fullName.substring(separator + 1).trim(); } } } if(parts.size() > 1) { String fullLocation = parts.get(1).trim(); - if(fullLocation.equalsIgnoreCase(STACK_TRACE_NATIVE_METHOD)) { + if(TextUtils.isEmpty(fullLocation)) { + locationFileName = null; + locationLine = -1; + } else if(fullLocation.equalsIgnoreCase(STACK_TRACE_NATIVE_METHOD)) { locationLine = -2;//as mentioned in documentation } else if(fullLocation.equalsIgnoreCase(STACK_TRACE_UNKNOWN_SOURCE)) { locationFileName = null; locationLine = -1; } else { /* extract file and line number */ List<String> locationParts = fastSplit(fullLocation, ':'); if(locationParts.size() > 0) { locationFileName = locationParts.get(0); } if(locationParts.size() > 1) { try { locationLine = Integer.parseInt(locationParts.get(1)); } catch(NumberFormatException ex) { //NOPMD //ignore } } } } elements[i] = new StackTraceElement(className, method, locationFileName, locationLine); } return elements; } }
true
true
protected StackTraceElement[] parseExceptionStackTrace(List<String> stackTrace) { //NOPMD StackTraceElement [] elements = new StackTraceElement[stackTrace.size()]; for(int i = 0; i < stackTrace.size(); i++) { String line = stackTrace.get(i).trim(); if(line.startsWith(STACK_TRACE_ENTRY_PREFIX)) { line = line.substring(STACK_TRACE_ENTRY_PREFIX.length()); line = line.trim(); } /* format: package.name.className.func(file:line) */ List<String> parts = fastSplit(line, '(', ')'); String className = "";//default is an empty class name String method = "";//default is an empty function name String locationFileName = null; int locationLine = -1; if(parts.size() > 0) { //NOPMD String fullName = parts.get(0).trim(); int separator = fullName.lastIndexOf('.'); if(separator < 0) { /* no method name */ className = fullName; } else { /* class name and method are available */ className = fullName.substring(0, separator).trim(); if(separator < fullName.length() - 1) { method = fullName.substring(separator + 1).trim(); } } } if(parts.size() > 1) { String fullLocation = parts.get(1).trim(); if(fullLocation.equalsIgnoreCase(STACK_TRACE_NATIVE_METHOD)) { locationLine = -2;//as mentioned in documentation } else if(fullLocation.equalsIgnoreCase(STACK_TRACE_UNKNOWN_SOURCE)) { locationFileName = null; locationLine = -1; } else { /* extract file and line number */ List<String> locationParts = fastSplit(fullLocation, ':'); if(locationParts.size() > 0) { locationFileName = locationParts.get(0); } if(locationParts.size() > 1) { try { locationLine = Integer.parseInt(locationParts.get(1)); } catch(NumberFormatException ex) { //NOPMD //ignore } } } } elements[i] = new StackTraceElement(className, method, locationFileName, locationLine); } return elements; }
protected StackTraceElement[] parseExceptionStackTrace(List<String> stackTrace) { //NOPMD StackTraceElement [] elements = new StackTraceElement[stackTrace.size()]; for(int i = 0; i < stackTrace.size(); i++) { String line = stackTrace.get(i).trim(); if(line.startsWith(STACK_TRACE_ENTRY_PREFIX)) { line = line.substring(STACK_TRACE_ENTRY_PREFIX.length()); line = line.trim(); } /* format: package.name.className.func(file:line) */ List<String> parts = fastSplit(line, '(', ')'); String className = "";//default is an empty class name String method = "";//default is an empty function name String locationFileName = null; int locationLine = -1; if(parts.size() > 0) { //NOPMD String fullName = parts.get(0).trim(); int separator = fullName.lastIndexOf('.'); if(separator < 0) { /* no method name */ className = fullName; } else { /* class name and method are available */ className = fullName.substring(0, separator).trim(); if(separator < fullName.length() - 1) { method = fullName.substring(separator + 1).trim(); } } } if(parts.size() > 1) { String fullLocation = parts.get(1).trim(); if(TextUtils.isEmpty(fullLocation)) { locationFileName = null; locationLine = -1; } else if(fullLocation.equalsIgnoreCase(STACK_TRACE_NATIVE_METHOD)) { locationLine = -2;//as mentioned in documentation } else if(fullLocation.equalsIgnoreCase(STACK_TRACE_UNKNOWN_SOURCE)) { locationFileName = null; locationLine = -1; } else { /* extract file and line number */ List<String> locationParts = fastSplit(fullLocation, ':'); if(locationParts.size() > 0) { locationFileName = locationParts.get(0); } if(locationParts.size() > 1) { try { locationLine = Integer.parseInt(locationParts.get(1)); } catch(NumberFormatException ex) { //NOPMD //ignore } } } } elements[i] = new StackTraceElement(className, method, locationFileName, locationLine); } return elements; }
diff --git a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java index e703140e1..1ab82a686 100644 --- a/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java +++ b/bundles/org.eclipse.team.cvs.core/src/org/eclipse/team/internal/ccvs/core/connection/PServerConnection.java @@ -1,251 +1,251 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.team.internal.ccvs.core.connection; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.net.Socket; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation; import org.eclipse.team.internal.ccvs.core.IServerConnection; import org.eclipse.team.internal.ccvs.core.Policy; import org.eclipse.team.internal.ccvs.core.util.Util; import org.eclipse.team.internal.core.streams.PollingInputStream; import org.eclipse.team.internal.core.streams.PollingOutputStream; import org.eclipse.team.internal.core.streams.TimeoutOutputStream; /** * A connection used to talk to an cvs pserver. */ public class PServerConnection implements IServerConnection { public static final char NEWLINE= 0xA; /** default CVS pserver port */ private static final int DEFAULT_PORT= 2401; /** error line indicators */ private static final char ERROR_CHAR = 'E'; private static final String ERROR_MESSAGE = "error 0";//$NON-NLS-1$ private static final String NO_SUCH_USER = "no such user";//$NON-NLS-1$ private static final char[] SCRAMBLING_TABLE=new char[] { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15, 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31, 114,120,53,79,96,109,72,108,70,64,76,67,116,74,68,87, 111,52,75,119,49,34,82,81,95,65,112,86,118,110,122,105, 41,57,83,43,46,102,40,89,38,103,45,50,42,123,91,35, 125,55,54,66,124,126,59,47,92,71,115,78,88,107,106,56, 36,121,117,104,101,100,69,73,99,63,94,93,39,37,61,48, 58,113,32,90,44,98,60,51,33,97,62,77,84,80,85,223, 225,216,187,166,229,189,222,188,141,249,148,200,184,136,248,190, 199,170,181,204,138,232,218,183,255,234,220,247,213,203,226,193, 174,172,228,252,217,201,131,230,197,211,145,238,161,179,160,212, 207,221,254,173,202,146,224,151,140,196,205,130,135,133,143,246, 192,159,244,239,185,168,215,144,139,165,180,157,147,186,214,176, 227,231,219,169,175,156,206,198,129,164,150,210,154,177,134,127, 182,128,158,208,162,132,167,209,149,241,153,251,237,236,171,195, 243,233,253,240,194,250,191,155,142,137,245,235,163,242,178,152 }; /** Communication strings */ private static final String BEGIN= "BEGIN AUTH REQUEST";//$NON-NLS-1$ private static final String END= "END AUTH REQUEST";//$NON-NLS-1$ private static final String LOGIN_OK= "I LOVE YOU";//$NON-NLS-1$ private static final String LOGIN_FAILED= "I HATE YOU";//$NON-NLS-1$ private String password; private ICVSRepositoryLocation cvsroot; private Socket fSocket; private InputStream inputStream; private OutputStream outputStream; /** * @see Connection#doClose() */ public void close() throws IOException { try { if (inputStream != null) inputStream.close(); } finally { inputStream = null; try { if (outputStream != null) outputStream.close(); } finally { outputStream = null; try { if (fSocket != null) fSocket.close(); } finally { fSocket = null; } } } } /** * @see Connection#doOpen() */ public void open(IProgressMonitor monitor) throws IOException, CVSAuthenticationException { monitor.subTask(Policy.bind("PServerConnection.authenticating"));//$NON-NLS-1$ monitor.worked(1); fSocket = createSocket(monitor); boolean connected = false; try { this.inputStream = new BufferedInputStream(new PollingInputStream(fSocket.getInputStream(), cvsroot.getTimeout(), monitor)); this.outputStream = new PollingOutputStream(new TimeoutOutputStream( fSocket.getOutputStream(), 8192 /*bufferSize*/, 1000 /*writeTimeout*/, 1000 /*closeTimeout*/), cvsroot.getTimeout(), monitor); authenticate(); connected = true; } finally { if (! connected) cleanUpAfterFailedConnection(); } } /** * @see Connection#getInputStream() */ public InputStream getInputStream() { return inputStream; } /** * @see Connection#getOutputStream() */ public OutputStream getOutputStream() { return outputStream; } /** * Creates a new <code>PServerConnection</code> for the given * cvs root. */ PServerConnection(ICVSRepositoryLocation cvsroot, String password) { this.cvsroot = cvsroot; this.password = password; } /** * Does the actual authentification. */ private void authenticate() throws IOException, CVSAuthenticationException { String scrambledPassword = scramblePassword(password); String user = cvsroot.getUsername(); OutputStream out = getOutputStream(); StringBuffer request = new StringBuffer(); request.append(BEGIN); request.append(NEWLINE); request.append(cvsroot.getRootDirectory()); request.append(NEWLINE); request.append(user); request.append(NEWLINE); request.append(scrambledPassword); request.append(NEWLINE); request.append(END); request.append(NEWLINE); out.write(request.toString().getBytes()); out.flush(); - String line = Connection.readLine(cvsroot, getInputStream()); + String line = Connection.readLine(cvsroot, getInputStream()).trim(); // Return if we succeeded if (LOGIN_OK.equals(line)) return; // Otherwise, determine the type of error if (line.length() == 0) throw new IOException(Policy.bind("PServerConnection.noResponse"));//$NON-NLS-1$ if (LOGIN_FAILED.equals(line)) throw new CVSAuthenticationException(Policy.bind("PServerConnection.loginRefused"), CVSAuthenticationException.RETRY);//$NON-NLS-1$ String message = "";//$NON-NLS-1$ // Skip any E messages for now while (line.charAt(0) == ERROR_CHAR) { // message += line.substring(1) + " "; line = Connection.readLine(cvsroot, getInputStream()); } // Remove leading "error 0" if (line.startsWith(ERROR_MESSAGE)) message += line.substring(ERROR_MESSAGE.length() + 1); else message += line; if (message.indexOf(NO_SUCH_USER) != -1) throw new CVSAuthenticationException(Policy.bind("PServerConnection.invalidUser", new Object[] {message}), CVSAuthenticationException.RETRY);//$NON-NLS-1$ throw new IOException(Policy.bind("PServerConnection.connectionRefused", new Object[] { message }));//$NON-NLS-1$ } /* * Called if there are exceptions when connecting. * This method makes sure that all connections are closed. */ private void cleanUpAfterFailedConnection() throws IOException { try { if (inputStream != null) inputStream.close(); } finally { try { if (outputStream != null) outputStream.close(); } finally { try { if (fSocket != null) fSocket.close(); } finally { fSocket = null; } } } } /** * Creates the actual socket */ protected Socket createSocket(IProgressMonitor monitor) throws IOException { // Determine what port to use int port = cvsroot.getPort(); if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) port = DEFAULT_PORT; // Make the connection Socket result; try { result= Util.createSocket(cvsroot.getHost(), port, monitor); // Bug 36351: disable buffering and send bytes immediately result.setTcpNoDelay(true); } catch (InterruptedIOException e) { // If we get this exception, chances are the host is not responding throw new InterruptedIOException(Policy.bind("PServerConnection.socket", new Object[] {cvsroot.getHost()}));//$NON-NLS-1$ } result.setSoTimeout(1000); // 1 second between timeouts return result; } private String scramblePassword(String password) throws CVSAuthenticationException { int length = password.length(); char[] out= new char[length]; for (int i= 0; i < length; i++) { char value = password.charAt(i); if( value < 0 || value > 255 ) throwInValidCharacter(); out[i]= SCRAMBLING_TABLE[value]; } return "A" + new String(out);//$NON-NLS-1$ } private void throwInValidCharacter() throws CVSAuthenticationException { throw new CVSAuthenticationException(Policy.bind("PServerConnection.invalidChars"), CVSAuthenticationException.RETRY);//$NON-NLS-1$ } }
true
true
private void authenticate() throws IOException, CVSAuthenticationException { String scrambledPassword = scramblePassword(password); String user = cvsroot.getUsername(); OutputStream out = getOutputStream(); StringBuffer request = new StringBuffer(); request.append(BEGIN); request.append(NEWLINE); request.append(cvsroot.getRootDirectory()); request.append(NEWLINE); request.append(user); request.append(NEWLINE); request.append(scrambledPassword); request.append(NEWLINE); request.append(END); request.append(NEWLINE); out.write(request.toString().getBytes()); out.flush(); String line = Connection.readLine(cvsroot, getInputStream()); // Return if we succeeded if (LOGIN_OK.equals(line)) return; // Otherwise, determine the type of error if (line.length() == 0) throw new IOException(Policy.bind("PServerConnection.noResponse"));//$NON-NLS-1$ if (LOGIN_FAILED.equals(line)) throw new CVSAuthenticationException(Policy.bind("PServerConnection.loginRefused"), CVSAuthenticationException.RETRY);//$NON-NLS-1$ String message = "";//$NON-NLS-1$ // Skip any E messages for now while (line.charAt(0) == ERROR_CHAR) { // message += line.substring(1) + " "; line = Connection.readLine(cvsroot, getInputStream()); } // Remove leading "error 0" if (line.startsWith(ERROR_MESSAGE)) message += line.substring(ERROR_MESSAGE.length() + 1); else message += line; if (message.indexOf(NO_SUCH_USER) != -1) throw new CVSAuthenticationException(Policy.bind("PServerConnection.invalidUser", new Object[] {message}), CVSAuthenticationException.RETRY);//$NON-NLS-1$ throw new IOException(Policy.bind("PServerConnection.connectionRefused", new Object[] { message }));//$NON-NLS-1$ }
private void authenticate() throws IOException, CVSAuthenticationException { String scrambledPassword = scramblePassword(password); String user = cvsroot.getUsername(); OutputStream out = getOutputStream(); StringBuffer request = new StringBuffer(); request.append(BEGIN); request.append(NEWLINE); request.append(cvsroot.getRootDirectory()); request.append(NEWLINE); request.append(user); request.append(NEWLINE); request.append(scrambledPassword); request.append(NEWLINE); request.append(END); request.append(NEWLINE); out.write(request.toString().getBytes()); out.flush(); String line = Connection.readLine(cvsroot, getInputStream()).trim(); // Return if we succeeded if (LOGIN_OK.equals(line)) return; // Otherwise, determine the type of error if (line.length() == 0) throw new IOException(Policy.bind("PServerConnection.noResponse"));//$NON-NLS-1$ if (LOGIN_FAILED.equals(line)) throw new CVSAuthenticationException(Policy.bind("PServerConnection.loginRefused"), CVSAuthenticationException.RETRY);//$NON-NLS-1$ String message = "";//$NON-NLS-1$ // Skip any E messages for now while (line.charAt(0) == ERROR_CHAR) { // message += line.substring(1) + " "; line = Connection.readLine(cvsroot, getInputStream()); } // Remove leading "error 0" if (line.startsWith(ERROR_MESSAGE)) message += line.substring(ERROR_MESSAGE.length() + 1); else message += line; if (message.indexOf(NO_SUCH_USER) != -1) throw new CVSAuthenticationException(Policy.bind("PServerConnection.invalidUser", new Object[] {message}), CVSAuthenticationException.RETRY);//$NON-NLS-1$ throw new IOException(Policy.bind("PServerConnection.connectionRefused", new Object[] { message }));//$NON-NLS-1$ }
diff --git a/src/rajawali/renderer/RajawaliRenderer.java b/src/rajawali/renderer/RajawaliRenderer.java index 54d0ed87..9cf3876b 100644 --- a/src/rajawali/renderer/RajawaliRenderer.java +++ b/src/rajawali/renderer/RajawaliRenderer.java @@ -1,768 +1,769 @@ package rajawali.renderer; import java.util.Collections; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CopyOnWriteArrayList; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import rajawali.BaseObject3D; import rajawali.Camera; import rajawali.animation.Animation3D; import rajawali.filters.IPostProcessingFilter; import rajawali.materials.AMaterial; import rajawali.materials.SimpleMaterial; import rajawali.materials.SkyboxMaterial; import rajawali.materials.TextureInfo; import rajawali.materials.TextureManager; import rajawali.math.Number3D; import rajawali.primitives.Cube; import rajawali.renderer.plugins.IRendererPlugin; import rajawali.util.FPSUpdateListener; import rajawali.util.ObjectColorPicker.ColorPickerInfo; import rajawali.util.RajLog; import rajawali.visitors.INode; import rajawali.visitors.INodeVisitor; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.opengl.Matrix; import android.os.SystemClock; import android.service.wallpaper.WallpaperService; import android.view.MotionEvent; import android.view.WindowManager; public class RajawaliRenderer implements GLSurfaceView.Renderer, INode { protected final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000; protected Context mContext; protected float mEyeZ = 4.0f; protected float mFrameRate; protected double mLastMeasuredFPS; protected FPSUpdateListener mFPSUpdateListener; protected SharedPreferences preferences; protected int mViewportWidth, mViewportHeight; protected WallpaperService.Engine mWallpaperEngine; protected GLSurfaceView mSurfaceView; protected Timer mTimer; protected int mFrameCount; private long mStartTime = System.nanoTime(); private long mLastRender; protected float[] mVMatrix = new float[16]; protected float[] mPMatrix = new float[16]; protected List<BaseObject3D> mChildren; private List<Animation3D> mAnimations; protected boolean mEnableDepthBuffer = true; protected TextureManager mTextureManager; protected PostProcessingRenderer mPostProcessingRenderer; /** * Deprecated. Use setSceneCachingEnabled(false) instead. */ @Deprecated protected boolean mClearChildren = true; /** * The camera currently in use. * Not thread safe for speed, should * only be used by GL thread (onDrawFrame() and render()) * or prior to rendering such as initScene(). */ protected Camera mCamera; /** * List of all cameras in the scene. */ protected List<Camera> mCameras; /** * Temporary camera which will be switched to by the GL thread. * Guarded by mNextCameraLock */ protected Camera mNextCamera; private final Object mNextCameraLock = new Object(); protected float mRed, mBlue, mGreen, mAlpha; protected Cube mSkybox; protected TextureInfo mSkyboxTextureInfo; protected static int mMaxLights = 1; protected ColorPickerInfo mPickerInfo; protected List<IPostProcessingFilter> mFilters; protected boolean mReloadPickerInfo; protected static boolean mFogEnabled; protected boolean mUsesCoverageAa; public static boolean supportsUIntBuffers = false; protected boolean mSceneInitialized; /** * Scene caching stores all textures and relevant OpenGL-specific * data. This is used when the OpenGL context needs to be restored. * The context typically needs to be restored when the application * is re-activated or when a live wallpaper is rotated. */ private boolean mSceneCachingEnabled; protected List<IRendererPlugin> mPlugins; public RajawaliRenderer(Context context) { RajLog.i("IMPORTANT: Rajawali's coordinate system has changed. It now reflects"); RajLog.i("the OpenGL standard. Please invert the camera's z coordinate or"); RajLog.i("call mCamera.setLookAt(0, 0, 0)."); AMaterial.setLoaderContext(context); mContext = context; mAnimations = Collections.synchronizedList(new CopyOnWriteArrayList<Animation3D>()); mChildren = Collections.synchronizedList(new CopyOnWriteArrayList<BaseObject3D>()); mFilters = Collections.synchronizedList(new CopyOnWriteArrayList<IPostProcessingFilter>()); mPlugins = Collections.synchronizedList(new CopyOnWriteArrayList<IRendererPlugin>()); mCamera = new Camera(); mCameras = Collections.synchronizedList(new CopyOnWriteArrayList<Camera>()); addCamera(mCamera); mCamera.setZ(mEyeZ); mAlpha = 0; mSceneCachingEnabled = true; mPostProcessingRenderer = new PostProcessingRenderer(this); mFrameRate = getRefreshRate(); } /** * Register an animation to be managed by the renderer. This is optional leaving open the possibility to manage * updates on Animations in your own implementation. Returns true on success. * * @param anim * @return */ public boolean registerAnimation(Animation3D anim) { return mAnimations.add(anim); } /** * Remove a managed animation. Returns true on success. * * @param anim * @return */ public boolean unregisterAnimation(Animation3D anim) { return mAnimations.remove(anim); } /** * Sets the camera currently being used to display the scene. * * @param mCamera Camera object to display the scene with. */ public void setCamera(Camera camera) { synchronized (mNextCameraLock) { mNextCamera = camera; } } /** * Sets the camera currently being used to display the scene. * * @param camera Index of the camera to use. */ public void setCamera(int camera) { setCamera(mCameras.get(camera)); } /** * Fetches the camera currently being used to display the scene. * Note that the camera is not thread safe so this should be used * with extreme caution. * * @return Camera object currently used for the scene. * @see {@link RajawaliRenderer#mCamera} */ public Camera getCamera() { return this.mCamera; } /** * Fetches the specified camera. * * @param camera Index of the camera to fetch. * @return Camera which was retrieved. */ public Camera getCamera(int camera) { return mCameras.get(camera); } /** * Adds a camera to the renderer. * * @param camera Camera object to add. * @return int The index the new camera was added at. */ public int addCamera(Camera camera) { mCameras.add(camera); return (mCameras.size() - 1); } /** * Replaces a camera in the renderer at the specified location * in the list. This does not validate the index, so if it is not * contained in the list already, an exception will be thrown. * * @param camera Camera object to add. * @param location Integer index of the camera to replace. */ public void replaceCamera(Camera camera, int location) { mCameras.set(location, camera); } /** * Adds a camera with the option to switch to it immediately * * @param camera The Camera to add. * @param useNow Boolean indicating if we should switch to this * camera immediately. * @return int The index the new camera was added at. */ public int addCamera(Camera camera, boolean useNow) { int index = addCamera(camera); if (useNow) setCamera(camera); return index; } /** * Replaces a camera at the specified index with an option to switch to it * immediately. * * @param camera The Camera to add. * @param location The index of the camera to replace. * @param useNow Boolean indicating if we should switch to this * camera immediately. */ public void replaceCamera(Camera camera, int location, boolean useNow) { replaceCamera(camera, location); if (useNow) setCamera(camera); } public void requestColorPickingTexture(ColorPickerInfo pickerInfo) { mPickerInfo = pickerInfo; } public void onDrawFrame(GL10 glUnused) { synchronized (mNextCameraLock) { //Check if we need to switch the camera, and if so, do it. if (mNextCamera != null) { mCamera = mNextCamera; mNextCamera = null; mCamera.setProjectionMatrix(mViewportWidth, mViewportHeight); } } render(); ++mFrameCount; if (mFrameCount % 50 == 0) { long now = System.nanoTime(); double elapsedS = (now - mStartTime) / 1.0e9; double msPerFrame = (1000 * elapsedS / mFrameCount); mLastMeasuredFPS = 1000 / msPerFrame; //RajLog.d("ms / frame: " + msPerFrame + " - fps: " + mLastMeasuredFPS); mFrameCount = 0; mStartTime = now; if(mFPSUpdateListener != null) mFPSUpdateListener.onFPSUpdate(mLastMeasuredFPS); } } private void render() { final double deltaTime = (SystemClock.elapsedRealtime() - mLastRender) / 1000d; mLastRender = SystemClock.elapsedRealtime(); int clearMask = GLES20.GL_COLOR_BUFFER_BIT; ColorPickerInfo pickerInfo = mPickerInfo; mTextureManager.validateTextures(); if (pickerInfo != null) { if(mReloadPickerInfo) pickerInfo.getPicker().reload(); mReloadPickerInfo = false; pickerInfo.getPicker().bindFrameBuffer(); GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); } else { if (mFilters.size() == 0) GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); else { if (mPostProcessingRenderer.isEnabled()) mPostProcessingRenderer.bind(); } GLES20.glClearColor(mRed, mGreen, mBlue, mAlpha); } if (mEnableDepthBuffer) { clearMask |= GLES20.GL_DEPTH_BUFFER_BIT; GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthFunc(GLES20.GL_LESS); GLES20.glDepthMask(true); GLES20.glClearDepthf(1.0f); } if (mUsesCoverageAa) { clearMask |= GL_COVERAGE_BUFFER_BIT_NV; } GLES20.glClear(clearMask); mVMatrix = mCamera.getViewMatrix(); mPMatrix = mCamera.getProjectionMatrix(); if (mSkybox != null) { GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(false); mSkybox.setPosition(mCamera.getX(), mCamera.getY(), mCamera.getZ()); mSkybox.render(mCamera, mPMatrix, mVMatrix, pickerInfo); if (mEnableDepthBuffer) { GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(true); } } mCamera.updateFrustum(mPMatrix,mVMatrix); //update frustum plane // Update all registered animations - for (int i = 0, j = mAnimations.size(); i < j; i++) + for (int i = 0; i < mAnimations.size(); i++) { mAnimations.get(i).update(deltaTime); + } for (int i = 0; i < mChildren.size(); i++) mChildren.get(i).render(mCamera, mPMatrix, mVMatrix, pickerInfo); if (pickerInfo != null) { pickerInfo.getPicker().createColorPickingTexture(pickerInfo); pickerInfo.getPicker().unbindFrameBuffer(); pickerInfo = null; mPickerInfo = null; render(); } else if (mPostProcessingRenderer.isEnabled()) { mPostProcessingRenderer.render(); } for (int i = 0, j = mPlugins.size(); i < j; i++) mPlugins.get(i).render(); } public void onOffsetsChanged(float xOffset, float yOffset, float xOffsetStep, float yOffsetStep, int xPixelOffset, int yPixelOffset) { } public void onTouchEvent(MotionEvent event) { } public void onSurfaceChanged(GL10 gl, int width, int height) { mViewportWidth = width; mViewportHeight = height; mCamera.setProjectionMatrix(width, height); GLES20.glViewport(0, 0, width, height); } /* Called when the OpenGL context is created or re-created. Don't set up your scene here, * use initScene() for that. * * @see rajawali.renderer.RajawaliRenderer#initScene * @see android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition.khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig) * */ public void onSurfaceCreated(GL10 gl, EGLConfig config) { supportsUIntBuffers = gl.glGetString(GL10.GL_EXTENSIONS).indexOf("GL_OES_element_index_uint") > -1; GLES20.glFrontFace(GLES20.GL_CCW); GLES20.glCullFace(GLES20.GL_BACK); if (!mSceneInitialized) { mTextureManager = new TextureManager(mContext); initScene(); } if (!mSceneCachingEnabled) { mTextureManager.reset(); if (mChildren.size() > 0) { mChildren.clear(); } if (mPlugins.size() > 0) { mPlugins.clear(); } } else if(mSceneCachingEnabled && mSceneInitialized) { mTextureManager.reload(); reloadChildren(); if(mSkybox != null) mSkybox.reload(); if(mPostProcessingRenderer.isInitialized()) mPostProcessingRenderer.reload(); reloadPlugins(); mReloadPickerInfo = true; } mSceneInitialized = true; startRendering(); } private void reloadChildren() { for (int i = 0; i < mChildren.size(); i++) mChildren.get(i).reload(); } private void reloadPlugins() { for (int i = 0, j = mPlugins.size(); i < j; i++) mPlugins.get(i).reload(); } /** * Scene construction should happen here, not in onSurfaceCreated() */ protected void initScene() { } protected void destroyScene() { mSceneInitialized = false; for (int i = 0; i < mChildren.size(); i++) mChildren.get(i).destroy(); mChildren.clear(); for (int i = 0, j = mPlugins.size(); i < j; i++) mPlugins.get(i).destroy(); mPlugins.clear(); } public void startRendering() { mLastRender = SystemClock.elapsedRealtime(); if (mTimer != null) { mTimer.cancel(); mTimer.purge(); } mTimer = new Timer(); mTimer.schedule(new RequestRenderTask(), 0, (long) (1000 / mFrameRate)); } /** * Stop rendering the scene. * * @return true if rendering was stopped, false if rendering was already * stopped (no action taken) */ protected boolean stopRendering() { if (mTimer != null) { mTimer.cancel(); mTimer.purge(); mTimer = null; return true; } return false; } public void onVisibilityChanged(boolean visible) { if (!visible) { stopRendering(); } else startRendering(); } public void onSurfaceDestroyed() { stopRendering(); if (mTextureManager != null) mTextureManager.reset(); destroyScene(); } public void setSharedPreferences(SharedPreferences preferences) { this.preferences = preferences; } private class RequestRenderTask extends TimerTask { public void run() { if (mSurfaceView != null) { mSurfaceView.requestRender(); } } } public Number3D unProject(float x, float y, float z) { x = mViewportWidth - x; y = mViewportHeight - y; float[] m = new float[16], mvpmatrix = new float[16], in = new float[4], out = new float[4]; Matrix.multiplyMM(mvpmatrix, 0, mPMatrix, 0, mVMatrix, 0); Matrix.invertM(m, 0, mvpmatrix, 0); in[0] = (x / (float)mViewportWidth) * 2 - 1; in[1] = (y / (float)mViewportHeight) * 2 - 1; in[2] = 2 * z - 1; in[3] = 1; Matrix.multiplyMV(out, 0, m, 0, in, 0); if (out[3]==0) return null; out[3] = 1/out[3]; return new Number3D(out[0] * out[3], out[1] * out[3], out[2] * out[3]); } public float getFrameRate() { return mFrameRate; } public void setFrameRate(int frameRate) { setFrameRate((float)frameRate); } public void setFrameRate(float frameRate) { this.mFrameRate = frameRate; if (stopRendering()) { // Restart timer with new frequency startRendering(); } } public float getRefreshRate() { return ((WindowManager) mContext .getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay() .getRefreshRate(); } public WallpaperService.Engine getEngine() { return mWallpaperEngine; } public void setEngine(WallpaperService.Engine engine) { this.mWallpaperEngine = engine; } public GLSurfaceView getSurfaceView() { return mSurfaceView; } public void setSurfaceView(GLSurfaceView surfaceView) { this.mSurfaceView = surfaceView; } public Context getContext() { return mContext; } public TextureManager getTextureManager() { return mTextureManager; } public void addChild(BaseObject3D child) { mChildren.add(child); } public void clearChildren() { mChildren.clear(); } public void addPlugin(IRendererPlugin plugin) { mPlugins.add(plugin); } public void clearPlugins() { mPlugins.clear(); } protected void setSkybox(int resourceId) { mCamera.setFarPlane(1000); mSkybox = new Cube(700, true, false); mSkybox.setDoubleSided(true); mSkyboxTextureInfo = mTextureManager.addTexture(BitmapFactory.decodeResource(mContext.getResources(), resourceId)); SimpleMaterial material = new SimpleMaterial(); material.addTexture(mSkyboxTextureInfo); mSkybox.setMaterial(material); } protected void setSkybox(int front, int right, int back, int left, int up, int down) { mCamera.setFarPlane(1000); mSkybox = new Cube(700, true); Bitmap[] textures = new Bitmap[6]; textures[0] = BitmapFactory.decodeResource(mContext.getResources(), left); textures[1] = BitmapFactory.decodeResource(mContext.getResources(), right); textures[2] = BitmapFactory.decodeResource(mContext.getResources(), up); textures[3] = BitmapFactory.decodeResource(mContext.getResources(), down); textures[4] = BitmapFactory.decodeResource(mContext.getResources(), front); textures[5] = BitmapFactory.decodeResource(mContext.getResources(), back); mSkyboxTextureInfo = mTextureManager.addCubemapTextures(textures); SkyboxMaterial mat = new SkyboxMaterial(); mat.addTexture(mSkyboxTextureInfo); mSkybox.setMaterial(mat); } protected void updateSkybox(int resourceId) { mTextureManager.updateTexture(mSkyboxTextureInfo, BitmapFactory.decodeResource(mContext.getResources(), resourceId)); } protected void updateSkybox(int front, int right, int back, int left, int up, int down) { Bitmap[] textures = new Bitmap[6]; textures[0] = BitmapFactory.decodeResource(mContext.getResources(), left); textures[1] = BitmapFactory.decodeResource(mContext.getResources(), right); textures[2] = BitmapFactory.decodeResource(mContext.getResources(), up); textures[3] = BitmapFactory.decodeResource(mContext.getResources(), down); textures[4] = BitmapFactory.decodeResource(mContext.getResources(), front); textures[5] = BitmapFactory.decodeResource(mContext.getResources(), back); mTextureManager.updateCubemapTextures(mSkyboxTextureInfo, textures); } public boolean removeChild(BaseObject3D child) { return mChildren.remove(child); } public boolean removePlugin(IRendererPlugin plugin) { return mPlugins.remove(plugin); } public int getNumPlugins() { return mPlugins.size(); } public List<IRendererPlugin> getPlugins() { return mPlugins; } public boolean hasPlugin(IRendererPlugin plugin) { return mPlugins.contains(plugin); } public int getNumChildren() { return mChildren.size(); } public List<BaseObject3D> getChildren() { return mChildren; } protected boolean hasChild(BaseObject3D child) { return mChildren.contains(child); } public void addPostProcessingFilter(IPostProcessingFilter filter) { if(mFilters.size() > 0) mFilters.remove(0); mFilters.add(filter); mPostProcessingRenderer.setEnabled(true); mPostProcessingRenderer.setFilter(filter); } public void accept(INodeVisitor visitor) { visitor.apply(this); for (int i = 0; i < mChildren.size(); i++) mChildren.get(i).accept(visitor); } public void removePostProcessingFilter(IPostProcessingFilter filter) { mFilters.remove(filter); } public void clearPostProcessingFilters() { mFilters.clear(); mPostProcessingRenderer.unbind(); mPostProcessingRenderer.destroy(); mPostProcessingRenderer = new PostProcessingRenderer(this); } public int getViewportWidth() { return mViewportWidth; } public int getViewportHeight() { return mViewportHeight; } public void setBackgroundColor(float red, float green, float blue, float alpha) { mRed = red; mGreen = green; mBlue = blue; mAlpha = alpha; } public void setBackgroundColor(int color) { setBackgroundColor(Color.red(color) / 255f, Color.green(color) / 255f, Color.blue(color) / 255f, Color.alpha(color) / 255f); } public boolean getSceneInitialized() { return mSceneInitialized; } public void setSceneCachingEnabled(boolean enabled) { mSceneCachingEnabled = enabled; } public boolean getSceneCachingEnabled() { return mSceneCachingEnabled; } public void setFogEnabled(boolean enabled) { mFogEnabled = enabled; mCamera.setFogEnabled(enabled); } public void setUsesCoverageAa(boolean value) { mUsesCoverageAa = value; } public static boolean isFogEnabled() { return mFogEnabled; } public static int getMaxLights() { return mMaxLights; } public static void setMaxLights(int maxLights) { RajawaliRenderer.mMaxLights = maxLights; } public void setFPSUpdateListener(FPSUpdateListener listener) { mFPSUpdateListener = listener; } public static int checkGLError(String message) { int error = GLES20.glGetError(); if(error != GLES20.GL_NO_ERROR) { StringBuffer sb = new StringBuffer(); if(message != null) sb.append("[").append(message).append("] "); sb.append("GLES20 Error: "); sb.append(GLU.gluErrorString(error)); RajLog.e(sb.toString()); } return error; } public int getNumTriangles() { int triangleCount = 0; for (int i = 0; i < mChildren.size(); i++) { if (mChildren.get(i).getGeometry() != null && mChildren.get(i).getGeometry().getVertices() != null && mChildren.get(i).isVisible()) triangleCount += mChildren.get(i).getGeometry().getVertices().limit() / 9; } return triangleCount; } }
false
true
private void render() { final double deltaTime = (SystemClock.elapsedRealtime() - mLastRender) / 1000d; mLastRender = SystemClock.elapsedRealtime(); int clearMask = GLES20.GL_COLOR_BUFFER_BIT; ColorPickerInfo pickerInfo = mPickerInfo; mTextureManager.validateTextures(); if (pickerInfo != null) { if(mReloadPickerInfo) pickerInfo.getPicker().reload(); mReloadPickerInfo = false; pickerInfo.getPicker().bindFrameBuffer(); GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); } else { if (mFilters.size() == 0) GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); else { if (mPostProcessingRenderer.isEnabled()) mPostProcessingRenderer.bind(); } GLES20.glClearColor(mRed, mGreen, mBlue, mAlpha); } if (mEnableDepthBuffer) { clearMask |= GLES20.GL_DEPTH_BUFFER_BIT; GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthFunc(GLES20.GL_LESS); GLES20.glDepthMask(true); GLES20.glClearDepthf(1.0f); } if (mUsesCoverageAa) { clearMask |= GL_COVERAGE_BUFFER_BIT_NV; } GLES20.glClear(clearMask); mVMatrix = mCamera.getViewMatrix(); mPMatrix = mCamera.getProjectionMatrix(); if (mSkybox != null) { GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(false); mSkybox.setPosition(mCamera.getX(), mCamera.getY(), mCamera.getZ()); mSkybox.render(mCamera, mPMatrix, mVMatrix, pickerInfo); if (mEnableDepthBuffer) { GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(true); } } mCamera.updateFrustum(mPMatrix,mVMatrix); //update frustum plane // Update all registered animations for (int i = 0, j = mAnimations.size(); i < j; i++) mAnimations.get(i).update(deltaTime); for (int i = 0; i < mChildren.size(); i++) mChildren.get(i).render(mCamera, mPMatrix, mVMatrix, pickerInfo); if (pickerInfo != null) { pickerInfo.getPicker().createColorPickingTexture(pickerInfo); pickerInfo.getPicker().unbindFrameBuffer(); pickerInfo = null; mPickerInfo = null; render(); } else if (mPostProcessingRenderer.isEnabled()) { mPostProcessingRenderer.render(); } for (int i = 0, j = mPlugins.size(); i < j; i++) mPlugins.get(i).render(); }
private void render() { final double deltaTime = (SystemClock.elapsedRealtime() - mLastRender) / 1000d; mLastRender = SystemClock.elapsedRealtime(); int clearMask = GLES20.GL_COLOR_BUFFER_BIT; ColorPickerInfo pickerInfo = mPickerInfo; mTextureManager.validateTextures(); if (pickerInfo != null) { if(mReloadPickerInfo) pickerInfo.getPicker().reload(); mReloadPickerInfo = false; pickerInfo.getPicker().bindFrameBuffer(); GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); } else { if (mFilters.size() == 0) GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER, 0); else { if (mPostProcessingRenderer.isEnabled()) mPostProcessingRenderer.bind(); } GLES20.glClearColor(mRed, mGreen, mBlue, mAlpha); } if (mEnableDepthBuffer) { clearMask |= GLES20.GL_DEPTH_BUFFER_BIT; GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthFunc(GLES20.GL_LESS); GLES20.glDepthMask(true); GLES20.glClearDepthf(1.0f); } if (mUsesCoverageAa) { clearMask |= GL_COVERAGE_BUFFER_BIT_NV; } GLES20.glClear(clearMask); mVMatrix = mCamera.getViewMatrix(); mPMatrix = mCamera.getProjectionMatrix(); if (mSkybox != null) { GLES20.glDisable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(false); mSkybox.setPosition(mCamera.getX(), mCamera.getY(), mCamera.getZ()); mSkybox.render(mCamera, mPMatrix, mVMatrix, pickerInfo); if (mEnableDepthBuffer) { GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glDepthMask(true); } } mCamera.updateFrustum(mPMatrix,mVMatrix); //update frustum plane // Update all registered animations for (int i = 0; i < mAnimations.size(); i++) { mAnimations.get(i).update(deltaTime); } for (int i = 0; i < mChildren.size(); i++) mChildren.get(i).render(mCamera, mPMatrix, mVMatrix, pickerInfo); if (pickerInfo != null) { pickerInfo.getPicker().createColorPickingTexture(pickerInfo); pickerInfo.getPicker().unbindFrameBuffer(); pickerInfo = null; mPickerInfo = null; render(); } else if (mPostProcessingRenderer.isEnabled()) { mPostProcessingRenderer.render(); } for (int i = 0, j = mPlugins.size(); i < j; i++) mPlugins.get(i).render(); }
diff --git a/src/main/java/net/notdot/protorpc/ProtoRpcHandler.java b/src/main/java/net/notdot/protorpc/ProtoRpcHandler.java index 98b36c8..0943a88 100644 --- a/src/main/java/net/notdot/protorpc/ProtoRpcHandler.java +++ b/src/main/java/net/notdot/protorpc/ProtoRpcHandler.java @@ -1,108 +1,111 @@ package net.notdot.protorpc; import java.net.SocketAddress; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.channel.group.ChannelGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.RpcCallback; import com.google.protobuf.Service; import com.google.protobuf.Message; import com.google.protobuf.Descriptors.MethodDescriptor; @ChannelPipelineCoverage("one") public class ProtoRpcHandler extends SimpleChannelHandler { protected class ProtoRpcCallback implements RpcCallback<Message> { protected ProtoRpcController controller; protected ProtoRpcCallback(ProtoRpcController controller) { this.controller = controller; } public void run(Message arg0) { Rpc.Response response = Rpc.Response.newBuilder() .setRpcId(this.controller.getRpcId()) .setStatus(Rpc.Response.ResponseType.OK) .setBody(arg0.toByteString()).build(); this.controller.sendResponse(response); } } final Logger logger = LoggerFactory.getLogger(ProtoRpcHandler.class); protected Service service; protected ChannelGroup open_channels; @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { open_channels.add(e.getChannel()); logger.info("New connection from {}.", ctx.getChannel().getRemoteAddress()); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if(service instanceof Disposable) ((Disposable)service).close(); logger.info("Client {} disconnected.", ctx.getChannel().getRemoteAddress()); } public ProtoRpcHandler(Service s, ChannelGroup channels) { this.service = s; this.open_channels = channels; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Channel ch = e.getChannel(); SocketAddress remote_addr = ch.getRemoteAddress(); Rpc.Request request = (Rpc.Request) e.getMessage(); // For now we ignore the service name in the message. MethodDescriptor method = service.getDescriptorForType().findMethodByName(request.getMethod()); if(method == null) { ch.write(Rpc.Response.newBuilder().setStatus(Rpc.Response.ResponseType.CALL_NOT_FOUND).build()); return; } Message request_data; try { request_data = service.getRequestPrototype(method).newBuilderForType().mergeFrom(request.getBody()).build(); } catch(InvalidProtocolBufferException ex) { ch.write(Rpc.Response.newBuilder().setStatus(Rpc.Response.ResponseType.ARGUMENT_ERROR).build()); return; } logger.debug("Client {} RPC {} request data: {}", new Object[] { remote_addr, request.getRpcId(), request_data }); ProtoRpcController controller = new ProtoRpcController(ch, request.getService(), request.getMethod(), request.getRpcId()); ProtoRpcCallback callback = new ProtoRpcCallback(controller); try { service.callMethod(method, controller, request_data, callback); } catch(RpcFailedError ex) { if(ex.getCause() != null) { logger.error("Internal error: ", ex.getCause()); } controller.setFailed(ex.getMessage(), ex.getApplicationError()); + } catch(Throwable t) { + logger.error("Internal error: ", t); + controller.setFailed(t.getMessage()); } if(!controller.isResponseSent()) { controller.sendResponse(Rpc.Response.newBuilder() .setRpcId(request.getRpcId()) .setStatus(Rpc.Response.ResponseType.RPC_FAILED) .setErrorDetail("RPC handler failed to issue a response").build()); logger.error("Client {} RPC {} failed to return a response.", new Object[] { remote_addr, request.getRpcId() }); } } }
true
true
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Channel ch = e.getChannel(); SocketAddress remote_addr = ch.getRemoteAddress(); Rpc.Request request = (Rpc.Request) e.getMessage(); // For now we ignore the service name in the message. MethodDescriptor method = service.getDescriptorForType().findMethodByName(request.getMethod()); if(method == null) { ch.write(Rpc.Response.newBuilder().setStatus(Rpc.Response.ResponseType.CALL_NOT_FOUND).build()); return; } Message request_data; try { request_data = service.getRequestPrototype(method).newBuilderForType().mergeFrom(request.getBody()).build(); } catch(InvalidProtocolBufferException ex) { ch.write(Rpc.Response.newBuilder().setStatus(Rpc.Response.ResponseType.ARGUMENT_ERROR).build()); return; } logger.debug("Client {} RPC {} request data: {}", new Object[] { remote_addr, request.getRpcId(), request_data }); ProtoRpcController controller = new ProtoRpcController(ch, request.getService(), request.getMethod(), request.getRpcId()); ProtoRpcCallback callback = new ProtoRpcCallback(controller); try { service.callMethod(method, controller, request_data, callback); } catch(RpcFailedError ex) { if(ex.getCause() != null) { logger.error("Internal error: ", ex.getCause()); } controller.setFailed(ex.getMessage(), ex.getApplicationError()); } if(!controller.isResponseSent()) { controller.sendResponse(Rpc.Response.newBuilder() .setRpcId(request.getRpcId()) .setStatus(Rpc.Response.ResponseType.RPC_FAILED) .setErrorDetail("RPC handler failed to issue a response").build()); logger.error("Client {} RPC {} failed to return a response.", new Object[] { remote_addr, request.getRpcId() }); } }
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Channel ch = e.getChannel(); SocketAddress remote_addr = ch.getRemoteAddress(); Rpc.Request request = (Rpc.Request) e.getMessage(); // For now we ignore the service name in the message. MethodDescriptor method = service.getDescriptorForType().findMethodByName(request.getMethod()); if(method == null) { ch.write(Rpc.Response.newBuilder().setStatus(Rpc.Response.ResponseType.CALL_NOT_FOUND).build()); return; } Message request_data; try { request_data = service.getRequestPrototype(method).newBuilderForType().mergeFrom(request.getBody()).build(); } catch(InvalidProtocolBufferException ex) { ch.write(Rpc.Response.newBuilder().setStatus(Rpc.Response.ResponseType.ARGUMENT_ERROR).build()); return; } logger.debug("Client {} RPC {} request data: {}", new Object[] { remote_addr, request.getRpcId(), request_data }); ProtoRpcController controller = new ProtoRpcController(ch, request.getService(), request.getMethod(), request.getRpcId()); ProtoRpcCallback callback = new ProtoRpcCallback(controller); try { service.callMethod(method, controller, request_data, callback); } catch(RpcFailedError ex) { if(ex.getCause() != null) { logger.error("Internal error: ", ex.getCause()); } controller.setFailed(ex.getMessage(), ex.getApplicationError()); } catch(Throwable t) { logger.error("Internal error: ", t); controller.setFailed(t.getMessage()); } if(!controller.isResponseSent()) { controller.sendResponse(Rpc.Response.newBuilder() .setRpcId(request.getRpcId()) .setStatus(Rpc.Response.ResponseType.RPC_FAILED) .setErrorDetail("RPC handler failed to issue a response").build()); logger.error("Client {} RPC {} failed to return a response.", new Object[] { remote_addr, request.getRpcId() }); } }
diff --git a/src/main/java/de/lessvoid/nifty/renderer/lwjgl/render/font/Font.java b/src/main/java/de/lessvoid/nifty/renderer/lwjgl/render/font/Font.java index 8d6f18bd..e1447273 100644 --- a/src/main/java/de/lessvoid/nifty/renderer/lwjgl/render/font/Font.java +++ b/src/main/java/de/lessvoid/nifty/renderer/lwjgl/render/font/Font.java @@ -1,401 +1,404 @@ package de.lessvoid.nifty.renderer.lwjgl.render.font; import java.util.Hashtable; import java.util.Map; import org.lwjgl.opengl.GL11; import de.lessvoid.nifty.elements.tools.FontHelper; import de.lessvoid.nifty.renderer.lwjgl.render.LwjglRenderFont; import de.lessvoid.nifty.renderer.lwjgl.render.LwjglRenderImage; import de.lessvoid.nifty.renderer.lwjgl.render.font.ColorValueParser.Result; import de.lessvoid.nifty.spi.render.RenderDevice; import de.lessvoid.nifty.tools.Color; /** * OpenGL display list based Font. * @author void */ public class Font { /** * the font reader. */ private AngelCodeFont font; /** * display list id. */ private int listId; /** * textures. */ private LwjglRenderImage[] textures; private int selectionStart; private int selectionEnd; private float selectionBackgroundR; private float selectionBackgroundG; private float selectionBackgroundB; private float selectionBackgroundA; private float selectionR; private float selectionG; private float selectionB; private float selectionA; private Map<Character, Integer> displayListMap = new Hashtable<Character, Integer>(); private ColorValueParser colorValueParser = new ColorValueParser(); /** * construct the font. */ public Font(final RenderDevice device) { selectionStart = -1; selectionEnd = -1; selectionR = 1.0f; selectionG = 0.0f; selectionB = 0.0f; selectionA = 1.0f; selectionBackgroundR = 0.0f; selectionBackgroundG = 1.0f; selectionBackgroundB = 0.0f; selectionBackgroundA = 1.0f; } /** * has selection. * @return true or false */ private boolean isSelection() { return !(selectionStart == -1 && selectionEnd == -1); } /** * init the font with the given filename. * @param filename the filename * @return true, when success or false on error */ public final boolean init(final String filename) { // get the angel code font from file font = new AngelCodeFont(); if (!font.load(filename)) { return false; } // load textures of font into array textures = new LwjglRenderImage[font.getTextures().length]; for (int i = 0; i < font.getTextures().length; i++) { textures[i] = new LwjglRenderImage(extractPath(filename) + font.getTextures()[i], true); } // now build open gl display lists for every character in the font initDisplayList(); return true; } /** * extract the path from the given filename. * @param filename file * @return path */ private String extractPath(final String filename) { int idx = filename.lastIndexOf("/"); if (idx == -1) { return ""; } else { return filename.substring(0, idx) + "/"; } } /** * */ private void initDisplayList() { displayListMap.clear(); // create new list listId = GL11.glGenLists(font.getChars().size()); Tools.checkGLError("glGenLists"); // create the list int i = 0; for (Map.Entry<Character, CharacterInfo> entry : font.getChars().entrySet()) { displayListMap.put(entry.getKey(), listId + i); GL11.glNewList(listId + i, GL11.GL_COMPILE); Tools.checkGLError("glNewList"); CharacterInfo charInfo = entry.getValue(); if (charInfo != null) { GL11.glBegin( GL11.GL_QUADS ); Tools.checkGLError( "glBegin" ); float u0 = charInfo.getX() / (float)font.getWidth(); float v0 = charInfo.getY() / (float)font.getHeight(); float u1 = ( charInfo.getX() + charInfo.getWidth() ) / (float)font.getWidth(); float v1 = ( charInfo.getY() + charInfo.getHeight() ) / (float)font.getHeight(); GL11.glTexCoord2f( u0, v0 ); GL11.glVertex2f( charInfo.getXoffset(), charInfo.getYoffset() ); GL11.glTexCoord2f( u0, v1 ); GL11.glVertex2f( charInfo.getXoffset(), charInfo.getYoffset() + charInfo.getHeight() ); GL11.glTexCoord2f( u1, v1 ); GL11.glVertex2f( charInfo.getXoffset() + charInfo.getWidth(), charInfo.getYoffset() + charInfo.getHeight() ); GL11.glTexCoord2f( u1, v0 ); GL11.glVertex2f( charInfo.getXoffset() + charInfo.getWidth(), charInfo.getYoffset() ); GL11.glEnd(); Tools.checkGLError( "glEnd" ); } // end list GL11.glEndList(); Tools.checkGLError( "glEndList" ); i++; } } /** * * @param x * @param y * @param text */ public void drawString( int x, int y, String text ) { // enableBlend(); internalRenderText(x, y, text, 1.0f, false, 1.0f); // disableBlend(); } public void drawStringWithSize( int x, int y, String text, float size ) { // enableBlend(); internalRenderText(x, y, text, size, false, 1.0f); // disableBlend(); } public void renderWithSizeAndColor( int x, int y, String text, float size, float r, float g, float b, float a ) { // enableBlend(); GL11.glColor4f(r, g, b, a); internalRenderText( x, y, text, size, false, a); // disableBlend(); } /** * @param xPos x * @param yPos y * @param text text * @param size size * @param useAlphaTexture use alpha * @param a */ private void internalRenderText( final int xPos, final int yPos, final String text, final float size, final boolean useAlphaTexture, final float alpha) { GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); // GL11.glEnable(GL11.GL_TEXTURE_2D); int originalWidth = getStringWidthInternal(text, 1.0f); int sizedWidth = getStringWidthInternal(text, size); int x = xPos - (sizedWidth - originalWidth) / 2; int activeTextureIdx = -1; for (int i = 0; i < text.length(); i++) { Result result = colorValueParser.isColor(text, i); while (result.isColor()) { Color color = result.getColor(); GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), alpha); i = result.getNextIndex(); if (i >= text.length()) { break; } result = colorValueParser.isColor(text, i); } + if (i >= text.length()) { + break; + } char currentc = text.charAt(i); char nextc = FontHelper.getNextCharacter(text, i); CharacterInfo charInfoC = font.getChar((char) currentc); int kerning = 0; float characterWidth = 0; if (charInfoC != null) { int texId = charInfoC.getPage(); if (activeTextureIdx != texId) { activeTextureIdx = texId; textures[activeTextureIdx].bind(); } kerning = LwjglRenderFont.getKerning(charInfoC, nextc); characterWidth = (float) (charInfoC.getXadvance() * size + kerning); GL11.glLoadIdentity(); GL11.glTranslatef(x, yPos, 0.0f); GL11.glTranslatef(0.0f, getHeight() / 2, 0.0f); GL11.glScalef(size, size, 1.0f); GL11.glTranslatef(0.0f, -getHeight() / 2, 0.0f); boolean characterDone = false; if (isSelection()) { if (i >= selectionStart && i < selectionEnd) { GL11.glPushAttrib(GL11.GL_CURRENT_BIT); disableBlend(); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(selectionBackgroundR, selectionBackgroundG, selectionBackgroundB, selectionBackgroundA); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2i(0, 0); GL11.glVertex2i((int) characterWidth, 0); GL11.glVertex2i((int) characterWidth, 0 + getHeight()); GL11.glVertex2i(0, 0 + getHeight()); GL11.glEnd(); GL11.glEnable(GL11.GL_TEXTURE_2D); enableBlend(); GL11.glColor4f(selectionR, selectionG, selectionB, selectionA); GL11.glCallList(displayListMap.get(currentc)); Tools.checkGLError("glCallList"); GL11.glPopAttrib(); characterDone = true; } } if (!characterDone) { GL11.glCallList(displayListMap.get(currentc)); Tools.checkGLError("glCallList"); } x += characterWidth; } } GL11.glPopMatrix(); } /** * */ private void disableBlend() { GL11.glDisable( GL11.GL_BLEND ); } /** * */ private void enableBlend() { GL11.glEnable( GL11.GL_BLEND ); GL11.glBlendFunc( GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA ); } public int getStringWidth( String text ) { return getStringWidthInternal( text, 1.0f ); } /** * @param text text * @param size size * @return length */ private int getStringWidthInternal(final String text, final float size) { int length = 0; for (int i=0; i<text.length(); i++) { Result result = colorValueParser.isColor(text, i); if (result.isColor()) { i = result.getNextIndex(); if (i >= text.length()) { break; } } char currentCharacter = text.charAt(i); char nextCharacter = FontHelper.getNextCharacter(text, i); Integer w = getCharacterWidth(currentCharacter, nextCharacter, size); if (w != null) { length += w; } } return length; } public int getHeight() { return font.getLineHeight(); } public void setSelectionStart(int selectionStart) { this.selectionStart = selectionStart; } public void setSelectionEnd(int selectionEnd) { this.selectionEnd = selectionEnd; } public void setSelectionColor(final float selectionR, final float selectionG, final float selectionB, final float selectionA) { this.selectionR = selectionR; this.selectionG = selectionG; this.selectionB = selectionB; this.selectionA = selectionA; } public void setSelectionBackgroundColor(final float selectionR, final float selectionG, final float selectionB, final float selectionA) { this.selectionBackgroundR = selectionR; this.selectionBackgroundG = selectionG; this.selectionBackgroundB = selectionB; this.selectionBackgroundA = selectionA; } /** * get character information. * @param character char * @return CharacterInfo */ public CharacterInfo getChar(final char character) { return font.getChar(character); } /** * Return the width of the given character including kerning information. * @param currentCharacter current character * @param nextCharacter next character * @param size font size * @return width of the character or null when no information for the character is available */ public Integer getCharacterWidth(final char currentCharacter, final char nextCharacter, final float size) { CharacterInfo currentCharacterInfo = font.getChar(currentCharacter); if (currentCharacterInfo == null) { return null; } else { return new Integer((int)(currentCharacterInfo.getXadvance() * size + getKerning(currentCharacterInfo, nextCharacter))); } } /** * @param charInfoC * @param nextc * @return */ public static int getKerning(final CharacterInfo charInfoC, final char nextc) { Integer kern = charInfoC.getKerning().get(Character.valueOf(nextc)); if (kern != null) { return kern.intValue(); } return 0; } }
true
true
private void internalRenderText( final int xPos, final int yPos, final String text, final float size, final boolean useAlphaTexture, final float alpha) { GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); // GL11.glEnable(GL11.GL_TEXTURE_2D); int originalWidth = getStringWidthInternal(text, 1.0f); int sizedWidth = getStringWidthInternal(text, size); int x = xPos - (sizedWidth - originalWidth) / 2; int activeTextureIdx = -1; for (int i = 0; i < text.length(); i++) { Result result = colorValueParser.isColor(text, i); while (result.isColor()) { Color color = result.getColor(); GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), alpha); i = result.getNextIndex(); if (i >= text.length()) { break; } result = colorValueParser.isColor(text, i); } char currentc = text.charAt(i); char nextc = FontHelper.getNextCharacter(text, i); CharacterInfo charInfoC = font.getChar((char) currentc); int kerning = 0; float characterWidth = 0; if (charInfoC != null) { int texId = charInfoC.getPage(); if (activeTextureIdx != texId) { activeTextureIdx = texId; textures[activeTextureIdx].bind(); } kerning = LwjglRenderFont.getKerning(charInfoC, nextc); characterWidth = (float) (charInfoC.getXadvance() * size + kerning); GL11.glLoadIdentity(); GL11.glTranslatef(x, yPos, 0.0f); GL11.glTranslatef(0.0f, getHeight() / 2, 0.0f); GL11.glScalef(size, size, 1.0f); GL11.glTranslatef(0.0f, -getHeight() / 2, 0.0f); boolean characterDone = false; if (isSelection()) { if (i >= selectionStart && i < selectionEnd) { GL11.glPushAttrib(GL11.GL_CURRENT_BIT); disableBlend(); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(selectionBackgroundR, selectionBackgroundG, selectionBackgroundB, selectionBackgroundA); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2i(0, 0); GL11.glVertex2i((int) characterWidth, 0); GL11.glVertex2i((int) characterWidth, 0 + getHeight()); GL11.glVertex2i(0, 0 + getHeight()); GL11.glEnd(); GL11.glEnable(GL11.GL_TEXTURE_2D); enableBlend(); GL11.glColor4f(selectionR, selectionG, selectionB, selectionA); GL11.glCallList(displayListMap.get(currentc)); Tools.checkGLError("glCallList"); GL11.glPopAttrib(); characterDone = true; } } if (!characterDone) { GL11.glCallList(displayListMap.get(currentc)); Tools.checkGLError("glCallList"); } x += characterWidth; } } GL11.glPopMatrix(); }
private void internalRenderText( final int xPos, final int yPos, final String text, final float size, final boolean useAlphaTexture, final float alpha) { GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); GL11.glLoadIdentity(); // GL11.glEnable(GL11.GL_TEXTURE_2D); int originalWidth = getStringWidthInternal(text, 1.0f); int sizedWidth = getStringWidthInternal(text, size); int x = xPos - (sizedWidth - originalWidth) / 2; int activeTextureIdx = -1; for (int i = 0; i < text.length(); i++) { Result result = colorValueParser.isColor(text, i); while (result.isColor()) { Color color = result.getColor(); GL11.glColor4f(color.getRed(), color.getGreen(), color.getBlue(), alpha); i = result.getNextIndex(); if (i >= text.length()) { break; } result = colorValueParser.isColor(text, i); } if (i >= text.length()) { break; } char currentc = text.charAt(i); char nextc = FontHelper.getNextCharacter(text, i); CharacterInfo charInfoC = font.getChar((char) currentc); int kerning = 0; float characterWidth = 0; if (charInfoC != null) { int texId = charInfoC.getPage(); if (activeTextureIdx != texId) { activeTextureIdx = texId; textures[activeTextureIdx].bind(); } kerning = LwjglRenderFont.getKerning(charInfoC, nextc); characterWidth = (float) (charInfoC.getXadvance() * size + kerning); GL11.glLoadIdentity(); GL11.glTranslatef(x, yPos, 0.0f); GL11.glTranslatef(0.0f, getHeight() / 2, 0.0f); GL11.glScalef(size, size, 1.0f); GL11.glTranslatef(0.0f, -getHeight() / 2, 0.0f); boolean characterDone = false; if (isSelection()) { if (i >= selectionStart && i < selectionEnd) { GL11.glPushAttrib(GL11.GL_CURRENT_BIT); disableBlend(); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(selectionBackgroundR, selectionBackgroundG, selectionBackgroundB, selectionBackgroundA); GL11.glBegin(GL11.GL_QUADS); GL11.glVertex2i(0, 0); GL11.glVertex2i((int) characterWidth, 0); GL11.glVertex2i((int) characterWidth, 0 + getHeight()); GL11.glVertex2i(0, 0 + getHeight()); GL11.glEnd(); GL11.glEnable(GL11.GL_TEXTURE_2D); enableBlend(); GL11.glColor4f(selectionR, selectionG, selectionB, selectionA); GL11.glCallList(displayListMap.get(currentc)); Tools.checkGLError("glCallList"); GL11.glPopAttrib(); characterDone = true; } } if (!characterDone) { GL11.glCallList(displayListMap.get(currentc)); Tools.checkGLError("glCallList"); } x += characterWidth; } } GL11.glPopMatrix(); }
diff --git a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/actions/ActionDescriptor.java b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/actions/ActionDescriptor.java index ec54f51d..714a062e 100644 --- a/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/actions/ActionDescriptor.java +++ b/nuxeo-webengine-core/src/main/java/org/nuxeo/ecm/webengine/actions/ActionDescriptor.java @@ -1,213 +1,213 @@ /* * (C) Copyright 2006-2008 Nuxeo SAS (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * Contributors: * bstefanescu * * $Id$ */ package org.nuxeo.ecm.webengine.actions; import java.text.ParseException; import org.nuxeo.common.xmap.annotation.XNode; import org.nuxeo.common.xmap.annotation.XNodeList; import org.nuxeo.common.xmap.annotation.XObject; import org.nuxeo.ecm.webengine.WebException; import org.nuxeo.ecm.webengine.WebObject; import org.nuxeo.ecm.webengine.exceptions.WebSecurityException; import org.nuxeo.ecm.webengine.security.Guard; import org.nuxeo.ecm.webengine.security.GuardDescriptor; /** * @author <a href="mailto:[email protected]">Bogdan Stefanescu</a> * */ @XObject("action") public class ActionDescriptor { public static final String[] EMPTY_CATEGORIES = new String[0]; @XNode("@id") protected String id; @XNode("@script") protected String script; @XNode("@handler") protected Class<ActionHandler> handlerClass; @XNode("@enabled") protected boolean isEnabled = true; @XNode("permission") private GuardDescriptor pd; @XNodeList(value = "category", type = String[].class, componentType = String.class) protected String[] categories = EMPTY_CATEGORIES; protected Guard guard; protected ActionHandler handler; public ActionDescriptor() { } public ActionDescriptor(String id, String path, Class<ActionHandler> handler, Guard guard) { this.id = id; script = path; handlerClass = handler; this.guard = guard; } public void setEnabled(boolean isEnabled) { this.isEnabled = isEnabled; } public boolean isEnabled() { return isEnabled; } public boolean isEnabled(WebObject obj) { if (!isEnabled) { return false; } return getGuard().check(obj.getWebContext()); } public String getId() { return id; } public Class<ActionHandler> getHandlerClass() { return handlerClass; } public void setHandlerClass(Class<ActionHandler> handlerClass) { this.handlerClass = handlerClass; } public String getScript() { return script; } public void setScript(String script) { this.script = script; } public Guard getGuard() { if (guard == null) { buildGuard(); } return guard; } public void setGuard(Guard guard) { this.guard = guard; } public void setCategories(String ... categories) { this.categories = categories; } public String[] getCategories() { return categories; } public boolean hasCategory(String name) { for (int i = categories.length-1; i>=0; i--) { if (name.equals(categories[i])) { return true; } } return false; } public ActionHandler getHandler() throws WebException { if (handler == null) { if (handlerClass == null) { handler = ActionHandler.NULL; } else { try { handler = handlerClass.newInstance(); } catch (Exception e) { throw new WebException("Failed to instantiate action handler for action: "+id, e); } } } return handler; } /** * This method should be used to run actions. * Avoid using getHandler().run() since it is not checking permissions */ public void run(WebObject obj) throws WebException { // check rights first if (!getGuard().check(obj.getWebContext())) { throw new WebSecurityException(id); } getHandler().run(obj); } public void setHandler(ActionHandler handler) { this.handler = handler; } public void copyFrom(ActionDescriptor ad) { id = ad.id; isEnabled = ad.isEnabled; if (ad.categories != null && ad.categories.length > 0) { if (categories == null) { categories = ad.categories; } else { String[] tmp = new String[categories.length+ad.categories.length]; System.arraycopy(categories, 0, tmp, 0, categories.length); System.arraycopy(ad.categories, 0, tmp, categories.length, ad.categories.length); categories = tmp; } } - if (script == null) { + if (ad.script != null) { script = ad.script; } - if (handlerClass == null) { + if (ad.handlerClass != null) { handlerClass = ad.handlerClass; } - if (pd == null) { + if (ad.getGuard() != null) { guard = ad.getGuard(); } else { pd.getGuards().put(".", ad.getGuard()); guard = null; } } private void buildGuard() { if (pd == null) { guard = Guard.DEFAULT; } else { try { guard = pd.getGuard(); // compute guards now } catch (ParseException e) { e.printStackTrace(); // TODO } } } @Override public String toString() { return id; } }
false
true
public void copyFrom(ActionDescriptor ad) { id = ad.id; isEnabled = ad.isEnabled; if (ad.categories != null && ad.categories.length > 0) { if (categories == null) { categories = ad.categories; } else { String[] tmp = new String[categories.length+ad.categories.length]; System.arraycopy(categories, 0, tmp, 0, categories.length); System.arraycopy(ad.categories, 0, tmp, categories.length, ad.categories.length); categories = tmp; } } if (script == null) { script = ad.script; } if (handlerClass == null) { handlerClass = ad.handlerClass; } if (pd == null) { guard = ad.getGuard(); } else { pd.getGuards().put(".", ad.getGuard()); guard = null; } }
public void copyFrom(ActionDescriptor ad) { id = ad.id; isEnabled = ad.isEnabled; if (ad.categories != null && ad.categories.length > 0) { if (categories == null) { categories = ad.categories; } else { String[] tmp = new String[categories.length+ad.categories.length]; System.arraycopy(categories, 0, tmp, 0, categories.length); System.arraycopy(ad.categories, 0, tmp, categories.length, ad.categories.length); categories = tmp; } } if (ad.script != null) { script = ad.script; } if (ad.handlerClass != null) { handlerClass = ad.handlerClass; } if (ad.getGuard() != null) { guard = ad.getGuard(); } else { pd.getGuards().put(".", ad.getGuard()); guard = null; } }
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/stats/IndicesStats.java b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/stats/IndicesStats.java index 624bf144a73..66809ea406d 100644 --- a/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/stats/IndicesStats.java +++ b/modules/elasticsearch/src/main/java/org/elasticsearch/action/admin/indices/stats/IndicesStats.java @@ -1,217 +1,217 @@ /* * Licensed to Elastic Search and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Elastic Search licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.action.admin.indices.stats; import org.elasticsearch.action.ShardOperationFailedException; import org.elasticsearch.action.support.broadcast.BroadcastOperationResponse; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.collect.Lists; import org.elasticsearch.common.collect.Maps; import org.elasticsearch.common.collect.Sets; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilderString; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; /** */ public class IndicesStats extends BroadcastOperationResponse implements ToXContent { private ShardStats[] shards; IndicesStats() { } IndicesStats(ShardStats[] shards, ClusterState clusterState, int totalShards, int successfulShards, int failedShards, List<ShardOperationFailedException> shardFailures) { super(totalShards, successfulShards, failedShards, shardFailures); this.shards = shards; } public ShardStats[] shards() { return this.shards; } public ShardStats[] getShards() { return this.shards; } public ShardStats getAt(int position) { return shards[position]; } public IndexStats index(String index) { return indices().get(index); } public Map<String, IndexStats> getIndices() { return indices(); } private Map<String, IndexStats> indicesStats; public Map<String, IndexStats> indices() { if (indicesStats != null) { return indicesStats; } Map<String, IndexStats> indicesStats = Maps.newHashMap(); Set<String> indices = Sets.newHashSet(); for (ShardStats shard : shards) { indices.add(shard.index()); } for (String index : indices) { List<ShardStats> shards = Lists.newArrayList(); for (ShardStats shard : this.shards) { if (shard.shardRouting().index().equals(index)) { shards.add(shard); } } indicesStats.put(index, new IndexStats(index, shards.toArray(new ShardStats[shards.size()]))); } this.indicesStats = indicesStats; return indicesStats; } private CommonStats total = null; public CommonStats getTotal() { return total(); } public CommonStats total() { if (total != null) { return total; } CommonStats stats = new CommonStats(); for (ShardStats shard : shards) { stats.add(shard.stats()); } total = stats; return stats; } private CommonStats primary = null; public CommonStats getPrimaries() { return primaries(); } public CommonStats primaries() { if (primary != null) { return primary; } CommonStats stats = new CommonStats(); for (ShardStats shard : shards) { if (shard.shardRouting().primary()) { stats.add(shard.stats()); } } primary = stats; return stats; } @Override public void readFrom(StreamInput in) throws IOException { super.readFrom(in); shards = new ShardStats[in.readVInt()]; for (int i = 0; i < shards.length; i++) { shards[i] = ShardStats.readShardStats(in); } } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeVInt(shards.length); for (ShardStats shard : shards) { shard.writeTo(out); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject("_all"); builder.startObject("primaries"); primaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); - primaries().toXContent(builder, params); + total().toXContent(builder, params); builder.endObject(); builder.startObject(Fields.INDICES); for (IndexStats indexStats : indices().values()) { builder.startObject(indexStats.index(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("primaries"); indexStats.primaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); indexStats.total().toXContent(builder, params); builder.endObject(); if ("shards".equalsIgnoreCase(params.param("level", null))) { builder.startObject(Fields.SHARDS); for (IndexShardStats indexShardStats : indexStats) { builder.startArray(Integer.toString(indexShardStats.shardId().id())); for (ShardStats shardStats : indexShardStats) { builder.startObject(); builder.startObject(Fields.ROUTING) .field(Fields.STATE, shardStats.shardRouting().state()) .field(Fields.PRIMARY, shardStats.shardRouting().primary()) .field(Fields.NODE, shardStats.shardRouting().currentNodeId()) .field(Fields.RELOCATING_NODE, shardStats.shardRouting().relocatingNodeId()) .endObject(); shardStats.stats().toXContent(builder, params); builder.endObject(); } builder.endArray(); } builder.endObject(); } builder.endObject(); } builder.endObject(); builder.endObject(); return builder; } static final class Fields { static final XContentBuilderString INDICES = new XContentBuilderString("indices"); static final XContentBuilderString SHARDS = new XContentBuilderString("shards"); static final XContentBuilderString ROUTING = new XContentBuilderString("routing"); static final XContentBuilderString STATE = new XContentBuilderString("state"); static final XContentBuilderString PRIMARY = new XContentBuilderString("primary"); static final XContentBuilderString NODE = new XContentBuilderString("node"); static final XContentBuilderString RELOCATING_NODE = new XContentBuilderString("relocating_node"); } }
true
true
@Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject("_all"); builder.startObject("primaries"); primaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); primaries().toXContent(builder, params); builder.endObject(); builder.startObject(Fields.INDICES); for (IndexStats indexStats : indices().values()) { builder.startObject(indexStats.index(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("primaries"); indexStats.primaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); indexStats.total().toXContent(builder, params); builder.endObject(); if ("shards".equalsIgnoreCase(params.param("level", null))) { builder.startObject(Fields.SHARDS); for (IndexShardStats indexShardStats : indexStats) { builder.startArray(Integer.toString(indexShardStats.shardId().id())); for (ShardStats shardStats : indexShardStats) { builder.startObject(); builder.startObject(Fields.ROUTING) .field(Fields.STATE, shardStats.shardRouting().state()) .field(Fields.PRIMARY, shardStats.shardRouting().primary()) .field(Fields.NODE, shardStats.shardRouting().currentNodeId()) .field(Fields.RELOCATING_NODE, shardStats.shardRouting().relocatingNodeId()) .endObject(); shardStats.stats().toXContent(builder, params); builder.endObject(); } builder.endArray(); } builder.endObject(); } builder.endObject(); } builder.endObject(); builder.endObject(); return builder; }
@Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject("_all"); builder.startObject("primaries"); primaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); total().toXContent(builder, params); builder.endObject(); builder.startObject(Fields.INDICES); for (IndexStats indexStats : indices().values()) { builder.startObject(indexStats.index(), XContentBuilder.FieldCaseConversion.NONE); builder.startObject("primaries"); indexStats.primaries().toXContent(builder, params); builder.endObject(); builder.startObject("total"); indexStats.total().toXContent(builder, params); builder.endObject(); if ("shards".equalsIgnoreCase(params.param("level", null))) { builder.startObject(Fields.SHARDS); for (IndexShardStats indexShardStats : indexStats) { builder.startArray(Integer.toString(indexShardStats.shardId().id())); for (ShardStats shardStats : indexShardStats) { builder.startObject(); builder.startObject(Fields.ROUTING) .field(Fields.STATE, shardStats.shardRouting().state()) .field(Fields.PRIMARY, shardStats.shardRouting().primary()) .field(Fields.NODE, shardStats.shardRouting().currentNodeId()) .field(Fields.RELOCATING_NODE, shardStats.shardRouting().relocatingNodeId()) .endObject(); shardStats.stats().toXContent(builder, params); builder.endObject(); } builder.endArray(); } builder.endObject(); } builder.endObject(); } builder.endObject(); builder.endObject(); return builder; }
diff --git a/phone-app/src/com/peoples/android/database/PeoplesDB.java b/phone-app/src/com/peoples/android/database/PeoplesDB.java index 105350b..08ba2dd 100644 --- a/phone-app/src/com/peoples/android/database/PeoplesDB.java +++ b/phone-app/src/com/peoples/android/database/PeoplesDB.java @@ -1,438 +1,438 @@ /*---------------------------------------------------------------------------* * PeoplesDB.java * * * * Contains information about the set up of the PEOPLES SQLite database and * * methods to create and update that database. * *---------------------------------------------------------------------------*/ package com.peoples.android.database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.util.Log; /** * Represents the SQLite database to hold information for the app. Contains * functions to create and upgrade the database, as well as public fields that * contain the names of the tables and columns. When another class needs to use * the database, they should use these constants. Subclasses represent the * various tables. Each implements BaseColumns by having a unique id field. * * @see BaseColumns * @see GPSTable * @see CallLogTable * @see AnswerTable * @see BranchTable * @see ChoiceTable * @see ConditionTable * @see QuestionTable * @see SurveyTable * @see ScheduledSurveys * * @author Diego Vargas * @author Vladimir Costescu */ public class PeoplesDB extends SQLiteOpenHelper { private static final String TAG = "PeoplesDB"; private static final boolean D = true; //Change the version number here to force the database to //update itself. This throws out all data. private static final String DATABASE_NAME = "peoples.db"; private static final int DATABASE_VERSION = 5; //table names public static final String GPS_TABLE_NAME = "gps"; public static final String CALLLOG_TABLE_NAME = "calllog"; public static final String ANSWER_TABLE_NAME = "answers"; public static final String BRANCH_TABLE_NAME = "branches"; public static final String CHOICE_TABLE_NAME = "choices"; public static final String CONDITION_TABLE_NAME = "conditions"; public static final String QUESTION_TABLE_NAME = "questions"; public static final String SURVEY_TABLE_NAME = "surveys"; public static final String SS_TABLE_NAME = "scheduled_surveys"; //needed for creating the call log private Context context; /** * Location data table. Contains longitude, latitude, uploaded (to mark * whether or not each record has been sent to the web server), and time. * * @author Diego Vargas * @author Vladimir Costescu */ public static final class GPSTable implements BaseColumns { // This class cannot be instantiated private GPSTable() {} public static final String DEFAULT_SORT_ORDER = "modified DESC"; public static final String LONGITUDE = "longitude"; public static final String LATITUDE = "latitude"; public static final String TIME = "time"; public static final String UPLOADED = "uploaded"; private static String createSql() { return "CREATE TABLE " + GPS_TABLE_NAME + " (" + GPSTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + GPSTable.LONGITUDE + " DOUBLE," + GPSTable.LATITUDE + " DOUBLE," + GPSTable.TIME + " INTEGER," + GPSTable.UPLOADED + " INT UNSIGNED DEFAULT 0" + " );"; } } /** * Call log data table. Contains phone number, duration, uploaded (to mark * whether or not each record has been sent to the web server), call type, * and time (the time the call was made). * * @author Diego Vargas * @author Vladimir Costescu */ public static final class CallLogTable implements BaseColumns { // This class cannot be instantiated private CallLogTable() {} public static final String DEFAULT_SORT_ORDER = "modified DESC"; public static final String PHONE_NUMBER = "phone_number"; public static final String CALL_TYPE = "call_type"; public static final String DURATION = "duration"; public static final String TIME = "time"; public static final String UPLOADED = "uploaded"; // Given an integer call type, return a string representation public static String getCallTypeString(int callType) { String stringCallType; switch (callType) { case android.provider.CallLog.Calls.INCOMING_TYPE: stringCallType = "Incoming"; break; case android.provider.CallLog.Calls.MISSED_TYPE: stringCallType = "Missed"; break; case android.provider.CallLog.Calls.OUTGOING_TYPE: stringCallType = "Outgoing"; break; default: stringCallType = ""; break; } return stringCallType; } private static String createSql() { return "CREATE TABLE " + CALLLOG_TABLE_NAME + " (" + CallLogTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + CallLogTable.PHONE_NUMBER + " TEXT," + CallLogTable.CALL_TYPE + " TEXT," + CallLogTable.DURATION + " INTEGER," + CallLogTable.TIME + " TEXT," + "uploaded INT UNSIGNED DEFAULT 0)"; } } /** * Survey answers table. Tracks what the phone user (subject) has answered * the administered surveys with. Contains a question id, a created time, * uploaded (to mark whether each answer has been sent to the server), and * either a choice id or and answer text depending on the type of question. * * @see com.peoples.android.model.Answer * * @author Diego Vargas * @author Vladimir Costescu */ public static final class AnswerTable implements BaseColumns { public static final String QUESTION_ID = "question_id"; public static final String CHOICE_ID = "choice_id"; public static final String ANS_TEXT = "ans_text"; public static final String CREATED = "created"; public static final String UPLOADED = "uploaded"; private static String createSql() { return "CREATE TABLE answers (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + "question_id INT UNSIGNED NOT NULL," + "choice_id INT UNSIGNED," + "ans_text TEXT," + "uploaded INT UNSIGNED DEFAULT 0," + "created DATETIME);"; } } /** * Survey Branches table. Contains a question id (the question a * branch belongs to), and a next question (the id of the question a * branch points to). * * @see com.peoples.android.model.Branch * * @author Diego Vargas * @author Vladimir Costescu */ public static final class BranchTable implements BaseColumns { public static final String QUESTION_ID = "question_id"; public static final String NEXT_Q = "next_q"; private static String createSql() { return "CREATE TABLE branches (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + "question_id INT UNSIGNED NOT NULL, " + "next_q INT UNSIGNED NOT NULL);"; } } /** * Survey Choices table. Contains the choice text and the question id that * each Choice belongs to. * * @see com.peoples.android.model.Choice * * @author Diego Vargas * @author Vladimir Costescu */ public static final class ChoiceTable implements BaseColumns { public static final String CHOICE_TEXT = "choice_text"; public static final String QUESTION_ID = "question_id"; private static String createSql() { return "CREATE TABLE choices (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + "choice_text VARCHAR(255)," + "question_id INT UNSIGNED);"; } } /** * Survey Conditions table. Contains the branch id that each Condition * belongs to, the question id that each Condition should check, the * choice id that that Question should be answered with, and the type of * check to do. * * @see com.peoples.android.model.Condition * * @author Diego Vargas * @author Vladimir Costescu */ public static final class ConditionTable implements BaseColumns { public static final String BRANCH_ID = "branch_id"; public static final String QUESTION_ID = "question_id"; public static final String CHOICE_ID = "choice_id"; public static final String TYPE = "type"; private static String createSql() { return "CREATE TABLE conditions (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + "branch_id INT UNSIGNED NOT NULL, " + "question_id INT UNSIGNED NOT NULL, " + "choice_id INT UNSIGNED NOT NULL, " + "type TINYINT UNSIGNED NOT NULL);"; } } /** * Survey Questions table. Contains the survey id each Questionbelongs * to and the text of each question. * * @see com.peoples.android.model.Question * * @author Diego Vargas * @author Vladimir Costescu */ public static final class QuestionTable implements BaseColumns { public static final String SURVEY_ID = "survey_id"; public static final String Q_TEXT = "q_text"; private static String createSql() { return "CREATE TABLE questions (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + "survey_id INT UNSIGNED NOT NULL," + "q_text TEXT);"; } } /** * Surveys table. Contains the survey name, its creation date/time, the * first Questions id, and 7 fields to hold a list of times as 4 digit, * comma separated integers that correspond to the times of the day that * each Survey should be given on each day of the week. * * @see come.peoples.android.model.Survey * * @author Diego Vargas * @author Vladimir Costescu */ public static final class SurveyTable implements BaseColumns { public static final String NAME = "name"; public static final String CREATED = "created"; public static final String QUESTION_ID = "question_id"; public static final String MO = "mo"; public static final String TU = "tu"; public static final String WE = "we"; public static final String TH = "th"; public static final String FR = "fr"; public static final String SA = "sa"; public static final String SU = "su"; private static String createSql() { return "CREATE TABLE surveys (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + "name VARCHAR(255),created DATETIME," + "question_id INT UNSIGNED NOT NULL," + "mo VARCHAR(255)," + "tu VARCHAR(255)," + "we VARCHAR(255)," + "th VARCHAR(255)," + "fr VARCHAR(255)," + "sa VARCHAR(255)," + "su VARCHAR(255));"; } } /** * Table tracking surveys that were scheduled to happen but were rejected * by the phone user to be asked at a later time. Contains the surveys id, * the time it was originally supposed to be complete, and how many times * it has been skipped. * * @author Diego Vargas */ public static final class ScheduledSurveys implements BaseColumns { public static final String SURVEY_ID = "survey_id"; public static final String ORIGINAL_TIME = "original_time"; public static final String SKIPPED = "survey_skipped"; private static String createSql() { return "CREATE TABLE " + SS_TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SURVEY_ID + " INT UNSIGNED NOT NULL, " + ORIGINAL_TIME + " LONG UNSIGNED NOT NULL, " + SKIPPED + " BOOLEAN NOT NULL);"; } } @Override public void onCreate(SQLiteDatabase db) { AnswerTable.createSql(); Log.d(TAG, "onCreate"); db.beginTransaction(); try { db.execSQL(GPSTable.createSql()); db.execSQL(CallLogTable.createSql()); db.execSQL(AnswerTable.createSql()); db.execSQL(BranchTable.createSql()); db.execSQL(ChoiceTable.createSql()); db.execSQL(ConditionTable.createSql()); db.execSQL(QuestionTable.createSql()); db.execSQL(SurveyTable.createSql()); db.execSQL(ScheduledSurveys.createSql()); buildInitialCallLog(db); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + GPS_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + CALLLOG_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + ANSWER_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + BRANCH_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + CHOICE_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + CONDITION_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + QUESTION_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + SURVEY_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + SS_TABLE_NAME); onCreate(db); } //check the phone's call records and copy them into the PEOPLES database private void buildInitialCallLog(SQLiteDatabase db) { Cursor c = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, - android.provider.CallLog.Calls.DATE + " DESC"); + android.provider.CallLog.Calls.DATE); // Retrieve the column-indices of phoneNumber, date and calltype int numberColumn = c.getColumnIndex(android.provider.CallLog.Calls.NUMBER); int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE); // type can be: Incoming, Outgoing or Missed int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE); // Loop through all entries the cursor provides to us. if (c.moveToFirst()) { do { String callerPhoneNumber = c.getString(numberColumn); - int callDate = c.getInt(dateColumn); + String callDate = c.getString(dateColumn); int callType = c.getInt(typeColumn); String stringCallType; ContentValues call = new ContentValues(); stringCallType = CallLogTable.getCallTypeString(callType); call.put(CallLogTable.PHONE_NUMBER, callerPhoneNumber); call.put(CallLogTable.CALL_TYPE, stringCallType); call.put(CallLogTable.TIME, callDate); db.insert(CALLLOG_TABLE_NAME, null, call); } while (c.moveToNext()); } c.close(); } /** * Create the database object. * * @param context - Android Context; needed to create the call log */ public PeoplesDB(Context context){ super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; Log.d(TAG, "in constructor"); } //for debugging; want to be able to print out when database is accessed @Override public synchronized SQLiteDatabase getReadableDatabase() { if(D) Log.d(TAG, "getReadable"); return super.getReadableDatabase(); } @Override public synchronized SQLiteDatabase getWritableDatabase() { if(D) Log.d(TAG, "getWriteable"); return super.getWritableDatabase(); } }
false
true
private void buildInitialCallLog(SQLiteDatabase db) { Cursor c = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, android.provider.CallLog.Calls.DATE + " DESC"); // Retrieve the column-indices of phoneNumber, date and calltype int numberColumn = c.getColumnIndex(android.provider.CallLog.Calls.NUMBER); int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE); // type can be: Incoming, Outgoing or Missed int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE); // Loop through all entries the cursor provides to us. if (c.moveToFirst()) { do { String callerPhoneNumber = c.getString(numberColumn); int callDate = c.getInt(dateColumn); int callType = c.getInt(typeColumn); String stringCallType; ContentValues call = new ContentValues(); stringCallType = CallLogTable.getCallTypeString(callType); call.put(CallLogTable.PHONE_NUMBER, callerPhoneNumber); call.put(CallLogTable.CALL_TYPE, stringCallType); call.put(CallLogTable.TIME, callDate); db.insert(CALLLOG_TABLE_NAME, null, call); } while (c.moveToNext()); } c.close(); }
private void buildInitialCallLog(SQLiteDatabase db) { Cursor c = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, android.provider.CallLog.Calls.DATE); // Retrieve the column-indices of phoneNumber, date and calltype int numberColumn = c.getColumnIndex(android.provider.CallLog.Calls.NUMBER); int dateColumn = c.getColumnIndex(android.provider.CallLog.Calls.DATE); // type can be: Incoming, Outgoing or Missed int typeColumn = c.getColumnIndex(android.provider.CallLog.Calls.TYPE); // Loop through all entries the cursor provides to us. if (c.moveToFirst()) { do { String callerPhoneNumber = c.getString(numberColumn); String callDate = c.getString(dateColumn); int callType = c.getInt(typeColumn); String stringCallType; ContentValues call = new ContentValues(); stringCallType = CallLogTable.getCallTypeString(callType); call.put(CallLogTable.PHONE_NUMBER, callerPhoneNumber); call.put(CallLogTable.CALL_TYPE, stringCallType); call.put(CallLogTable.TIME, callDate); db.insert(CALLLOG_TABLE_NAME, null, call); } while (c.moveToNext()); } c.close(); }
diff --git a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java index a236c7465..6a5ee06af 100755 --- a/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java +++ b/src/java/org/infoglue/cms/controllers/kernel/impl/simple/ContentController.java @@ -1,2389 +1,2389 @@ /* =============================================================================== * * Part of the InfoGlue Content Management Platform (www.infoglue.org) * * =============================================================================== * * Copyright (C) * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2, as published by the * Free Software Foundation. See the file LICENSE.html for more information. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple * Place, Suite 330 / Boston, MA 02111-1307 / USA. * * =============================================================================== */ package org.infoglue.cms.controllers.kernel.impl.simple; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.exolab.castor.jdo.Database; import org.exolab.castor.jdo.OQLQuery; import org.exolab.castor.jdo.ObjectNotFoundException; import org.exolab.castor.jdo.QueryResults; import org.infoglue.cms.applications.contenttool.wizards.actions.CreateContentWizardInfoBean; import org.infoglue.cms.entities.content.Content; import org.infoglue.cms.entities.content.ContentVO; import org.infoglue.cms.entities.content.ContentVersion; import org.infoglue.cms.entities.content.ContentVersionVO; import org.infoglue.cms.entities.content.impl.simple.ContentImpl; import org.infoglue.cms.entities.content.impl.simple.MediumContentImpl; import org.infoglue.cms.entities.content.impl.simple.SmallContentImpl; import org.infoglue.cms.entities.content.impl.simple.SmallestContentVersionImpl; import org.infoglue.cms.entities.kernel.BaseEntityVO; import org.infoglue.cms.entities.management.ContentTypeDefinition; import org.infoglue.cms.entities.management.ContentTypeDefinitionVO; import org.infoglue.cms.entities.management.LanguageVO; import org.infoglue.cms.entities.management.Repository; import org.infoglue.cms.entities.management.RepositoryLanguage; import org.infoglue.cms.entities.management.RepositoryVO; import org.infoglue.cms.entities.management.ServiceDefinition; import org.infoglue.cms.entities.management.ServiceDefinitionVO; import org.infoglue.cms.entities.management.impl.simple.ContentTypeDefinitionImpl; import org.infoglue.cms.entities.management.impl.simple.RepositoryImpl; import org.infoglue.cms.entities.structure.Qualifyer; import org.infoglue.cms.entities.structure.ServiceBinding; import org.infoglue.cms.entities.structure.SiteNode; import org.infoglue.cms.entities.structure.SiteNodeVO; import org.infoglue.cms.entities.structure.SiteNodeVersion; import org.infoglue.cms.entities.structure.impl.simple.SiteNodeImpl; import org.infoglue.cms.exception.Bug; import org.infoglue.cms.exception.ConstraintException; import org.infoglue.cms.exception.SystemException; import org.infoglue.cms.security.InfoGluePrincipal; import org.infoglue.cms.services.BaseService; import org.infoglue.cms.util.ConstraintExceptionBuffer; import org.infoglue.deliver.applications.databeans.DeliveryContext; import org.infoglue.deliver.util.CacheController; import org.infoglue.deliver.util.Timer; import com.opensymphony.module.propertyset.PropertySet; import com.opensymphony.module.propertyset.PropertySetManager; /** * @author Mattias Bogeblad */ public class ContentController extends BaseController { private final static Logger logger = Logger.getLogger(ContentController.class.getName()); //private static ContentController controller = null; /** * Factory method */ public static ContentController getContentController() { /* if(controller == null) controller = new ContentController(); return controller; */ return new ContentController(); } public ContentVO getContentVOWithId(Integer contentId) throws SystemException, Bug { return (ContentVO) getVOWithId(SmallContentImpl.class, contentId); } public ContentVO getContentVOWithId(Integer contentId, Database db) throws SystemException, Bug { return (ContentVO) getVOWithId(SmallContentImpl.class, contentId, db); } public ContentVO getSmallContentVOWithId(Integer contentId, Database db) throws SystemException, Bug { return (ContentVO) getVOWithId(SmallContentImpl.class, contentId, db); } public Content getContentWithId(Integer contentId, Database db) throws SystemException, Bug { return (Content) getObjectWithId(ContentImpl.class, contentId, db); } public Content getReadOnlyContentWithId(Integer contentId, Database db) throws SystemException, Bug { return (Content) getObjectWithIdAsReadOnly(ContentImpl.class, contentId, db); } public Content getReadOnlyMediumContentWithId(Integer contentId, Database db) throws SystemException, Bug { return (Content) getObjectWithIdAsReadOnly(MediumContentImpl.class, contentId, db); } public List getContentVOList() throws SystemException, Bug { return getAllVOObjects(ContentImpl.class, "contentId"); } public List<ContentVO> getContentVOListMarkedForDeletion(Integer repositoryId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List<ContentVO> contentVOListMarkedForDeletion = new ArrayList<ContentVO>(); try { beginTransaction(db); String sql = "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.isDeleted = $1 AND is_defined(c.repository.name) ORDER BY c.contentId"; if(repositoryId != null && repositoryId != -1) sql = "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.isDeleted = $1 AND is_defined(c.repository.name) AND c.repository = $2 ORDER BY c.contentId"; OQLQuery oql = db.getOQLQuery(sql); oql.bind(true); if(repositoryId != null && repositoryId != -1) oql.bind(repositoryId); QueryResults results = oql.execute(Database.READONLY); while(results.hasMore()) { Content content = (Content)results.next(); contentVOListMarkedForDeletion.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch ( Exception e) { throw new SystemException("An error occurred when we tried to fetch a list of deleted pages. Reason:" + e.getMessage(), e); } return contentVOListMarkedForDeletion; } /** * Returns a repository list marked for deletion. */ public Set<ContentVO> getContentVOListLastModifiedByPincipal(InfoGluePrincipal principal, String[] excludedContentTypes) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); Set<ContentVO> contentVOList = new HashSet<ContentVO>(); try { beginTransaction(db); OQLQuery oql = db.getOQLQuery("SELECT cv FROM org.infoglue.cms.entities.content.impl.simple.SmallestContentVersionImpl cv WHERE cv.versionModifier = $1 ORDER BY cv.modifiedDateTime DESC LIMIT $2"); oql.bind(principal.getName()); oql.bind(50); QueryResults results = oql.execute(Database.READONLY); while(results.hasMore()) { SmallestContentVersionImpl contentVersion = (SmallestContentVersionImpl)results.next(); ContentVO contentVO = getContentVOWithId(contentVersion.getValueObject().getContentId(), db); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(contentVO.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(contentVO); } results.close(); oql.close(); commitTransaction(db); } catch ( Exception e) { e.printStackTrace(); throw new SystemException("An error occurred when we tried to fetch a list contents last modified by the user. Reason:" + e.getMessage(), e); } return contentVOList; } /** * This method finishes what the create content wizard initiated and resulted in. */ public ContentVO create(CreateContentWizardInfoBean createContentWizardInfoBean) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = create(db, createContentWizardInfoBean.getParentContentId(), createContentWizardInfoBean.getContentTypeDefinitionId(), createContentWizardInfoBean.getRepositoryId(), createContentWizardInfoBean.getContent().getValueObject()); Iterator it = createContentWizardInfoBean.getContentVersions().keySet().iterator(); while (it.hasNext()) { Integer languageId = (Integer)it.next(); logger.info("languageId:" + languageId); ContentVersionVO contentVersionVO = (ContentVersionVO)createContentWizardInfoBean.getContentVersions().get(languageId); contentVersionVO = ContentVersionController.getContentVersionController().create(content.getContentId(), languageId, contentVersionVO, null, db).getValueObject(); } //Bind if needed? ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public ContentVO create(Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = create(db, parentContentId, contentTypeDefinitionId, repositoryId, contentVO); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public /*synchronized*/ Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); if(repositoryId == null) repositoryId = parentContent.getRepository().getRepositoryId(); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); Repository repository = RepositoryController.getController().getRepositoryWithId(repositoryId, db); /* synchronized (controller) { //db.lock(parentContent); */ content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } //} //repository.getContents().add(content); } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Repository repository, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { delete(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. * @throws Exception * @throws Bug */ public void delete(Integer contentId, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws Bug, Exception { ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(infogluePrincipal, contentId); delete(contentVO, infogluePrincipal, forceDelete); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { delete(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { delete(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { /* synchronized (controller) { //db.lock(controller); */ Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { deleteRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /* } */ } else { deleteRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void deleteRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); deleteRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } content.setChildren(new ArrayList()); boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); if(!skipServiceBindings) ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); if(parentIterator != null) parentIterator.remove(); db.remove(content); Map args = new HashMap(); args.put("globalKey", "infoglue"); PropertySet ps = PropertySetManager.getInstance("jdbc", args); ps.remove( "content_" + content.getContentId() + "_allowedContentTypeNames"); ps.remove( "content_" + content.getContentId() + "_defaultContentTypeName"); ps.remove( "content_" + content.getContentId() + "_initialLanguageId"); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method returns true if the content does not have any published contentversions or * are restricted in any other way. */ private static boolean getIsDeletable(Content content, InfoGluePrincipal infogluePrincipal, Database db) throws SystemException { boolean isDeletable = true; if(content.getIsProtected().equals(ContentVO.YES)) { boolean hasAccess = AccessRightController.getController().getIsPrincipalAuthorized(db, infogluePrincipal, "Content.Delete", "" + content.getId()); if(!hasAccess) return false; } Collection contentVersions = content.getContentVersions(); Iterator versionIterator = contentVersions.iterator(); while (versionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)versionIterator.next(); if(contentVersion.getStateId().intValue() == ContentVersionVO.PUBLISHED_STATE.intValue() && contentVersion.getIsActive().booleanValue() == true) { logger.info("The content had a published version so we cannot delete it.."); isDeletable = false; break; } } return isDeletable; } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { markForDeletion(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { markForDeletion(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { markForDeletion(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { markForDeletionRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } } else { markForDeletionRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void markForDeletionRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305", "<br/><br/>" + content.getName() + " (" + content.getId() + ")"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); markForDeletionRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { //ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); //if(!skipServiceBindings) // ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); //if(parentIterator != null) // parentIterator.remove(); content.setIsDeleted(true); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method restored a content. */ public void restoreContent(Integer contentId, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { Content content = getContentWithId(contentId, db); content.setIsDeleted(false); while(content.getParentContent() != null && content.getParentContent().getIsDeleted()) { content = content.getParentContent(); content.setIsDeleted(false); } commitTransaction(db); } catch(Exception e) { rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public ContentVO update(ContentVO contentVO) throws ConstraintException, SystemException { return update(contentVO, null); } public ContentVO update(ContentVO contentVO, Integer contentTypeDefinitionId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); Content content = null; beginTransaction(db); try { content = (Content)getObjectWithId(ContentImpl.class, contentVO.getId(), db); content.setVO(contentVO); if(contentTypeDefinitionId != null) { ContentTypeDefinition contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } public List<LanguageVO> getAvailableLanguagVOListForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException, Exception { //List<LanguageVO> availableLanguageVOList = new ArrayList<LanguageVO>(); Content content = getContentWithId(contentId, db); List<LanguageVO> availableLanguageVOList = LanguageController.getController().getLanguageVOList(content.getRepositoryId(), db); /* if(content != null) { Repository repository = content.getRepository(); if(repository != null) { List availableRepositoryLanguageList = RepositoryLanguageController.getController().getRepositoryLanguageListWithRepositoryId(repository.getId(), db); Iterator i = availableRepositoryLanguageList.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); availableLanguageVOList.add(repositoryLanguage.getLanguage().getValueObject()); } } } */ return availableLanguageVOList; } /* public List getAvailableLanguagesForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException { List availableLanguageVOList = new ArrayList(); Content content = getContentWithId(contentId, db); if(content != null) { Repository repository = content.getRepository(); if(repository != null) { Collection availableLanguages = repository.getRepositoryLanguages(); Iterator i = availableLanguages.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); int position = 0; Iterator availableLanguageVOListIterator = availableLanguageVOList.iterator(); while(availableLanguageVOListIterator.hasNext()) { LanguageVO availableLanguageVO = (LanguageVO)availableLanguageVOListIterator.next(); if(repositoryLanguage.getLanguage().getValueObject().getId().intValue() < availableLanguageVO.getId().intValue()) break; position++; } availableLanguageVOList.add(position, repositoryLanguage.getLanguage().getValueObject()); } } } return availableLanguageVOList; } */ /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); ContentVO parentContentVO = null; beginTransaction(db); try { Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return parentContentVO; } /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId, Database db) throws SystemException, Bug { ContentVO parentContentVO = null; Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); logger.info("CONTENT:" + content.getName()); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); return parentContentVO; } public static void addChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().add(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public static void removeChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().remove(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { moveContent(contentVO, newParentContentId, db); commitTransaction(db); } catch(ConstraintException ce) { logger.error("An error occurred so we should not complete the transaction:" + ce.getMessage()); rollbackTransaction(db); throw new SystemException(ce.getMessage()); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId, Database db) throws ConstraintException, SystemException { ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; Content newParentContent = null; Content oldParentContent = null; //Validation that checks the entire object contentVO.validate(); if(newParentContentId == null) { logger.warn("You must specify the new parent-content......"); throw new ConstraintException("Content.parentContentId", "3303"); } if(contentVO.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot have the content as it's own parent......"); throw new ConstraintException("Content.parentContentId", "3301"); } content = getContentWithId(contentVO.getContentId(), db); oldParentContent = content.getParentContent(); newParentContent = getContentWithId(newParentContentId, db); if(oldParentContent.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot specify the same folder as it originally was located in......"); throw new ConstraintException("Content.parentContentId", "3304"); } Content tempContent = newParentContent.getParentContent(); while(tempContent != null) { if(tempContent.getId().intValue() == content.getId().intValue()) { logger.warn("You cannot move the content to a child under it......"); throw new ConstraintException("Content.parentContentId", "3302"); } tempContent = tempContent.getParentContent(); } oldParentContent.getChildren().remove(content); content.setParentContent((ContentImpl)newParentContent); changeRepositoryRecursive(content, newParentContent.getRepository()); //content.setRepository(newParentContent.getRepository()); newParentContent.getChildren().add(content); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); } /** * Recursively sets the contents repositoryId. * @param content * @param newRepository */ private void changeRepositoryRecursive(Content content, Repository newRepository) { if(content.getRepository().getId().intValue() != newRepository.getId().intValue()) { content.setRepository((RepositoryImpl)newRepository); Iterator childContentsIterator = content.getChildren().iterator(); while(childContentsIterator.hasNext()) { Content childContent = (Content)childContentsIterator.next(); changeRepositoryRecursive(childContent, newRepository); } } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName) throws SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { List result = getContentVOWithContentTypeDefinition(contentTypeDefinitionName, db); commitTransaction(db); return result; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName, Database db) throws SystemException { HashMap arguments = new HashMap(); arguments.put("method", "selectListOnContentTypeName"); List argumentList = new ArrayList(); String[] names = contentTypeDefinitionName.split(","); for(int i = 0; i < names.length; i++) { HashMap argument = new HashMap(); argument.put("contentTypeDefinitionName", names[i]); argumentList.add(argument); } arguments.put("arguments", argumentList); try { return getContentVOList(arguments, db); } catch(SystemException e) { throw e; } catch(Exception e) { throw new SystemException(e.getMessage()); } } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap) throws SystemException, Bug { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getContentVOWithId(contentId)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments); } return contents; } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap, Database db) throws SystemException, Exception { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getSmallContentVOWithId(contentId, db)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments, db); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List contents = new ArrayList(); beginTransaction(db); try { Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); - OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND content.isDeleted = $2 ORDER BY c.contentId"); + OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments, Database db) throws SystemException, Exception { List contents = new ArrayList(); Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } return contents; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName) throws ConstraintException, SystemException { if(repositoryId == null || repositoryId.intValue() < 1) return null; Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { logger.info("Fetching the root content for the repository " + repositoryId); //OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE is_undefined(c.parentContentId) AND c.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = getRootContent(db, repositoryId, userName, createIfNonExisting); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Database db, Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException, Exception { Content content = null; logger.info("Fetching the root content for the repository " + repositoryId); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { if(createIfNonExisting) { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } } results.close(); oql.close(); return content; } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content createRootContent(Database db, Repository repository, String userName) throws ConstraintException, SystemException, Exception { Content content = null; ContentVO rootContentVO = new ContentVO(); rootContentVO.setCreatorName(userName); rootContentVO.setName(repository.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repository, rootContentVO); return content; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Integer repositoryId, Database db) throws ConstraintException, SystemException, Exception { Content content = null; OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(); this.logger.info("Fetching entity in read/write mode" + repositoryId); if (results.hasMore()) { content = (Content)results.next(); } results.close(); oql.close(); return content; } /** * This method returns a list of the children a content has. */ /* public List getContentChildrenVOList(Integer parentContentId) throws ConstraintException, SystemException { String key = "" + parentContentId; logger.info("key:" + key); List cachedChildContentVOList = (List)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = null; beginTransaction(db); try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } */ /** * This method returns a list of the children a content has. */ public List<ContentVO> getContentChildrenVOList(Integer parentContentId, String[] allowedContentTypeIds, Boolean showDeletedItems) throws ConstraintException, SystemException { String allowedContentTypeIdsString = ""; if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) allowedContentTypeIdsString += "_" + allowedContentTypeIds[i]; } String key = "" + parentContentId + allowedContentTypeIdsString + "_" + showDeletedItems; if(logger.isInfoEnabled()) logger.info("key:" + key); List<ContentVO> cachedChildContentVOList = (List<ContentVO>)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { if(logger.isInfoEnabled()) logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = new ArrayList(); beginTransaction(db); Timer t = new Timer(); /* try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); System.out.println("childrenVOList under:" + content.getName() + ":" + childrenVOList.size()); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } */ try { String contentTypeINClause = ""; if(allowedContentTypeIds != null && allowedContentTypeIds.length > 0) { contentTypeINClause = " AND content.contentTypeDefinitionId IN LIST ("; for(int i=0; i < allowedContentTypeIds.length; i++) { if(i > 0) contentTypeINClause += ","; contentTypeINClause += "$" + (i+3); } contentTypeINClause += ")"; } String showDeletedItemsClause = " AND content.isDeleted = $2"; String SQL = "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 " + showDeletedItemsClause + contentTypeINClause + " ORDER BY content.contentId"; //System.out.println("SQL:" + SQL); OQLQuery oql = db.getOQLQuery(SQL); //OQLQuery oql = db.getOQLQuery( "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 ORDER BY content.contentId"); oql.bind(parentContentId); oql.bind(showDeletedItems); if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) { System.out.println("allowedContentTypeIds[i]:" + allowedContentTypeIds[i]); oql.bind(allowedContentTypeIds[i]); } } QueryResults results = oql.execute(Database.ReadOnly); while (results.hasMore()) { Content content = (Content)results.next(); childrenVOList.add(content.getValueObject()); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } /** * This method returns the contentTypeDefinitionVO which is associated with this content. */ public ContentTypeDefinitionVO getContentTypeDefinition(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); ContentTypeDefinitionVO contentTypeDefinitionVO = null; beginTransaction(db); try { ContentVO smallContentVO = getSmallContentVOWithId(contentId, db); if(smallContentVO != null && smallContentVO.getContentTypeDefinitionId() != null) contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(smallContentVO.getContentTypeDefinitionId(), db); /* Content content = getReadOnlyMediumContentWithId(contentId, db); if(content != null && content.getContentTypeDefinition() != null) contentTypeDefinitionVO = content.getContentTypeDefinition().getValueObject(); */ //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentTypeDefinitionVO; } /** * This method reurns a list of available languages for this content. */ public List getRepositoryLanguages(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List languages = null; beginTransaction(db); try { languages = LanguageController.getController().getLanguageVOList(contentId, db); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return languages; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { result = getBoundContents(db, serviceBindingId); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return result; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } public static List getInTransactionBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getController().getReadOnlyServiceBindingWithId(serviceBindingId, db); //ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments, db); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } /** * This method just sorts the list of qualifyers on sortOrder. */ private static List sortQualifyers(Collection qualifyers) { List sortedQualifyers = new ArrayList(); try { Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); int index = 0; Iterator sortedListIterator = sortedQualifyers.iterator(); while(sortedListIterator.hasNext()) { Qualifyer sortedQualifyer = (Qualifyer)sortedListIterator.next(); if(sortedQualifyer.getSortOrder().intValue() > qualifyer.getSortOrder().intValue()) { break; } index++; } sortedQualifyers.add(index, qualifyer); } } catch(Exception e) { logger.warn("The sorting of qualifyers failed:" + e.getMessage(), e); } return sortedQualifyers; } /** * This method returns the contents belonging to a certain repository. */ public List getRepositoryContents(Integer repositoryId, Database db) throws SystemException, Exception { List contents = new ArrayList(); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.repositoryId = $1 ORDER BY c.contentId"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content); } results.close(); oql.close(); return contents; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator) throws SystemException, Exception { ContentVO contentVO = null; Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { contentVO = getContentVOWithPath(repositoryId, path, forceFolders, creator, db); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVO; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { ContentVO content = getRootContent(repositoryId, db).getValueObject(); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; if(!name.equals("")) { final ContentVO childContent = getChildVOWithName(content.getContentId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent.getValueObject(); } } } return content; } public Content getContentWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { Content content = getRootContent(repositoryId, db); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; final Content childContent = getChildWithName(content.getId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { logger.info(" CREATE " + name); ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent; } } return content; } /** * */ private ContentVO getChildVOWithName(Integer parentContentId, String name, Database db) throws Exception { ContentVO contentVO = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.parentContentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(Database.ReadOnly); if(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contentVO = content.getValueObject(); } results.close(); oql.close(); return contentVO; } /** * */ private Content getChildWithName(Integer parentContentId, String name, Database db) throws Exception { Content content = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.parentContent.contentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(); if(results.hasMore()) { content = (ContentImpl)results.next(); } results.close(); oql.close(); return content; } /** * */ /* private Content getChildWithName(Content content, String name, Database db) { for(Iterator i=content.getChildren().iterator(); i.hasNext(); ) { final Content childContent = (Content) i.next(); if(childContent.getName().equals(name)) return childContent; } return null; } */ /** * Recursive methods to get all contentVersions of a given state under the specified parent content. */ public List getContentVOWithParentRecursive(Integer contentId) throws ConstraintException, SystemException { return getContentVOWithParentRecursive(contentId, new ArrayList()); } private List getContentVOWithParentRecursive(Integer contentId, List resultList) throws ConstraintException, SystemException { // Get the versions of this content. resultList.add(getContentVOWithId(contentId)); // Get the children of this content and do the recursion List childContentList = ContentController.getContentController().getContentChildrenVOList(contentId, null, false); Iterator cit = childContentList.iterator(); while (cit.hasNext()) { ContentVO contentVO = (ContentVO) cit.next(); getContentVOWithParentRecursive(contentVO.getId(), resultList); } return resultList; } public String getContentAttribute(Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId); attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } /** * This is a method that gives the user back an newly initialized ValueObject for this entity that the controller * is handling. */ public BaseEntityVO getNewVO() { return new ContentVO(); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId) throws ConstraintException, SystemException, Bug, Exception { return getContentPath(contentId, false, false); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId, boolean includeRootContent, boolean includeRepositoryName) throws ConstraintException, SystemException, Bug, Exception { StringBuffer sb = new StringBuffer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); sb.insert(0, contentVO.getName()); while (contentVO.getParentContentId() != null) { contentVO = ContentController.getContentController().getContentVOWithId(contentVO.getParentContentId()); if (includeRootContent || contentVO.getParentContentId() != null) { sb.insert(0, contentVO.getName() + "/"); } } if (includeRepositoryName) { RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(contentVO.getRepositoryId()); if(repositoryVO != null) sb.insert(0, repositoryVO.getName() + " - /"); } return sb.toString(); } public List<ContentVO> getUpcomingExpiringContents(int numberOfWeeks) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfWeeks); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } public List<ContentVO> getUpcomingExpiringContents(int numberOfDays, InfoGluePrincipal principal, String[] excludedContentTypes) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3 AND c.contentVersions.versionModifier = $4"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfDays); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); oql.bind(principal.getName()); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(content.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } System.out.println("contentVOList:" + contentVOList.size()); return contentVOList; } }
true
true
public /*synchronized*/ Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); if(repositoryId == null) repositoryId = parentContent.getRepository().getRepositoryId(); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); Repository repository = RepositoryController.getController().getRepositoryWithId(repositoryId, db); /* synchronized (controller) { //db.lock(parentContent); */ content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } //} //repository.getContents().add(content); } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Repository repository, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { delete(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. * @throws Exception * @throws Bug */ public void delete(Integer contentId, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws Bug, Exception { ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(infogluePrincipal, contentId); delete(contentVO, infogluePrincipal, forceDelete); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { delete(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { delete(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { /* synchronized (controller) { //db.lock(controller); */ Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { deleteRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /* } */ } else { deleteRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void deleteRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); deleteRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } content.setChildren(new ArrayList()); boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); if(!skipServiceBindings) ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); if(parentIterator != null) parentIterator.remove(); db.remove(content); Map args = new HashMap(); args.put("globalKey", "infoglue"); PropertySet ps = PropertySetManager.getInstance("jdbc", args); ps.remove( "content_" + content.getContentId() + "_allowedContentTypeNames"); ps.remove( "content_" + content.getContentId() + "_defaultContentTypeName"); ps.remove( "content_" + content.getContentId() + "_initialLanguageId"); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method returns true if the content does not have any published contentversions or * are restricted in any other way. */ private static boolean getIsDeletable(Content content, InfoGluePrincipal infogluePrincipal, Database db) throws SystemException { boolean isDeletable = true; if(content.getIsProtected().equals(ContentVO.YES)) { boolean hasAccess = AccessRightController.getController().getIsPrincipalAuthorized(db, infogluePrincipal, "Content.Delete", "" + content.getId()); if(!hasAccess) return false; } Collection contentVersions = content.getContentVersions(); Iterator versionIterator = contentVersions.iterator(); while (versionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)versionIterator.next(); if(contentVersion.getStateId().intValue() == ContentVersionVO.PUBLISHED_STATE.intValue() && contentVersion.getIsActive().booleanValue() == true) { logger.info("The content had a published version so we cannot delete it.."); isDeletable = false; break; } } return isDeletable; } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { markForDeletion(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { markForDeletion(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { markForDeletion(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { markForDeletionRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } } else { markForDeletionRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void markForDeletionRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305", "<br/><br/>" + content.getName() + " (" + content.getId() + ")"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); markForDeletionRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { //ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); //if(!skipServiceBindings) // ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); //if(parentIterator != null) // parentIterator.remove(); content.setIsDeleted(true); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method restored a content. */ public void restoreContent(Integer contentId, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { Content content = getContentWithId(contentId, db); content.setIsDeleted(false); while(content.getParentContent() != null && content.getParentContent().getIsDeleted()) { content = content.getParentContent(); content.setIsDeleted(false); } commitTransaction(db); } catch(Exception e) { rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public ContentVO update(ContentVO contentVO) throws ConstraintException, SystemException { return update(contentVO, null); } public ContentVO update(ContentVO contentVO, Integer contentTypeDefinitionId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); Content content = null; beginTransaction(db); try { content = (Content)getObjectWithId(ContentImpl.class, contentVO.getId(), db); content.setVO(contentVO); if(contentTypeDefinitionId != null) { ContentTypeDefinition contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } public List<LanguageVO> getAvailableLanguagVOListForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException, Exception { //List<LanguageVO> availableLanguageVOList = new ArrayList<LanguageVO>(); Content content = getContentWithId(contentId, db); List<LanguageVO> availableLanguageVOList = LanguageController.getController().getLanguageVOList(content.getRepositoryId(), db); /* if(content != null) { Repository repository = content.getRepository(); if(repository != null) { List availableRepositoryLanguageList = RepositoryLanguageController.getController().getRepositoryLanguageListWithRepositoryId(repository.getId(), db); Iterator i = availableRepositoryLanguageList.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); availableLanguageVOList.add(repositoryLanguage.getLanguage().getValueObject()); } } } */ return availableLanguageVOList; } /* public List getAvailableLanguagesForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException { List availableLanguageVOList = new ArrayList(); Content content = getContentWithId(contentId, db); if(content != null) { Repository repository = content.getRepository(); if(repository != null) { Collection availableLanguages = repository.getRepositoryLanguages(); Iterator i = availableLanguages.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); int position = 0; Iterator availableLanguageVOListIterator = availableLanguageVOList.iterator(); while(availableLanguageVOListIterator.hasNext()) { LanguageVO availableLanguageVO = (LanguageVO)availableLanguageVOListIterator.next(); if(repositoryLanguage.getLanguage().getValueObject().getId().intValue() < availableLanguageVO.getId().intValue()) break; position++; } availableLanguageVOList.add(position, repositoryLanguage.getLanguage().getValueObject()); } } } return availableLanguageVOList; } */ /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); ContentVO parentContentVO = null; beginTransaction(db); try { Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return parentContentVO; } /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId, Database db) throws SystemException, Bug { ContentVO parentContentVO = null; Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); logger.info("CONTENT:" + content.getName()); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); return parentContentVO; } public static void addChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().add(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public static void removeChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().remove(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { moveContent(contentVO, newParentContentId, db); commitTransaction(db); } catch(ConstraintException ce) { logger.error("An error occurred so we should not complete the transaction:" + ce.getMessage()); rollbackTransaction(db); throw new SystemException(ce.getMessage()); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId, Database db) throws ConstraintException, SystemException { ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; Content newParentContent = null; Content oldParentContent = null; //Validation that checks the entire object contentVO.validate(); if(newParentContentId == null) { logger.warn("You must specify the new parent-content......"); throw new ConstraintException("Content.parentContentId", "3303"); } if(contentVO.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot have the content as it's own parent......"); throw new ConstraintException("Content.parentContentId", "3301"); } content = getContentWithId(contentVO.getContentId(), db); oldParentContent = content.getParentContent(); newParentContent = getContentWithId(newParentContentId, db); if(oldParentContent.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot specify the same folder as it originally was located in......"); throw new ConstraintException("Content.parentContentId", "3304"); } Content tempContent = newParentContent.getParentContent(); while(tempContent != null) { if(tempContent.getId().intValue() == content.getId().intValue()) { logger.warn("You cannot move the content to a child under it......"); throw new ConstraintException("Content.parentContentId", "3302"); } tempContent = tempContent.getParentContent(); } oldParentContent.getChildren().remove(content); content.setParentContent((ContentImpl)newParentContent); changeRepositoryRecursive(content, newParentContent.getRepository()); //content.setRepository(newParentContent.getRepository()); newParentContent.getChildren().add(content); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); } /** * Recursively sets the contents repositoryId. * @param content * @param newRepository */ private void changeRepositoryRecursive(Content content, Repository newRepository) { if(content.getRepository().getId().intValue() != newRepository.getId().intValue()) { content.setRepository((RepositoryImpl)newRepository); Iterator childContentsIterator = content.getChildren().iterator(); while(childContentsIterator.hasNext()) { Content childContent = (Content)childContentsIterator.next(); changeRepositoryRecursive(childContent, newRepository); } } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName) throws SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { List result = getContentVOWithContentTypeDefinition(contentTypeDefinitionName, db); commitTransaction(db); return result; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName, Database db) throws SystemException { HashMap arguments = new HashMap(); arguments.put("method", "selectListOnContentTypeName"); List argumentList = new ArrayList(); String[] names = contentTypeDefinitionName.split(","); for(int i = 0; i < names.length; i++) { HashMap argument = new HashMap(); argument.put("contentTypeDefinitionName", names[i]); argumentList.add(argument); } arguments.put("arguments", argumentList); try { return getContentVOList(arguments, db); } catch(SystemException e) { throw e; } catch(Exception e) { throw new SystemException(e.getMessage()); } } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap) throws SystemException, Bug { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getContentVOWithId(contentId)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments); } return contents; } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap, Database db) throws SystemException, Exception { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getSmallContentVOWithId(contentId, db)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments, db); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List contents = new ArrayList(); beginTransaction(db); try { Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND content.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments, Database db) throws SystemException, Exception { List contents = new ArrayList(); Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } return contents; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName) throws ConstraintException, SystemException { if(repositoryId == null || repositoryId.intValue() < 1) return null; Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { logger.info("Fetching the root content for the repository " + repositoryId); //OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE is_undefined(c.parentContentId) AND c.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = getRootContent(db, repositoryId, userName, createIfNonExisting); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Database db, Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException, Exception { Content content = null; logger.info("Fetching the root content for the repository " + repositoryId); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { if(createIfNonExisting) { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } } results.close(); oql.close(); return content; } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content createRootContent(Database db, Repository repository, String userName) throws ConstraintException, SystemException, Exception { Content content = null; ContentVO rootContentVO = new ContentVO(); rootContentVO.setCreatorName(userName); rootContentVO.setName(repository.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repository, rootContentVO); return content; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Integer repositoryId, Database db) throws ConstraintException, SystemException, Exception { Content content = null; OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(); this.logger.info("Fetching entity in read/write mode" + repositoryId); if (results.hasMore()) { content = (Content)results.next(); } results.close(); oql.close(); return content; } /** * This method returns a list of the children a content has. */ /* public List getContentChildrenVOList(Integer parentContentId) throws ConstraintException, SystemException { String key = "" + parentContentId; logger.info("key:" + key); List cachedChildContentVOList = (List)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = null; beginTransaction(db); try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } */ /** * This method returns a list of the children a content has. */ public List<ContentVO> getContentChildrenVOList(Integer parentContentId, String[] allowedContentTypeIds, Boolean showDeletedItems) throws ConstraintException, SystemException { String allowedContentTypeIdsString = ""; if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) allowedContentTypeIdsString += "_" + allowedContentTypeIds[i]; } String key = "" + parentContentId + allowedContentTypeIdsString + "_" + showDeletedItems; if(logger.isInfoEnabled()) logger.info("key:" + key); List<ContentVO> cachedChildContentVOList = (List<ContentVO>)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { if(logger.isInfoEnabled()) logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = new ArrayList(); beginTransaction(db); Timer t = new Timer(); /* try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); System.out.println("childrenVOList under:" + content.getName() + ":" + childrenVOList.size()); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } */ try { String contentTypeINClause = ""; if(allowedContentTypeIds != null && allowedContentTypeIds.length > 0) { contentTypeINClause = " AND content.contentTypeDefinitionId IN LIST ("; for(int i=0; i < allowedContentTypeIds.length; i++) { if(i > 0) contentTypeINClause += ","; contentTypeINClause += "$" + (i+3); } contentTypeINClause += ")"; } String showDeletedItemsClause = " AND content.isDeleted = $2"; String SQL = "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 " + showDeletedItemsClause + contentTypeINClause + " ORDER BY content.contentId"; //System.out.println("SQL:" + SQL); OQLQuery oql = db.getOQLQuery(SQL); //OQLQuery oql = db.getOQLQuery( "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 ORDER BY content.contentId"); oql.bind(parentContentId); oql.bind(showDeletedItems); if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) { System.out.println("allowedContentTypeIds[i]:" + allowedContentTypeIds[i]); oql.bind(allowedContentTypeIds[i]); } } QueryResults results = oql.execute(Database.ReadOnly); while (results.hasMore()) { Content content = (Content)results.next(); childrenVOList.add(content.getValueObject()); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } /** * This method returns the contentTypeDefinitionVO which is associated with this content. */ public ContentTypeDefinitionVO getContentTypeDefinition(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); ContentTypeDefinitionVO contentTypeDefinitionVO = null; beginTransaction(db); try { ContentVO smallContentVO = getSmallContentVOWithId(contentId, db); if(smallContentVO != null && smallContentVO.getContentTypeDefinitionId() != null) contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(smallContentVO.getContentTypeDefinitionId(), db); /* Content content = getReadOnlyMediumContentWithId(contentId, db); if(content != null && content.getContentTypeDefinition() != null) contentTypeDefinitionVO = content.getContentTypeDefinition().getValueObject(); */ //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentTypeDefinitionVO; } /** * This method reurns a list of available languages for this content. */ public List getRepositoryLanguages(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List languages = null; beginTransaction(db); try { languages = LanguageController.getController().getLanguageVOList(contentId, db); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return languages; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { result = getBoundContents(db, serviceBindingId); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return result; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } public static List getInTransactionBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getController().getReadOnlyServiceBindingWithId(serviceBindingId, db); //ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments, db); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } /** * This method just sorts the list of qualifyers on sortOrder. */ private static List sortQualifyers(Collection qualifyers) { List sortedQualifyers = new ArrayList(); try { Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); int index = 0; Iterator sortedListIterator = sortedQualifyers.iterator(); while(sortedListIterator.hasNext()) { Qualifyer sortedQualifyer = (Qualifyer)sortedListIterator.next(); if(sortedQualifyer.getSortOrder().intValue() > qualifyer.getSortOrder().intValue()) { break; } index++; } sortedQualifyers.add(index, qualifyer); } } catch(Exception e) { logger.warn("The sorting of qualifyers failed:" + e.getMessage(), e); } return sortedQualifyers; } /** * This method returns the contents belonging to a certain repository. */ public List getRepositoryContents(Integer repositoryId, Database db) throws SystemException, Exception { List contents = new ArrayList(); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.repositoryId = $1 ORDER BY c.contentId"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content); } results.close(); oql.close(); return contents; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator) throws SystemException, Exception { ContentVO contentVO = null; Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { contentVO = getContentVOWithPath(repositoryId, path, forceFolders, creator, db); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVO; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { ContentVO content = getRootContent(repositoryId, db).getValueObject(); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; if(!name.equals("")) { final ContentVO childContent = getChildVOWithName(content.getContentId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent.getValueObject(); } } } return content; } public Content getContentWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { Content content = getRootContent(repositoryId, db); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; final Content childContent = getChildWithName(content.getId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { logger.info(" CREATE " + name); ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent; } } return content; } /** * */ private ContentVO getChildVOWithName(Integer parentContentId, String name, Database db) throws Exception { ContentVO contentVO = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.parentContentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(Database.ReadOnly); if(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contentVO = content.getValueObject(); } results.close(); oql.close(); return contentVO; } /** * */ private Content getChildWithName(Integer parentContentId, String name, Database db) throws Exception { Content content = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.parentContent.contentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(); if(results.hasMore()) { content = (ContentImpl)results.next(); } results.close(); oql.close(); return content; } /** * */ /* private Content getChildWithName(Content content, String name, Database db) { for(Iterator i=content.getChildren().iterator(); i.hasNext(); ) { final Content childContent = (Content) i.next(); if(childContent.getName().equals(name)) return childContent; } return null; } */ /** * Recursive methods to get all contentVersions of a given state under the specified parent content. */ public List getContentVOWithParentRecursive(Integer contentId) throws ConstraintException, SystemException { return getContentVOWithParentRecursive(contentId, new ArrayList()); } private List getContentVOWithParentRecursive(Integer contentId, List resultList) throws ConstraintException, SystemException { // Get the versions of this content. resultList.add(getContentVOWithId(contentId)); // Get the children of this content and do the recursion List childContentList = ContentController.getContentController().getContentChildrenVOList(contentId, null, false); Iterator cit = childContentList.iterator(); while (cit.hasNext()) { ContentVO contentVO = (ContentVO) cit.next(); getContentVOWithParentRecursive(contentVO.getId(), resultList); } return resultList; } public String getContentAttribute(Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId); attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } /** * This is a method that gives the user back an newly initialized ValueObject for this entity that the controller * is handling. */ public BaseEntityVO getNewVO() { return new ContentVO(); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId) throws ConstraintException, SystemException, Bug, Exception { return getContentPath(contentId, false, false); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId, boolean includeRootContent, boolean includeRepositoryName) throws ConstraintException, SystemException, Bug, Exception { StringBuffer sb = new StringBuffer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); sb.insert(0, contentVO.getName()); while (contentVO.getParentContentId() != null) { contentVO = ContentController.getContentController().getContentVOWithId(contentVO.getParentContentId()); if (includeRootContent || contentVO.getParentContentId() != null) { sb.insert(0, contentVO.getName() + "/"); } } if (includeRepositoryName) { RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(contentVO.getRepositoryId()); if(repositoryVO != null) sb.insert(0, repositoryVO.getName() + " - /"); } return sb.toString(); } public List<ContentVO> getUpcomingExpiringContents(int numberOfWeeks) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfWeeks); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } public List<ContentVO> getUpcomingExpiringContents(int numberOfDays, InfoGluePrincipal principal, String[] excludedContentTypes) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3 AND c.contentVersions.versionModifier = $4"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfDays); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); oql.bind(principal.getName()); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(content.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } System.out.println("contentVOList:" + contentVOList.size()); return contentVOList; } }
public /*synchronized*/ Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Integer repositoryId, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); if(repositoryId == null) repositoryId = parentContent.getRepository().getRepositoryId(); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); Repository repository = RepositoryController.getController().getRepositoryWithId(repositoryId, db); /* synchronized (controller) { //db.lock(parentContent); */ content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } //} //repository.getContents().add(content); } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method creates a new content-entity and references the entities it should know about. * As castor is lousy at this in my opinion we also add the new entity to the surrounding entities. */ public Content create(Database db, Integer parentContentId, Integer contentTypeDefinitionId, Repository repository, ContentVO contentVO) throws ConstraintException, SystemException, Exception { Content content = null; try { Content parentContent = null; ContentTypeDefinition contentTypeDefinition = null; if(parentContentId != null) { parentContent = getContentWithId(parentContentId, db); } if(contentTypeDefinitionId != null) contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content = new ContentImpl(); content.setValueObject(contentVO); content.setParentContent((ContentImpl)parentContent); content.setRepository((RepositoryImpl)repository); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); db.create(content); //Now we add the content to the knowledge of the related entities. if(parentContent != null) { parentContent.getChildren().add(content); parentContent.setIsBranch(new Boolean(true)); } } catch(Exception e) { //logger.error("An error occurred so we should not complete the transaction:" + e, e); throw new SystemException(e.getMessage()); } return content; } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { delete(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. * @throws Exception * @throws Bug */ public void delete(Integer contentId, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws Bug, Exception { ContentVO contentVO = ContentControllerProxy.getController().getACContentVOWithId(infogluePrincipal, contentId); delete(contentVO, infogluePrincipal, forceDelete); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { delete(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { delete(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void delete(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { /* synchronized (controller) { //db.lock(controller); */ Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { deleteRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /* } */ } else { deleteRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void deleteRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); deleteRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } content.setChildren(new ArrayList()); boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); if(!skipServiceBindings) ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); if(parentIterator != null) parentIterator.remove(); db.remove(content); Map args = new HashMap(); args.put("globalKey", "infoglue"); PropertySet ps = PropertySetManager.getInstance("jdbc", args); ps.remove( "content_" + content.getContentId() + "_allowedContentTypeNames"); ps.remove( "content_" + content.getContentId() + "_defaultContentTypeName"); ps.remove( "content_" + content.getContentId() + "_initialLanguageId"); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method returns true if the content does not have any published contentversions or * are restricted in any other way. */ private static boolean getIsDeletable(Content content, InfoGluePrincipal infogluePrincipal, Database db) throws SystemException { boolean isDeletable = true; if(content.getIsProtected().equals(ContentVO.YES)) { boolean hasAccess = AccessRightController.getController().getIsPrincipalAuthorized(db, infogluePrincipal, "Content.Delete", "" + content.getId()); if(!hasAccess) return false; } Collection contentVersions = content.getContentVersions(); Iterator versionIterator = contentVersions.iterator(); while (versionIterator.hasNext()) { ContentVersion contentVersion = (ContentVersion)versionIterator.next(); if(contentVersion.getStateId().intValue() == ContentVersionVO.PUBLISHED_STATE.intValue() && contentVersion.getIsActive().booleanValue() == true) { logger.info("The content had a published version so we cannot delete it.."); isDeletable = false; break; } } return isDeletable; } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { markForDeletion(contentVO, infogluePrincipal, false); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, boolean forceDelete) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { markForDeletion(contentVO, db, false, false, forceDelete, infogluePrincipal); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Exception { markForDeletion(contentVO, db, false, false, false, infogluePrincipal); } /** * This method deletes a content and also erases all the children and all versions. */ public void markForDeletion(ContentVO contentVO, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { Content content = null; try { content = getContentWithId(contentVO.getContentId(), db); } catch(SystemException e) { return; } Content parent = content.getParentContent(); if(parent != null) { Iterator childContentIterator = parent.getChildren().iterator(); while(childContentIterator.hasNext()) { Content candidate = (Content)childContentIterator.next(); if(candidate.getId().equals(contentVO.getContentId())) { markForDeletionRecursive(content, childContentIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } } else { markForDeletionRecursive(content, null, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } } /** * Recursively deletes all contents and their versions. Also updates related entities about the change. */ private static void markForDeletionRecursive(Content content, Iterator parentIterator, Database db, boolean skipRelationCheck, boolean skipServiceBindings, boolean forceDelete, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Exception { if(!skipRelationCheck) { List referenceBeanList = RegistryController.getController().getReferencingObjectsForContent(content.getId(), -1, db); if(referenceBeanList != null && referenceBeanList.size() > 0) throw new ConstraintException("ContentVersion.stateId", "3305", "<br/><br/>" + content.getName() + " (" + content.getId() + ")"); } Collection children = content.getChildren(); Iterator childrenIterator = children.iterator(); while(childrenIterator.hasNext()) { Content childContent = (Content)childrenIterator.next(); markForDeletionRecursive(childContent, childrenIterator, db, skipRelationCheck, skipServiceBindings, forceDelete, infogluePrincipal); } boolean isDeletable = getIsDeletable(content, infogluePrincipal, db); if(forceDelete || isDeletable) { //ContentVersionController.getContentVersionController().deleteVersionsForContent(content, db, forceDelete, infogluePrincipal); //if(!skipServiceBindings) // ServiceBindingController.deleteServiceBindingsReferencingContent(content, db); //if(parentIterator != null) // parentIterator.remove(); content.setIsDeleted(true); } else { throw new ConstraintException("ContentVersion.stateId", "3300", content.getName()); } } /** * This method restored a content. */ public void restoreContent(Integer contentId, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { Content content = getContentWithId(contentId, db); content.setIsDeleted(false); while(content.getParentContent() != null && content.getParentContent().getIsDeleted()) { content = content.getParentContent(); content.setIsDeleted(false); } commitTransaction(db); } catch(Exception e) { rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public ContentVO update(ContentVO contentVO) throws ConstraintException, SystemException { return update(contentVO, null); } public ContentVO update(ContentVO contentVO, Integer contentTypeDefinitionId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); Content content = null; beginTransaction(db); try { content = (Content)getObjectWithId(ContentImpl.class, contentVO.getId(), db); content.setVO(contentVO); if(contentTypeDefinitionId != null) { ContentTypeDefinition contentTypeDefinition = ContentTypeDefinitionController.getController().getContentTypeDefinitionWithId(contentTypeDefinitionId, db); content.setContentTypeDefinition((ContentTypeDefinitionImpl)contentTypeDefinition); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return content.getValueObject(); } public List<LanguageVO> getAvailableLanguagVOListForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException, Exception { //List<LanguageVO> availableLanguageVOList = new ArrayList<LanguageVO>(); Content content = getContentWithId(contentId, db); List<LanguageVO> availableLanguageVOList = LanguageController.getController().getLanguageVOList(content.getRepositoryId(), db); /* if(content != null) { Repository repository = content.getRepository(); if(repository != null) { List availableRepositoryLanguageList = RepositoryLanguageController.getController().getRepositoryLanguageListWithRepositoryId(repository.getId(), db); Iterator i = availableRepositoryLanguageList.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); availableLanguageVOList.add(repositoryLanguage.getLanguage().getValueObject()); } } } */ return availableLanguageVOList; } /* public List getAvailableLanguagesForContentWithId(Integer contentId, Database db) throws ConstraintException, SystemException { List availableLanguageVOList = new ArrayList(); Content content = getContentWithId(contentId, db); if(content != null) { Repository repository = content.getRepository(); if(repository != null) { Collection availableLanguages = repository.getRepositoryLanguages(); Iterator i = availableLanguages.iterator(); while(i.hasNext()) { RepositoryLanguage repositoryLanguage = (RepositoryLanguage)i.next(); int position = 0; Iterator availableLanguageVOListIterator = availableLanguageVOList.iterator(); while(availableLanguageVOListIterator.hasNext()) { LanguageVO availableLanguageVO = (LanguageVO)availableLanguageVOListIterator.next(); if(repositoryLanguage.getLanguage().getValueObject().getId().intValue() < availableLanguageVO.getId().intValue()) break; position++; } availableLanguageVOList.add(position, repositoryLanguage.getLanguage().getValueObject()); } } } return availableLanguageVOList; } */ /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); ContentVO parentContentVO = null; beginTransaction(db); try { Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return parentContentVO; } /** * This method returns the value-object of the parent of a specific content. */ public static ContentVO getParentContent(Integer contentId, Database db) throws SystemException, Bug { ContentVO parentContentVO = null; Content content = (Content) getObjectWithId(ContentImpl.class, contentId, db); logger.info("CONTENT:" + content.getName()); Content parent = content.getParentContent(); if(parent != null) parentContentVO = parent.getValueObject(); return parentContentVO; } public static void addChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().add(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } public static void removeChildContent(ContentVO parentVO, ContentVO childVO) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { Content parent = (Content) getObjectWithId(ContentImpl.class, parentVO.getContentId(), db); Content child = (Content) getObjectWithId(ContentImpl.class, childVO.getContentId(), db); parent.getChildren().remove(child); ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { moveContent(contentVO, newParentContentId, db); commitTransaction(db); } catch(ConstraintException ce) { logger.error("An error occurred so we should not complete the transaction:" + ce.getMessage()); rollbackTransaction(db); throw new SystemException(ce.getMessage()); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * This method moves a content from one parent-content to another. First we check so no illegal actions are * in process. For example the target folder must not be the item to be moved or a child to the item. * Such actions would result in model-errors. */ public void moveContent(ContentVO contentVO, Integer newParentContentId, Database db) throws ConstraintException, SystemException { ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; Content newParentContent = null; Content oldParentContent = null; //Validation that checks the entire object contentVO.validate(); if(newParentContentId == null) { logger.warn("You must specify the new parent-content......"); throw new ConstraintException("Content.parentContentId", "3303"); } if(contentVO.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot have the content as it's own parent......"); throw new ConstraintException("Content.parentContentId", "3301"); } content = getContentWithId(contentVO.getContentId(), db); oldParentContent = content.getParentContent(); newParentContent = getContentWithId(newParentContentId, db); if(oldParentContent.getId().intValue() == newParentContentId.intValue()) { logger.warn("You cannot specify the same folder as it originally was located in......"); throw new ConstraintException("Content.parentContentId", "3304"); } Content tempContent = newParentContent.getParentContent(); while(tempContent != null) { if(tempContent.getId().intValue() == content.getId().intValue()) { logger.warn("You cannot move the content to a child under it......"); throw new ConstraintException("Content.parentContentId", "3302"); } tempContent = tempContent.getParentContent(); } oldParentContent.getChildren().remove(content); content.setParentContent((ContentImpl)newParentContent); changeRepositoryRecursive(content, newParentContent.getRepository()); //content.setRepository(newParentContent.getRepository()); newParentContent.getChildren().add(content); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); } /** * Recursively sets the contents repositoryId. * @param content * @param newRepository */ private void changeRepositoryRecursive(Content content, Repository newRepository) { if(content.getRepository().getId().intValue() != newRepository.getId().intValue()) { content.setRepository((RepositoryImpl)newRepository); Iterator childContentsIterator = content.getChildren().iterator(); while(childContentsIterator.hasNext()) { Content childContent = (Content)childContentsIterator.next(); changeRepositoryRecursive(childContent, newRepository); } } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName) throws SystemException { Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { List result = getContentVOWithContentTypeDefinition(contentTypeDefinitionName, db); commitTransaction(db); return result; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } } /** * Returns all Contents having the specified ContentTypeDefintion. */ public List getContentVOWithContentTypeDefinition(String contentTypeDefinitionName, Database db) throws SystemException { HashMap arguments = new HashMap(); arguments.put("method", "selectListOnContentTypeName"); List argumentList = new ArrayList(); String[] names = contentTypeDefinitionName.split(","); for(int i = 0; i < names.length; i++) { HashMap argument = new HashMap(); argument.put("contentTypeDefinitionName", names[i]); argumentList.add(argument); } arguments.put("arguments", argumentList); try { return getContentVOList(arguments, db); } catch(SystemException e) { throw e; } catch(Exception e) { throw new SystemException(e.getMessage()); } } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap) throws SystemException, Bug { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getContentVOWithId(contentId)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments); } return contents; } /** * This method is sort of a sql-query-like method where you can send in arguments in form of a list * of things that should match. The input is a Hashmap with a method and a List of HashMaps. */ public List getContentVOList(HashMap argumentHashMap, Database db) throws SystemException, Exception { List contents = null; String method = (String)argumentHashMap.get("method"); logger.info("method:" + method); if(method.equalsIgnoreCase("selectContentListOnIdList")) { contents = new ArrayList(); List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); Iterator argumentIterator = arguments.iterator(); while(argumentIterator.hasNext()) { HashMap argument = (HashMap)argumentIterator.next(); Integer contentId = new Integer((String)argument.get("contentId")); logger.info("Getting the content with Id:" + contentId); contents.add(getSmallContentVOWithId(contentId, db)); } } else if(method.equalsIgnoreCase("selectListOnContentTypeName")) { List arguments = (List)argumentHashMap.get("arguments"); logger.info("Arguments:" + arguments.size()); contents = getContentVOListByContentTypeNames(arguments, db); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments) throws SystemException, Bug { Database db = CastorDatabaseService.getDatabase(); List contents = new ArrayList(); beginTransaction(db); try { Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 AND c.isDeleted = $2 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); oql.bind(false); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contents; } /** * The input is a list of hashmaps. */ protected List getContentVOListByContentTypeNames(List arguments, Database db) throws SystemException, Exception { List contents = new ArrayList(); Iterator i = arguments.iterator(); while(i.hasNext()) { HashMap argument = (HashMap)i.next(); String contentTypeDefinitionName = (String)argument.get("contentTypeDefinitionName"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT c.contentId, c.name, c.publishDateTime, c.expireDateTime, c.isBranch, c.isProtected, c.creator, ctd.contentTypeDefinitionId, r.repositoryId FROM cmContent c, cmContentTypeDefinition ctd, cmRepository r where c.repositoryId = r.repositoryId AND c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.SmallContentImpl"); //OQLQuery oql = db.getOQLQuery("CALL SQL SELECT contentId, name FROM cmContent c, cmContentTypeDefinition ctd WHERE c.contentTypeDefinitionId = ctd.contentTypeDefinitionId AND ctd.name = $1 AS org.infoglue.cms.entities.content.impl.simple.ContentImpl"); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.contentTypeDefinition.name = $1 ORDER BY c.contentId"); oql.bind(contentTypeDefinitionName); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content.getValueObject()); } results.close(); oql.close(); } return contents; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName) throws ConstraintException, SystemException { if(repositoryId == null || repositoryId.intValue() < 1) return null; Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { logger.info("Fetching the root content for the repository " + repositoryId); //OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE is_undefined(c.parentContentId) AND c.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public ContentVO getRootContentVO(Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); Content content = null; beginTransaction(db); try { content = getRootContent(db, repositoryId, userName, createIfNonExisting); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return (content == null) ? null : content.getValueObject(); } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Database db, Integer repositoryId, String userName, boolean createIfNonExisting) throws ConstraintException, SystemException, Exception { Content content = null; logger.info("Fetching the root content for the repository " + repositoryId); OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); if (results.hasMore()) { content = (Content)results.next(); } else { if(createIfNonExisting) { //None found - we create it and give it the name of the repository. logger.info("Found no rootContent so we create a new...."); ContentVO rootContentVO = new ContentVO(); RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(repositoryId); rootContentVO.setCreatorName(userName); rootContentVO.setName(repositoryVO.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repositoryId, rootContentVO); } } results.close(); oql.close(); return content; } /** * This method fetches the root content for a particular repository within a transaction. * If there is no such content we create one as all repositories need one to work. */ public Content createRootContent(Database db, Repository repository, String userName) throws ConstraintException, SystemException, Exception { Content content = null; ContentVO rootContentVO = new ContentVO(); rootContentVO.setCreatorName(userName); rootContentVO.setName(repository.getName()); rootContentVO.setIsBranch(new Boolean(true)); content = create(db, null, null, repository, rootContentVO); return content; } /** * This method fetches the root content for a particular repository. * If there is no such content we create one as all repositories need one to work. */ public Content getRootContent(Integer repositoryId, Database db) throws ConstraintException, SystemException, Exception { Content content = null; OQLQuery oql = db.getOQLQuery( "SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE is_undefined(c.parentContent) AND c.repository.repositoryId = $1"); oql.bind(repositoryId); QueryResults results = oql.execute(); this.logger.info("Fetching entity in read/write mode" + repositoryId); if (results.hasMore()) { content = (Content)results.next(); } results.close(); oql.close(); return content; } /** * This method returns a list of the children a content has. */ /* public List getContentChildrenVOList(Integer parentContentId) throws ConstraintException, SystemException { String key = "" + parentContentId; logger.info("key:" + key); List cachedChildContentVOList = (List)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = null; beginTransaction(db); try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } */ /** * This method returns a list of the children a content has. */ public List<ContentVO> getContentChildrenVOList(Integer parentContentId, String[] allowedContentTypeIds, Boolean showDeletedItems) throws ConstraintException, SystemException { String allowedContentTypeIdsString = ""; if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) allowedContentTypeIdsString += "_" + allowedContentTypeIds[i]; } String key = "" + parentContentId + allowedContentTypeIdsString + "_" + showDeletedItems; if(logger.isInfoEnabled()) logger.info("key:" + key); List<ContentVO> cachedChildContentVOList = (List<ContentVO>)CacheController.getCachedObject("childContentCache", key); if(cachedChildContentVOList != null) { if(logger.isInfoEnabled()) logger.info("There was an cached childContentVOList:" + cachedChildContentVOList.size()); return cachedChildContentVOList; } Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List childrenVOList = new ArrayList(); beginTransaction(db); Timer t = new Timer(); /* try { Content content = getReadOnlyContentWithId(parentContentId, db); Collection children = content.getChildren(); childrenVOList = ContentController.toVOList(children); System.out.println("childrenVOList under:" + content.getName() + ":" + childrenVOList.size()); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } */ try { String contentTypeINClause = ""; if(allowedContentTypeIds != null && allowedContentTypeIds.length > 0) { contentTypeINClause = " AND content.contentTypeDefinitionId IN LIST ("; for(int i=0; i < allowedContentTypeIds.length; i++) { if(i > 0) contentTypeINClause += ","; contentTypeINClause += "$" + (i+3); } contentTypeINClause += ")"; } String showDeletedItemsClause = " AND content.isDeleted = $2"; String SQL = "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 " + showDeletedItemsClause + contentTypeINClause + " ORDER BY content.contentId"; //System.out.println("SQL:" + SQL); OQLQuery oql = db.getOQLQuery(SQL); //OQLQuery oql = db.getOQLQuery( "SELECT content FROM org.infoglue.cms.entities.content.impl.simple.SmallishContentImpl content WHERE content.parentContentId = $1 ORDER BY content.contentId"); oql.bind(parentContentId); oql.bind(showDeletedItems); if(allowedContentTypeIds != null) { for(int i=0; i < allowedContentTypeIds.length; i++) { System.out.println("allowedContentTypeIds[i]:" + allowedContentTypeIds[i]); oql.bind(allowedContentTypeIds[i]); } } QueryResults results = oql.execute(Database.ReadOnly); while (results.hasMore()) { Content content = (Content)results.next(); childrenVOList.add(content.getValueObject()); } results.close(); oql.close(); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } CacheController.cacheObject("childContentCache", key, childrenVOList); return childrenVOList; } /** * This method returns the contentTypeDefinitionVO which is associated with this content. */ public ContentTypeDefinitionVO getContentTypeDefinition(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); ContentTypeDefinitionVO contentTypeDefinitionVO = null; beginTransaction(db); try { ContentVO smallContentVO = getSmallContentVOWithId(contentId, db); if(smallContentVO != null && smallContentVO.getContentTypeDefinitionId() != null) contentTypeDefinitionVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithId(smallContentVO.getContentTypeDefinitionId(), db); /* Content content = getReadOnlyMediumContentWithId(contentId, db); if(content != null && content.getContentTypeDefinition() != null) contentTypeDefinitionVO = content.getContentTypeDefinition().getValueObject(); */ //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentTypeDefinitionVO; } /** * This method reurns a list of available languages for this content. */ public List getRepositoryLanguages(Integer contentId) throws ConstraintException, SystemException { Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); List languages = null; beginTransaction(db); try { languages = LanguageController.getController().getLanguageVOList(contentId, db); //If any of the validations or setMethods reported an error, we throw them up now before create. ceb.throwIfNotEmpty(); commitTransaction(db); } catch(ConstraintException ce) { logger.warn("An error occurred so we should not complete the transaction:" + ce, ce); rollbackTransaction(db); throw ce; } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return languages; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { result = getBoundContents(db, serviceBindingId); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return result; } /** * This method returns the bound contents based on a servicebinding. */ public static List getBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } public static List getInTransactionBoundContents(Database db, Integer serviceBindingId) throws SystemException, Exception { List result = new ArrayList(); ServiceBinding serviceBinding = ServiceBindingController.getController().getReadOnlyServiceBindingWithId(serviceBindingId, db); //ServiceBinding serviceBinding = ServiceBindingController.getServiceBindingWithId(serviceBindingId, db); if(serviceBinding != null) { ServiceDefinition serviceDefinition = serviceBinding.getServiceDefinition(); if(serviceDefinition != null) { String serviceClassName = serviceDefinition.getClassName(); BaseService service = (BaseService)Class.forName(serviceClassName).newInstance(); HashMap arguments = new HashMap(); arguments.put("method", "selectContentListOnIdList"); List qualifyerList = new ArrayList(); Collection qualifyers = serviceBinding.getBindingQualifyers(); qualifyers = sortQualifyers(qualifyers); Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); HashMap argument = new HashMap(); argument.put(qualifyer.getName(), qualifyer.getValue()); qualifyerList.add(argument); } arguments.put("arguments", qualifyerList); List contents = service.selectMatchingEntities(arguments, db); if(contents != null) { Iterator i = contents.iterator(); while(i.hasNext()) { ContentVO candidate = (ContentVO)i.next(); result.add(candidate); } } } } return result; } /** * This method just sorts the list of qualifyers on sortOrder. */ private static List sortQualifyers(Collection qualifyers) { List sortedQualifyers = new ArrayList(); try { Iterator iterator = qualifyers.iterator(); while(iterator.hasNext()) { Qualifyer qualifyer = (Qualifyer)iterator.next(); int index = 0; Iterator sortedListIterator = sortedQualifyers.iterator(); while(sortedListIterator.hasNext()) { Qualifyer sortedQualifyer = (Qualifyer)sortedListIterator.next(); if(sortedQualifyer.getSortOrder().intValue() > qualifyer.getSortOrder().intValue()) { break; } index++; } sortedQualifyers.add(index, qualifyer); } } catch(Exception e) { logger.warn("The sorting of qualifyers failed:" + e.getMessage(), e); } return sortedQualifyers; } /** * This method returns the contents belonging to a certain repository. */ public List getRepositoryContents(Integer repositoryId, Database db) throws SystemException, Exception { List contents = new ArrayList(); OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.repositoryId = $1 ORDER BY c.contentId"); oql.bind(repositoryId); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contents.add(content); } results.close(); oql.close(); return contents; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator) throws SystemException, Exception { ContentVO contentVO = null; Database db = CastorDatabaseService.getDatabase(); beginTransaction(db); try { contentVO = getContentVOWithPath(repositoryId, path, forceFolders, creator, db); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVO; } /** * Returns the content belonging to the specified repository and with the specified path. * Note! If a folder contains more than one child with a requested name, then one of the children * will be used (non-deterministic). * * Example: * If we have the following repository (id=100): * <root id="1"> * <news id="2"> * <imported id="3"> * <calendar id="4"> * then: * getContentVOWithPath(100, "", true, db) => returns content "1" * getContentVOWithPath(100, "news", true, db) => returns content "2" * getContentVOWithPath(100, "news/imported", true, db) => returns content "3" * getContentVOWithPath(100, "news/other", true, db) => will create a new content with the name "other" with content "2" as parent * getContentVOWithPath(100, "news/other", false, db) => will throw an exception * * @param repositoryId the repository identifier * @param path the path of the content starting from the root of the repository * @param forceFolders if true then non-existing folders will be created; otherwise an exception will be thrown * @param db the database to use */ public ContentVO getContentVOWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { ContentVO content = getRootContent(repositoryId, db).getValueObject(); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; if(!name.equals("")) { final ContentVO childContent = getChildVOWithName(content.getContentId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent.getValueObject(); } } } return content; } public Content getContentWithPath(Integer repositoryId, String path, boolean forceFolders, InfoGluePrincipal creator, Database db) throws SystemException, Exception { Content content = getRootContent(repositoryId, db); final String paths[] = path.split("/"); if(path.equals("")) return content; for(int i=0; i<paths.length; ++i) { final String name = paths[i]; final Content childContent = getChildWithName(content.getId(), name, db); if(childContent != null) content = childContent; else if(childContent == null && !forceFolders) throw new SystemException("There exists no content with the path [" + path + "]."); else { logger.info(" CREATE " + name); ContentVO contentVO = new ContentVO(); contentVO.setIsBranch(Boolean.TRUE); contentVO.setCreatorName(creator.getName()); contentVO.setName(name); Content newContent = create(db, content.getId(), null, repositoryId, contentVO); if(newContent != null) content = newContent; } } return content; } /** * */ private ContentVO getChildVOWithName(Integer parentContentId, String name, Database db) throws Exception { ContentVO contentVO = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE c.parentContentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(Database.ReadOnly); if(results.hasMore()) { MediumContentImpl content = (MediumContentImpl)results.next(); contentVO = content.getValueObject(); } results.close(); oql.close(); return contentVO; } /** * */ private Content getChildWithName(Integer parentContentId, String name, Database db) throws Exception { Content content = null; OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.ContentImpl c WHERE c.parentContent.contentId = $1 AND c.name = $2"); oql.bind(parentContentId); oql.bind(name); QueryResults results = oql.execute(); if(results.hasMore()) { content = (ContentImpl)results.next(); } results.close(); oql.close(); return content; } /** * */ /* private Content getChildWithName(Content content, String name, Database db) { for(Iterator i=content.getChildren().iterator(); i.hasNext(); ) { final Content childContent = (Content) i.next(); if(childContent.getName().equals(name)) return childContent; } return null; } */ /** * Recursive methods to get all contentVersions of a given state under the specified parent content. */ public List getContentVOWithParentRecursive(Integer contentId) throws ConstraintException, SystemException { return getContentVOWithParentRecursive(contentId, new ArrayList()); } private List getContentVOWithParentRecursive(Integer contentId, List resultList) throws ConstraintException, SystemException { // Get the versions of this content. resultList.add(getContentVOWithId(contentId)); // Get the children of this content and do the recursion List childContentList = ContentController.getContentController().getContentChildrenVOList(contentId, null, false); Iterator cit = childContentList.iterator(); while (cit.hasNext()) { ContentVO contentVO = (ContentVO) cit.next(); getContentVOWithParentRecursive(contentVO.getId(), resultList); } return resultList; } public String getContentAttribute(Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId); attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } public String getContentAttribute(Database db, Integer contentId, Integer languageId, String attributeName, boolean useLanguageFallBack) throws Exception { String attribute = "Undefined"; ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId, db); ContentVersionVO contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), languageId, db); if(contentVersionVO == null && useLanguageFallBack) { LanguageVO masterLanguageVO = LanguageController.getController().getMasterLanguage(contentVO.getRepositoryId(), db); contentVersionVO = ContentVersionController.getContentVersionController().getLatestActiveContentVersionVO(contentVO.getId(), masterLanguageVO.getId(), db); } if(contentVersionVO != null) attribute = ContentVersionController.getContentVersionController().getAttributeValue(contentVersionVO, attributeName, false); return attribute; } /** * This is a method that gives the user back an newly initialized ValueObject for this entity that the controller * is handling. */ public BaseEntityVO getNewVO() { return new ContentVO(); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId) throws ConstraintException, SystemException, Bug, Exception { return getContentPath(contentId, false, false); } /** * Returns the path to, and including, the supplied content. * * @param contentId the content to * * @return String the path to, and including, this content "library/library/..." * */ public String getContentPath(Integer contentId, boolean includeRootContent, boolean includeRepositoryName) throws ConstraintException, SystemException, Bug, Exception { StringBuffer sb = new StringBuffer(); ContentVO contentVO = ContentController.getContentController().getContentVOWithId(contentId); sb.insert(0, contentVO.getName()); while (contentVO.getParentContentId() != null) { contentVO = ContentController.getContentController().getContentVOWithId(contentVO.getParentContentId()); if (includeRootContent || contentVO.getParentContentId() != null) { sb.insert(0, contentVO.getName() + "/"); } } if (includeRepositoryName) { RepositoryVO repositoryVO = RepositoryController.getController().getRepositoryVOWithId(contentVO.getRepositoryId()); if(repositoryVO != null) sb.insert(0, repositoryVO.getName() + " - /"); } return sb.toString(); } public List<ContentVO> getUpcomingExpiringContents(int numberOfWeeks) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.SmallContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfWeeks); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } return contentVOList; } public List<ContentVO> getUpcomingExpiringContents(int numberOfDays, InfoGluePrincipal principal, String[] excludedContentTypes) throws Exception { List<ContentVO> contentVOList = new ArrayList<ContentVO>(); Database db = CastorDatabaseService.getDatabase(); ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer(); beginTransaction(db); try { OQLQuery oql = db.getOQLQuery("SELECT c FROM org.infoglue.cms.entities.content.impl.simple.MediumContentImpl c WHERE " + "c.expireDateTime > $1 AND c.expireDateTime < $2 AND c.publishDateTime < $3 AND c.contentVersions.versionModifier = $4"); Calendar now = Calendar.getInstance(); Date currentDate = now.getTime(); oql.bind(currentDate); now.add(Calendar.DAY_OF_YEAR, numberOfDays); Date futureDate = now.getTime(); oql.bind(futureDate); oql.bind(currentDate); oql.bind(principal.getName()); QueryResults results = oql.execute(Database.ReadOnly); while(results.hasMore()) { Content content = (ContentImpl)results.next(); boolean isValid = true; for(int i=0; i<excludedContentTypes.length; i++) { String contentTypeDefinitionNameToExclude = excludedContentTypes[i]; ContentTypeDefinitionVO ctdVO = ContentTypeDefinitionController.getController().getContentTypeDefinitionVOWithName(contentTypeDefinitionNameToExclude, db); if(content.getContentTypeDefinitionId().equals(ctdVO.getId())) { isValid = false; break; } } if(isValid) contentVOList.add(content.getValueObject()); } results.close(); oql.close(); commitTransaction(db); } catch(Exception e) { logger.error("An error occurred so we should not complete the transaction:" + e, e); rollbackTransaction(db); throw new SystemException(e.getMessage()); } System.out.println("contentVOList:" + contentVOList.size()); return contentVOList; } }
diff --git a/src/com/ferg/awful/thread/AwfulThread.java b/src/com/ferg/awful/thread/AwfulThread.java index 713c6e4b..0a5c7fb5 100644 --- a/src/com/ferg/awful/thread/AwfulThread.java +++ b/src/com/ferg/awful/thread/AwfulThread.java @@ -1,280 +1,281 @@ /******************************************************************************** * Copyright (c) 2011, Scott Ferguson * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the software nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY SCOTT FERGUSON ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SCOTT FERGUSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *******************************************************************************/ package com.ferg.awful.thread; import android.os.Parcel; import android.os.Parcelable; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import org.htmlcleaner.TagNode; import org.htmlcleaner.XPatherException; import com.ferg.awful.constants.Constants; import com.ferg.awful.network.NetworkUtils; public class AwfulThread extends AwfulPagedItem implements Parcelable { private static final String TAG = "AwfulThread"; //private static final String THREAD_ROW = "//table[@id='forum']//tr"; //private static final String THREAD_SEEN_ROW = "//tr[@class='thread']"; //private static final String THREAD_TITLE = "//a[@class='thread_title']"; //private static final String THREAD_STICKY = "//td[@class='title title_sticky']"; //private static final String THREAD_ICON = "//td[@class='icon']/img"; //private static final String THREAD_AUTHOR = "//td[@class='author']/a"; //private static final String UNREAD_POSTS = "//a[@class='count']//b"; //private static final String UNREAD_UNDO = "//a[@class='x']"; //private static final String CURRENT_PAGE = "//span[@class='curpage']"; //private static final String LAST_PAGE = "//a[@class='pagenumber']"; //private static final String ALT_TITLE = "//a[@class='bclast']"; private String mThreadId; private String mTitle; private String mAuthor; private boolean mSticky; private String mIcon; private int mUnreadCount; private ArrayList<AwfulPost> mPosts; public AwfulThread() {} public AwfulThread(String aThreadId) { mThreadId = aThreadId; } public AwfulThread(Parcel aAwfulThread) { mThreadId = aAwfulThread.readString(); mTitle = aAwfulThread.readString(); mAuthor = aAwfulThread.readString(); mSticky = aAwfulThread.readInt() == 1 ? true : false; mIcon = aAwfulThread.readString(); mUnreadCount = aAwfulThread.readInt(); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public AwfulThread createFromParcel(Parcel aAwfulThread) { return new AwfulThread(aAwfulThread); } public AwfulThread[] newArray(int aSize) { return new AwfulThread[aSize]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel aDestination, int aFlags) { aDestination.writeString(mThreadId); aDestination.writeString(mTitle); aDestination.writeString(mAuthor); aDestination.writeInt(mSticky ? 1 : 0); aDestination.writeString(mIcon); aDestination.writeInt(mUnreadCount); } public static TagNode getForumThreads(String aForumId) throws Exception { return getForumThreads(aForumId, 0); } public static TagNode getForumThreads(String aForumId, int aPage) throws Exception { HashMap<String, String> params = new HashMap<String, String>(); params.put(Constants.PARAM_FORUM_ID, aForumId); if (aPage != 0) { params.put(Constants.PARAM_PAGE, Integer.toString(aPage)); } return NetworkUtils.get(Constants.FUNCTION_FORUM, params); } public static TagNode getUserCPThreads() throws Exception { return NetworkUtils.get(Constants.FUNCTION_USERCP, null); } public static ArrayList<AwfulThread> parseForumThreads(TagNode aResponse) throws Exception { long startTime = System.currentTimeMillis(); ArrayList<AwfulThread> result = new ArrayList<AwfulThread>(); //Object[] threadObjects = aResponse.evaluateXPath(THREAD_ROW); - TagNode[] threads = aResponse.getElementsByAttValue("class", "thread", true, true); - for(TagNode node : threads){ + TagNode[] threads = aResponse.getElementsByAttValue("id", "forum", true, true); + TagNode[] tbody = threads[0].getElementsByName("tbody", false); + for(TagNode node : tbody[0].getChildTags()){ AwfulThread thread = new AwfulThread(); try { String threadId = node.getAttributeByName("id"); thread.setThreadId(threadId.replaceAll("thread", "")); } catch (NullPointerException e) { // If we can't parse a row, just skip it e.printStackTrace(); continue; } TagNode[] tarThread = node.getElementsByAttValue("class", "thread_title", true, true); TagNode[] tarUser = node.getElementsByAttValue("class", "author", true, true); Object[] nodeList;// = node.evaluateXPath(THREAD_TITLE); if (tarThread.length > 0) { thread.setTitle(((TagNode) tarThread[0]).getText().toString().trim()); } TagNode[] tarSticky = node.getElementsByAttValue("class", "title title_sticky", true, true); if (tarSticky.length > 0) { thread.setSticky(true); } else { thread.setSticky(false); } //nodeList = node.evaluateXPath(THREAD_ICON); TagNode[] tarIcon = node.getElementsByAttValue("class", "icon", true, true); if (tarIcon.length > 0 && tarIcon[0].getChildTags().length >0) { thread.setIcon(tarIcon[0].getChildTags()[0].getAttributeByName("src")); } //nodeList = node.evaluateXPath(THREAD_AUTHOR); if (tarUser.length > 0) { //TagNode authorNode = (TagNode) tarUser[0]; // There's got to be a better way to do this //authorNode.removeChild(authorNode.findElementHavingAttribute("href", false)); thread.setAuthor(tarUser[0].getText().toString().trim()); } //nodeList = node.evaluateXPath(UNREAD_POSTS); TagNode[] tarCount = node.getElementsByAttValue("class", "count", true, true); if (tarCount.length > 0 && tarCount[0].getChildTags().length >0) { thread.setUnreadCount(Integer.parseInt( tarCount[0].getChildTags()[0].getText().toString().trim())); } else { TagNode[] tarXCount = node.getElementsByAttValue("class", "x", true, true); //nodeList = node.evaluateXPath(UNREAD_UNDO); if (tarXCount.length > 0) { thread.setUnreadCount(0); } else { thread.setUnreadCount(-1); } } result.add(thread); } Log.e("AwfulThread", "Process Time: "+(System.currentTimeMillis()-startTime)); return result; } public void getThreadPosts() throws Exception { getThreadPosts(-1); } public void getThreadPosts(int aPage) throws Exception { HashMap<String, String> params = new HashMap<String, String>(); params.put(Constants.PARAM_THREAD_ID, mThreadId); if (aPage == -1) { params.put(Constants.PARAM_GOTO, "newpost"); } else { params.put(Constants.PARAM_PAGE, Integer.toString(aPage)); } TagNode response = NetworkUtils.get(Constants.FUNCTION_THREAD, params); // If we got here from ChromeToPhone the title hasn't been parsed yet, // so grab that now if (mTitle == null) { TagNode[] tarTitle = response.getElementsByAttValue("class", "bclast", true, true); //Object[] titleObject = response.evaluateXPath(ALT_TITLE); if (tarTitle.length > 0) { mTitle = tarTitle[0].getText().toString().trim(); Log.i(TAG, mTitle); } } setPosts(AwfulPost.parsePosts(response)); parsePageNumbers(response); } public String getThreadId() { return mThreadId; } public void setThreadId(String aThreadId) { mThreadId = aThreadId; } public String getTitle() { return mTitle; } public void setTitle(String aTitle) { mTitle = aTitle; } public String getAuthor() { return mAuthor; } public void setAuthor(String aAuthor) { mAuthor = aAuthor; } public String getIcon() { return mIcon; } public void setIcon(String aIcon) { mIcon = aIcon; } public boolean isSticky() { return mSticky; } public void setSticky(boolean aSticky) { mSticky = aSticky; } public int getUnreadCount() { return mUnreadCount; } public void setUnreadCount(int aUnreadCount) { mUnreadCount = aUnreadCount; } public ArrayList<AwfulPost> getPosts() { return mPosts; } public void setPosts(ArrayList<AwfulPost> aPosts) { mPosts = aPosts; } }
true
true
public static ArrayList<AwfulThread> parseForumThreads(TagNode aResponse) throws Exception { long startTime = System.currentTimeMillis(); ArrayList<AwfulThread> result = new ArrayList<AwfulThread>(); //Object[] threadObjects = aResponse.evaluateXPath(THREAD_ROW); TagNode[] threads = aResponse.getElementsByAttValue("class", "thread", true, true); for(TagNode node : threads){ AwfulThread thread = new AwfulThread(); try { String threadId = node.getAttributeByName("id"); thread.setThreadId(threadId.replaceAll("thread", "")); } catch (NullPointerException e) { // If we can't parse a row, just skip it e.printStackTrace(); continue; } TagNode[] tarThread = node.getElementsByAttValue("class", "thread_title", true, true); TagNode[] tarUser = node.getElementsByAttValue("class", "author", true, true); Object[] nodeList;// = node.evaluateXPath(THREAD_TITLE); if (tarThread.length > 0) { thread.setTitle(((TagNode) tarThread[0]).getText().toString().trim()); } TagNode[] tarSticky = node.getElementsByAttValue("class", "title title_sticky", true, true); if (tarSticky.length > 0) { thread.setSticky(true); } else { thread.setSticky(false); } //nodeList = node.evaluateXPath(THREAD_ICON); TagNode[] tarIcon = node.getElementsByAttValue("class", "icon", true, true); if (tarIcon.length > 0 && tarIcon[0].getChildTags().length >0) { thread.setIcon(tarIcon[0].getChildTags()[0].getAttributeByName("src")); } //nodeList = node.evaluateXPath(THREAD_AUTHOR); if (tarUser.length > 0) { //TagNode authorNode = (TagNode) tarUser[0]; // There's got to be a better way to do this //authorNode.removeChild(authorNode.findElementHavingAttribute("href", false)); thread.setAuthor(tarUser[0].getText().toString().trim()); } //nodeList = node.evaluateXPath(UNREAD_POSTS); TagNode[] tarCount = node.getElementsByAttValue("class", "count", true, true); if (tarCount.length > 0 && tarCount[0].getChildTags().length >0) { thread.setUnreadCount(Integer.parseInt( tarCount[0].getChildTags()[0].getText().toString().trim())); } else { TagNode[] tarXCount = node.getElementsByAttValue("class", "x", true, true); //nodeList = node.evaluateXPath(UNREAD_UNDO); if (tarXCount.length > 0) { thread.setUnreadCount(0); } else { thread.setUnreadCount(-1); } } result.add(thread); } Log.e("AwfulThread", "Process Time: "+(System.currentTimeMillis()-startTime)); return result; }
public static ArrayList<AwfulThread> parseForumThreads(TagNode aResponse) throws Exception { long startTime = System.currentTimeMillis(); ArrayList<AwfulThread> result = new ArrayList<AwfulThread>(); //Object[] threadObjects = aResponse.evaluateXPath(THREAD_ROW); TagNode[] threads = aResponse.getElementsByAttValue("id", "forum", true, true); TagNode[] tbody = threads[0].getElementsByName("tbody", false); for(TagNode node : tbody[0].getChildTags()){ AwfulThread thread = new AwfulThread(); try { String threadId = node.getAttributeByName("id"); thread.setThreadId(threadId.replaceAll("thread", "")); } catch (NullPointerException e) { // If we can't parse a row, just skip it e.printStackTrace(); continue; } TagNode[] tarThread = node.getElementsByAttValue("class", "thread_title", true, true); TagNode[] tarUser = node.getElementsByAttValue("class", "author", true, true); Object[] nodeList;// = node.evaluateXPath(THREAD_TITLE); if (tarThread.length > 0) { thread.setTitle(((TagNode) tarThread[0]).getText().toString().trim()); } TagNode[] tarSticky = node.getElementsByAttValue("class", "title title_sticky", true, true); if (tarSticky.length > 0) { thread.setSticky(true); } else { thread.setSticky(false); } //nodeList = node.evaluateXPath(THREAD_ICON); TagNode[] tarIcon = node.getElementsByAttValue("class", "icon", true, true); if (tarIcon.length > 0 && tarIcon[0].getChildTags().length >0) { thread.setIcon(tarIcon[0].getChildTags()[0].getAttributeByName("src")); } //nodeList = node.evaluateXPath(THREAD_AUTHOR); if (tarUser.length > 0) { //TagNode authorNode = (TagNode) tarUser[0]; // There's got to be a better way to do this //authorNode.removeChild(authorNode.findElementHavingAttribute("href", false)); thread.setAuthor(tarUser[0].getText().toString().trim()); } //nodeList = node.evaluateXPath(UNREAD_POSTS); TagNode[] tarCount = node.getElementsByAttValue("class", "count", true, true); if (tarCount.length > 0 && tarCount[0].getChildTags().length >0) { thread.setUnreadCount(Integer.parseInt( tarCount[0].getChildTags()[0].getText().toString().trim())); } else { TagNode[] tarXCount = node.getElementsByAttValue("class", "x", true, true); //nodeList = node.evaluateXPath(UNREAD_UNDO); if (tarXCount.length > 0) { thread.setUnreadCount(0); } else { thread.setUnreadCount(-1); } } result.add(thread); } Log.e("AwfulThread", "Process Time: "+(System.currentTimeMillis()-startTime)); return result; }
diff --git a/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java b/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java index 75da180c8c..311410d096 100644 --- a/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java +++ b/geoserver/web/src/main/java/org/vfny/geoserver/action/MapPreviewAction.java @@ -1,270 +1,272 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, availible at the root * application directory. */ package org.vfny.geoserver.action; import com.vividsolutions.jts.geom.Envelope; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; import org.geoserver.feature.FeatureSourceUtils; import org.geoserver.util.ReaderUtils; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.CRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.NoSuchAuthorityCodeException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import org.vfny.geoserver.global.ConfigurationException; import org.vfny.geoserver.global.CoverageInfo; import org.vfny.geoserver.global.Data; import org.vfny.geoserver.global.FeatureTypeInfo; import org.vfny.geoserver.global.WMS; import org.vfny.geoserver.util.requests.CapabilitiesRequest; import org.vfny.geoserver.wms.servlets.Capabilities; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * <b>MapPreviewAction</b><br> Sep 26, 2005<br> * <b>Purpose:</b><br> * Gathers up all the FeatureTypes in use and returns the informaion to the * .jsp .<br> * It will also generate requests to the WMS "openlayers" output format. <br> * This will communicate to a .jsp and return it three arrays of strings that contain:<br> * - The Featuretype's name<br> * - The DataStore name of the FeatureType<br> * - The bounding box of the FeatureType<br> * To change what data is output to the .jsp, you must change <b>struts-config.xml</b>.<br> * Look for the line:<br> * &lt;form-bean <br> * name="mapPreviewForm"<br> * * @author Brent Owens (The Open Planning Project) * @version */ public class MapPreviewAction extends GeoServerAction { /* (non-Javadoc) * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ArrayList dsList = new ArrayList(); ArrayList ftList = new ArrayList(); ArrayList bboxList = new ArrayList(); ArrayList srsList = new ArrayList(); ArrayList ftnsList = new ArrayList(); ArrayList widthList = new ArrayList(); ArrayList heightList = new ArrayList(); // 1) get the capabilities info so we can find out our feature types WMS wms = getWMS(request); Capabilities caps = new Capabilities(wms); CapabilitiesRequest capRequest = new CapabilitiesRequest("WMS", caps); capRequest.setHttpServletRequest(request); Data catalog = wms.getData(); List ftypes = new ArrayList(catalog.getFeatureTypeInfos().values()); Collections.sort(ftypes, new FeatureTypeInfoNameComparator()); List ctypes = new ArrayList(catalog.getCoverageInfos().values()); Collections.sort(ctypes, new CoverageInfoNameComparator()); // 2) delete any existing generated files in the generation directory ServletContext sc = request.getSession().getServletContext(); //File rootDir = GeoserverDataDirectory.getGeoserverDataDirectory(sc); //File previewDir = new File(sc.getRealPath("data/generated")); if (sc.getRealPath("preview") == null) { //There's a problem here, since we can't get a real path for the "preview" directory. //On tomcat this happens when "unpackWars=false" is set for this context. throw new RuntimeException( "Couldn't populate preview directory...is the war running in unpacked mode?"); } File previewDir = new File(sc.getRealPath("preview")); //File previewDir = new File(rootDir, "data/generated"); if (!previewDir.exists()) { previewDir.mkdirs(); } // We need to create a 4326 CRS for comparison to layer's crs CoordinateReferenceSystem latLonCrs = null; try { // get the CRS object for lat/lon 4326 latLonCrs = CRS.decode("EPSG:" + 4326); } catch (NoSuchAuthorityCodeException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } catch (FactoryException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } // 3) Go through each *FeatureType* and collect information && write out config files for (Iterator it = ftypes.iterator(); it.hasNext();) { FeatureTypeInfo layer = (FeatureTypeInfo) it.next(); if (!layer.isEnabled() || layer.isGeometryless()) { continue; // if it isn't enabled, move to the next layer } CoordinateReferenceSystem layerCrs = layer.getDeclaredCRS(); /* A quick and efficient way to grab the bounding box is to get it * from the featuretype info where the lat/lon bbox is loaded * from the DTO. We do this with layer.getLatLongBoundingBox(). * We need to reproject the bounding box from lat/lon to the layer crs * for display */ Envelope orig_bbox = layer.getLatLongBoundingBox(); if ((orig_bbox.getWidth() == 0) || (orig_bbox.getHeight() == 0)) { orig_bbox.expandBy(0.1); } ReferencedEnvelope bbox = new ReferencedEnvelope(orig_bbox, latLonCrs); if (!CRS.equalsIgnoreMetadata(layerCrs, latLonCrs)) { try { // reproject the bbox to the layer crs bbox = bbox.transform(layerCrs, true); } catch (TransformException e) { e.printStackTrace(); } catch (FactoryException e) { e.printStackTrace(); } } // we now have a bounding box in the same CRS as the layer if ((bbox.getWidth() == 0) || (bbox.getHeight() == 0)) { bbox.expandBy(0.1); } if (layer.isEnabled()) { // prepare strings for web output ftList.add(layer.getNameSpace().getPrefix() + "_" + layer.getFeatureType().getTypeName()); // FeatureType name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + layer.getFeatureType().getTypeName()); dsList.add(layer.getDataStoreInfo().getId()); // DataStore info // bounding box of the FeatureType - bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," - + bbox.getMaxY()); - srsList.add("EPSG:" + layer.getSRS()); + // expand bbox by 5% to allow large symbolizers to fit the map + bbox.expandBy(bbox.getWidth() / 20, bbox.getHeight() / 20); + bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + + bbox.getMaxY()); + srsList.add("EPSG:" + layer.getSRS()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 3.5) Go through each *Coverage* and collect its info for (Iterator it = ctypes.iterator(); it.hasNext();) { CoverageInfo layer = (CoverageInfo) it.next(); // upper right corner? lower left corner? Who knows?! Better naming conventions needed guys. double[] lowerLeft = layer.getEnvelope().getLowerCorner().getCoordinates(); double[] upperRight = layer.getEnvelope().getUpperCorner().getCoordinates(); Envelope bbox = new Envelope(lowerLeft[0], upperRight[0], lowerLeft[1], upperRight[1]); if (layer.isEnabled()) { // prepare strings for web output String shortLayerName = layer.getName().split(":")[1]; // we don't want the namespace prefix ftList.add(layer.getNameSpace().getPrefix() + "_" + shortLayerName); // Coverage name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + shortLayerName); dsList.add(layer.getFormatInfo().getId()); // DataStore info // bounding box of the Coverage bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add(layer.getSrsName()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 4) send off gathered information to the .jsp DynaActionForm myForm = (DynaActionForm) form; myForm.set("DSNameList", dsList.toArray(new String[dsList.size()])); myForm.set("FTNameList", ftList.toArray(new String[ftList.size()])); myForm.set("BBoxList", bboxList.toArray(new String[bboxList.size()])); myForm.set("SRSList", srsList.toArray(new String[srsList.size()])); myForm.set("WidthList", widthList.toArray(new String[widthList.size()])); myForm.set("HeightList", heightList.toArray(new String[heightList.size()])); myForm.set("FTNamespaceList", ftnsList.toArray(new String[ftnsList.size()])); return mapping.findForward("success"); } private int[] getMapWidthHeight(Envelope bbox) { int width; int height; double ratio = bbox.getHeight() / bbox.getWidth(); if (ratio < 1) { width = 750; height = (int) Math.round(750 * ratio); } else { width = (int) Math.round(550 / ratio); height = 550; } // make sure we reach some minimal dimensions (300 pixels is more or less // the height of the zoom bar) if (width < 300) { width = 300; } if (height < 300) { height = 300; } // add 50 pixels horizontally to account for the zoom bar return new int[] { width + 50, height }; } private static class FeatureTypeInfoNameComparator implements Comparator { public int compare(Object o1, Object o2) { FeatureTypeInfo ft1 = (FeatureTypeInfo) o1; FeatureTypeInfo ft2 = (FeatureTypeInfo) o2; String ft1Name = ft1.getNameSpace().getPrefix() + ft1.getName(); String ft2Name = ft2.getNameSpace().getPrefix() + ft2.getName(); return ft1Name.compareTo(ft2Name); } } private static class CoverageInfoNameComparator implements Comparator { public int compare(Object o1, Object o2) { CoverageInfo c1 = (CoverageInfo) o1; CoverageInfo c2 = (CoverageInfo) o2; String ft1Name = c1.getNameSpace().getPrefix() + c1.getName(); String ft2Name = c2.getNameSpace().getPrefix() + c2.getName(); return ft1Name.compareTo(ft2Name); } } }
true
true
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ArrayList dsList = new ArrayList(); ArrayList ftList = new ArrayList(); ArrayList bboxList = new ArrayList(); ArrayList srsList = new ArrayList(); ArrayList ftnsList = new ArrayList(); ArrayList widthList = new ArrayList(); ArrayList heightList = new ArrayList(); // 1) get the capabilities info so we can find out our feature types WMS wms = getWMS(request); Capabilities caps = new Capabilities(wms); CapabilitiesRequest capRequest = new CapabilitiesRequest("WMS", caps); capRequest.setHttpServletRequest(request); Data catalog = wms.getData(); List ftypes = new ArrayList(catalog.getFeatureTypeInfos().values()); Collections.sort(ftypes, new FeatureTypeInfoNameComparator()); List ctypes = new ArrayList(catalog.getCoverageInfos().values()); Collections.sort(ctypes, new CoverageInfoNameComparator()); // 2) delete any existing generated files in the generation directory ServletContext sc = request.getSession().getServletContext(); //File rootDir = GeoserverDataDirectory.getGeoserverDataDirectory(sc); //File previewDir = new File(sc.getRealPath("data/generated")); if (sc.getRealPath("preview") == null) { //There's a problem here, since we can't get a real path for the "preview" directory. //On tomcat this happens when "unpackWars=false" is set for this context. throw new RuntimeException( "Couldn't populate preview directory...is the war running in unpacked mode?"); } File previewDir = new File(sc.getRealPath("preview")); //File previewDir = new File(rootDir, "data/generated"); if (!previewDir.exists()) { previewDir.mkdirs(); } // We need to create a 4326 CRS for comparison to layer's crs CoordinateReferenceSystem latLonCrs = null; try { // get the CRS object for lat/lon 4326 latLonCrs = CRS.decode("EPSG:" + 4326); } catch (NoSuchAuthorityCodeException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } catch (FactoryException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } // 3) Go through each *FeatureType* and collect information && write out config files for (Iterator it = ftypes.iterator(); it.hasNext();) { FeatureTypeInfo layer = (FeatureTypeInfo) it.next(); if (!layer.isEnabled() || layer.isGeometryless()) { continue; // if it isn't enabled, move to the next layer } CoordinateReferenceSystem layerCrs = layer.getDeclaredCRS(); /* A quick and efficient way to grab the bounding box is to get it * from the featuretype info where the lat/lon bbox is loaded * from the DTO. We do this with layer.getLatLongBoundingBox(). * We need to reproject the bounding box from lat/lon to the layer crs * for display */ Envelope orig_bbox = layer.getLatLongBoundingBox(); if ((orig_bbox.getWidth() == 0) || (orig_bbox.getHeight() == 0)) { orig_bbox.expandBy(0.1); } ReferencedEnvelope bbox = new ReferencedEnvelope(orig_bbox, latLonCrs); if (!CRS.equalsIgnoreMetadata(layerCrs, latLonCrs)) { try { // reproject the bbox to the layer crs bbox = bbox.transform(layerCrs, true); } catch (TransformException e) { e.printStackTrace(); } catch (FactoryException e) { e.printStackTrace(); } } // we now have a bounding box in the same CRS as the layer if ((bbox.getWidth() == 0) || (bbox.getHeight() == 0)) { bbox.expandBy(0.1); } if (layer.isEnabled()) { // prepare strings for web output ftList.add(layer.getNameSpace().getPrefix() + "_" + layer.getFeatureType().getTypeName()); // FeatureType name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + layer.getFeatureType().getTypeName()); dsList.add(layer.getDataStoreInfo().getId()); // DataStore info // bounding box of the FeatureType bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add("EPSG:" + layer.getSRS()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 3.5) Go through each *Coverage* and collect its info for (Iterator it = ctypes.iterator(); it.hasNext();) { CoverageInfo layer = (CoverageInfo) it.next(); // upper right corner? lower left corner? Who knows?! Better naming conventions needed guys. double[] lowerLeft = layer.getEnvelope().getLowerCorner().getCoordinates(); double[] upperRight = layer.getEnvelope().getUpperCorner().getCoordinates(); Envelope bbox = new Envelope(lowerLeft[0], upperRight[0], lowerLeft[1], upperRight[1]); if (layer.isEnabled()) { // prepare strings for web output String shortLayerName = layer.getName().split(":")[1]; // we don't want the namespace prefix ftList.add(layer.getNameSpace().getPrefix() + "_" + shortLayerName); // Coverage name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + shortLayerName); dsList.add(layer.getFormatInfo().getId()); // DataStore info // bounding box of the Coverage bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add(layer.getSrsName()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 4) send off gathered information to the .jsp DynaActionForm myForm = (DynaActionForm) form; myForm.set("DSNameList", dsList.toArray(new String[dsList.size()])); myForm.set("FTNameList", ftList.toArray(new String[ftList.size()])); myForm.set("BBoxList", bboxList.toArray(new String[bboxList.size()])); myForm.set("SRSList", srsList.toArray(new String[srsList.size()])); myForm.set("WidthList", widthList.toArray(new String[widthList.size()])); myForm.set("HeightList", heightList.toArray(new String[heightList.size()])); myForm.set("FTNamespaceList", ftnsList.toArray(new String[ftnsList.size()])); return mapping.findForward("success"); }
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ArrayList dsList = new ArrayList(); ArrayList ftList = new ArrayList(); ArrayList bboxList = new ArrayList(); ArrayList srsList = new ArrayList(); ArrayList ftnsList = new ArrayList(); ArrayList widthList = new ArrayList(); ArrayList heightList = new ArrayList(); // 1) get the capabilities info so we can find out our feature types WMS wms = getWMS(request); Capabilities caps = new Capabilities(wms); CapabilitiesRequest capRequest = new CapabilitiesRequest("WMS", caps); capRequest.setHttpServletRequest(request); Data catalog = wms.getData(); List ftypes = new ArrayList(catalog.getFeatureTypeInfos().values()); Collections.sort(ftypes, new FeatureTypeInfoNameComparator()); List ctypes = new ArrayList(catalog.getCoverageInfos().values()); Collections.sort(ctypes, new CoverageInfoNameComparator()); // 2) delete any existing generated files in the generation directory ServletContext sc = request.getSession().getServletContext(); //File rootDir = GeoserverDataDirectory.getGeoserverDataDirectory(sc); //File previewDir = new File(sc.getRealPath("data/generated")); if (sc.getRealPath("preview") == null) { //There's a problem here, since we can't get a real path for the "preview" directory. //On tomcat this happens when "unpackWars=false" is set for this context. throw new RuntimeException( "Couldn't populate preview directory...is the war running in unpacked mode?"); } File previewDir = new File(sc.getRealPath("preview")); //File previewDir = new File(rootDir, "data/generated"); if (!previewDir.exists()) { previewDir.mkdirs(); } // We need to create a 4326 CRS for comparison to layer's crs CoordinateReferenceSystem latLonCrs = null; try { // get the CRS object for lat/lon 4326 latLonCrs = CRS.decode("EPSG:" + 4326); } catch (NoSuchAuthorityCodeException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } catch (FactoryException e) { String msg = "Error looking up SRS for EPSG: " + 4326 + ":" + e.getLocalizedMessage(); LOGGER.warning(msg); } // 3) Go through each *FeatureType* and collect information && write out config files for (Iterator it = ftypes.iterator(); it.hasNext();) { FeatureTypeInfo layer = (FeatureTypeInfo) it.next(); if (!layer.isEnabled() || layer.isGeometryless()) { continue; // if it isn't enabled, move to the next layer } CoordinateReferenceSystem layerCrs = layer.getDeclaredCRS(); /* A quick and efficient way to grab the bounding box is to get it * from the featuretype info where the lat/lon bbox is loaded * from the DTO. We do this with layer.getLatLongBoundingBox(). * We need to reproject the bounding box from lat/lon to the layer crs * for display */ Envelope orig_bbox = layer.getLatLongBoundingBox(); if ((orig_bbox.getWidth() == 0) || (orig_bbox.getHeight() == 0)) { orig_bbox.expandBy(0.1); } ReferencedEnvelope bbox = new ReferencedEnvelope(orig_bbox, latLonCrs); if (!CRS.equalsIgnoreMetadata(layerCrs, latLonCrs)) { try { // reproject the bbox to the layer crs bbox = bbox.transform(layerCrs, true); } catch (TransformException e) { e.printStackTrace(); } catch (FactoryException e) { e.printStackTrace(); } } // we now have a bounding box in the same CRS as the layer if ((bbox.getWidth() == 0) || (bbox.getHeight() == 0)) { bbox.expandBy(0.1); } if (layer.isEnabled()) { // prepare strings for web output ftList.add(layer.getNameSpace().getPrefix() + "_" + layer.getFeatureType().getTypeName()); // FeatureType name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + layer.getFeatureType().getTypeName()); dsList.add(layer.getDataStoreInfo().getId()); // DataStore info // bounding box of the FeatureType // expand bbox by 5% to allow large symbolizers to fit the map bbox.expandBy(bbox.getWidth() / 20, bbox.getHeight() / 20); bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add("EPSG:" + layer.getSRS()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 3.5) Go through each *Coverage* and collect its info for (Iterator it = ctypes.iterator(); it.hasNext();) { CoverageInfo layer = (CoverageInfo) it.next(); // upper right corner? lower left corner? Who knows?! Better naming conventions needed guys. double[] lowerLeft = layer.getEnvelope().getLowerCorner().getCoordinates(); double[] upperRight = layer.getEnvelope().getUpperCorner().getCoordinates(); Envelope bbox = new Envelope(lowerLeft[0], upperRight[0], lowerLeft[1], upperRight[1]); if (layer.isEnabled()) { // prepare strings for web output String shortLayerName = layer.getName().split(":")[1]; // we don't want the namespace prefix ftList.add(layer.getNameSpace().getPrefix() + "_" + shortLayerName); // Coverage name ftnsList.add(layer.getNameSpace().getPrefix() + ":" + shortLayerName); dsList.add(layer.getFormatInfo().getId()); // DataStore info // bounding box of the Coverage bboxList.add(bbox.getMinX() + "," + bbox.getMinY() + "," + bbox.getMaxX() + "," + bbox.getMaxY()); srsList.add(layer.getSrsName()); int[] imageBox = getMapWidthHeight(bbox); widthList.add(String.valueOf(imageBox[0])); heightList.add(String.valueOf(imageBox[1])); } } // 4) send off gathered information to the .jsp DynaActionForm myForm = (DynaActionForm) form; myForm.set("DSNameList", dsList.toArray(new String[dsList.size()])); myForm.set("FTNameList", ftList.toArray(new String[ftList.size()])); myForm.set("BBoxList", bboxList.toArray(new String[bboxList.size()])); myForm.set("SRSList", srsList.toArray(new String[srsList.size()])); myForm.set("WidthList", widthList.toArray(new String[widthList.size()])); myForm.set("HeightList", heightList.toArray(new String[heightList.size()])); myForm.set("FTNamespaceList", ftnsList.toArray(new String[ftnsList.size()])); return mapping.findForward("success"); }
diff --git a/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java b/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java index e35f9fd55..7d072aa05 100644 --- a/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java +++ b/TFC_Shared/src/TFC/Containers/ContainerTerraForge.java @@ -1,239 +1,238 @@ package TFC.Containers; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.ICrafting; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import TFC.Core.HeatManager; import TFC.Items.ItemOre; import TFC.TileEntities.TileEntityForge; public class ContainerTerraForge extends ContainerTFC { private TileEntityForge forge; private int coolTime; private int freezeTime; private int itemFreezeTime; private float firetemp; public ContainerTerraForge(InventoryPlayer inventoryplayer, TileEntityForge tileentityforge, World world, int x, int y, int z) { forge = tileentityforge; coolTime = 0; freezeTime = 0; itemFreezeTime = 0; //Input slot addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 0, 44, 8)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 1, 62, 26)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 2, 80, 44)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 3, 98, 26)); addSlotToContainer(new SlotForge(inventoryplayer.player,tileentityforge, 4, 116, 8)); //fuel stack addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 5, 44, 26)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 6, 62, 44)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 7, 80, 62)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 8, 98, 44)); addSlotToContainer(new SlotForgeFuel(inventoryplayer.player, tileentityforge, 9, 116, 26)); //Storage slot addSlotToContainer(new Slot(tileentityforge, 10, 152, 8)); addSlotToContainer(new Slot(tileentityforge, 11, 152, 26)); addSlotToContainer(new Slot(tileentityforge, 12, 152, 44)); addSlotToContainer(new Slot(tileentityforge, 13, 152, 62)); for(int i = 0; i < 3; i++) { for(int k = 0; k < 9; k++) { addSlotToContainer(new Slot(inventoryplayer, k + i * 9 + 9, 8 + k * 18, 84 + i * 18)); } } for(int j = 0; j < 9; j++) { addSlotToContainer(new Slot(inventoryplayer, j, 8 + j * 18, 142)); } } @Override public boolean canInteractWith(EntityPlayer entityplayer) { return true; } @Override public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { Slot slot = (Slot)inventorySlots.get(i); Slot[] slotinput = {(Slot)inventorySlots.get(2), (Slot)inventorySlots.get(1), (Slot)inventorySlots.get(3), (Slot)inventorySlots.get(0), (Slot)inventorySlots.get(4)}; Slot[] slotstorage = {(Slot)inventorySlots.get(10), (Slot)inventorySlots.get(11), (Slot)inventorySlots.get(12), (Slot)inventorySlots.get(13)}; Slot[] slotfuel = {(Slot)inventorySlots.get(7), (Slot)inventorySlots.get(6), (Slot)inventorySlots.get(8), (Slot)inventorySlots.get(5), (Slot)inventorySlots.get(9)}; HeatManager manager = HeatManager.getInstance(); if(slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); if(i <= 13) { - if(!entityplayer.inventory.addItemStackToInventory(itemstack1.copy())) + if(!this.mergeItemStack(itemstack1, 14, this.inventorySlots.size(), true)) { return null; } - slot.putStack(null); } else { if(itemstack1.itemID == Item.coal.itemID) { int j = 0; while(j < 5) { if(slotfuel[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotfuel[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else if(!(itemstack1.getItem() instanceof ItemOre) && manager.findMatchingIndex(itemstack1) != null) { int j = 0; while(j < 5) { if(slotinput[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotinput[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else { int j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } if(itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return null; } @Override public void detectAndSendChanges() { for (int var1 = 0; var1 < this.inventorySlots.size(); ++var1) { ItemStack var2 = ((Slot)this.inventorySlots.get(var1)).getStack(); ItemStack var3 = (ItemStack)this.inventoryItemStacks.get(var1); if (!ItemStack.areItemStacksEqual(var3, var2)) { var3 = var2 == null ? null : var2.copy(); this.inventoryItemStacks.set(var1, var3); for (int var4 = 0; var4 < this.crafters.size(); ++var4) { ((ICrafting)this.crafters.get(var4)).sendSlotContents(this, var1, var3); } } } for (int var1 = 0; var1 < this.crafters.size(); ++var1) { ICrafting var2 = (ICrafting)this.crafters.get(var1); if (this.firetemp != this.forge.fireTemperature) { var2.sendProgressBarUpdate(this, 0, (int)this.forge.fireTemperature); } } firetemp = this.forge.fireTemperature; } @Override public void updateProgressBar(int par1, int par2) { if (par1 == 0) { this.forge.fireTemperature = par2; } } }
false
true
public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { Slot slot = (Slot)inventorySlots.get(i); Slot[] slotinput = {(Slot)inventorySlots.get(2), (Slot)inventorySlots.get(1), (Slot)inventorySlots.get(3), (Slot)inventorySlots.get(0), (Slot)inventorySlots.get(4)}; Slot[] slotstorage = {(Slot)inventorySlots.get(10), (Slot)inventorySlots.get(11), (Slot)inventorySlots.get(12), (Slot)inventorySlots.get(13)}; Slot[] slotfuel = {(Slot)inventorySlots.get(7), (Slot)inventorySlots.get(6), (Slot)inventorySlots.get(8), (Slot)inventorySlots.get(5), (Slot)inventorySlots.get(9)}; HeatManager manager = HeatManager.getInstance(); if(slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); if(i <= 13) { if(!entityplayer.inventory.addItemStackToInventory(itemstack1.copy())) { return null; } slot.putStack(null); } else { if(itemstack1.itemID == Item.coal.itemID) { int j = 0; while(j < 5) { if(slotfuel[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotfuel[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else if(!(itemstack1.getItem() instanceof ItemOre) && manager.findMatchingIndex(itemstack1) != null) { int j = 0; while(j < 5) { if(slotinput[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotinput[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else { int j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } if(itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return null; }
public ItemStack transferStackInSlot(EntityPlayer entityplayer, int i) { Slot slot = (Slot)inventorySlots.get(i); Slot[] slotinput = {(Slot)inventorySlots.get(2), (Slot)inventorySlots.get(1), (Slot)inventorySlots.get(3), (Slot)inventorySlots.get(0), (Slot)inventorySlots.get(4)}; Slot[] slotstorage = {(Slot)inventorySlots.get(10), (Slot)inventorySlots.get(11), (Slot)inventorySlots.get(12), (Slot)inventorySlots.get(13)}; Slot[] slotfuel = {(Slot)inventorySlots.get(7), (Slot)inventorySlots.get(6), (Slot)inventorySlots.get(8), (Slot)inventorySlots.get(5), (Slot)inventorySlots.get(9)}; HeatManager manager = HeatManager.getInstance(); if(slot != null && slot.getHasStack()) { ItemStack itemstack1 = slot.getStack(); if(i <= 13) { if(!this.mergeItemStack(itemstack1, 14, this.inventorySlots.size(), true)) { return null; } } else { if(itemstack1.itemID == Item.coal.itemID) { int j = 0; while(j < 5) { if(slotfuel[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotfuel[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else if(!(itemstack1.getItem() instanceof ItemOre) && manager.findMatchingIndex(itemstack1) != null) { int j = 0; while(j < 5) { if(slotinput[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotinput[j].putStack(stack); itemstack1.stackSize--; j = -1; break; } } if (j > 0) { j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } else { int j = 0; while(j < 4) { if(slotstorage[j].getHasStack()) { j++; } else { ItemStack stack = itemstack1.copy(); stack.stackSize = 1; slotstorage[j].putStack(stack); itemstack1.stackSize--; break; } } } } if(itemstack1.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return null; }
diff --git a/seqware-queryengine-webservice/src/test/java/com/github/seqware/queryengine/system/rest/resources/ReadSetResourceTest.java b/seqware-queryengine-webservice/src/test/java/com/github/seqware/queryengine/system/rest/resources/ReadSetResourceTest.java index aea01560..27bdea4a 100644 --- a/seqware-queryengine-webservice/src/test/java/com/github/seqware/queryengine/system/rest/resources/ReadSetResourceTest.java +++ b/seqware-queryengine-webservice/src/test/java/com/github/seqware/queryengine/system/rest/resources/ReadSetResourceTest.java @@ -1,181 +1,181 @@ package com.github.seqware.queryengine.system.rest.resources; import static org.junit.Assert.assertEquals; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.github.seqware.queryengine.model.ReadSet; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; public class ReadSetResourceTest { public static String setKey; public static String tagSetKey; public ReadSetResourceTest() { } @BeforeClass public static void setUpClass() { //Create a Test ReadSet Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset" ); String readSet = "{" + "\"readSetName\": \"ReadSetResourceTest\"}" + "}"; ClientResponse response = webResource.type("application/json").post(ClientResponse.class, readSet); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); String output = response.getEntity(String.class); setKey = extractRowKey(output); client.destroy(); //Create a TagSet for this test - WebResource webResource2 = client.resource(WEBSERVICE_URL + "tagset"); + WebResource webResource2 = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "tagset"); String tagset = "{\n" + " \"name\": \"TestReferenceSetTagSet\"\n" + "}"; ClientResponse response2 = webResource2.type("application/json").post(ClientResponse.class, tagset); Assert.assertTrue("Request failed: " + response2.getStatus(), response2.getStatus() == 200); String output2 = response2.getEntity(String.class); tagSetKey = extractRowKey(output2); } @AfterClass public static void tearDownClass() { Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/" + setKey); webResource.delete(); WebResource webResource2 = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "tagset/" + tagSetKey); webResource2.delete(); client.destroy(); } @Before public void setUp() { } @After public void tearDown() { } @Test public void testGetClassName() { ReadSetResource instance = new ReadSetResource(); String expResult = "ReadSet"; String result = instance.getClassName(); assertEquals(expResult, result); } /** * Test of getModelClass method, of class ReadSetResource. */ @Test public void testGetModelClass() { ReadSetResource instance = new ReadSetResource(); Class expResult = ReadSet.class; Class result = instance.getModelClass(); assertEquals(expResult, result); } //GET readset @Test public void testGetReadSets() { Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset"); ClientResponse response = webResource.type("application/json").get(ClientResponse.class); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); client.destroy(); } //GET readset/{sgid} @Test public void testGetReadSet() { Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/" + setKey); ClientResponse response = webResource.type("application/json").get(ClientResponse.class); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); client.destroy(); } //PUT readset/{sgid} //DELETE readset/{sgid} @Test public void testPutReadSet() { Client client = Client.create(); String readset = "{\"readSetName\": \"TestPutReadSet\"}"; WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/"); ClientResponse response = webResource.type("application/json").post(ClientResponse.class, readset); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); String rowKey = extractRowKey(response.getEntity(String.class)); WebResource webResource2 = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/" + rowKey); String put = "{\"readSetName\": \"ChangedReadSet\"}"; ClientResponse response2 = webResource2.type("application/json").put(ClientResponse.class, put); Assert.assertTrue("Request failed: " + response2.getStatus(), response2.getStatus() == 200); webResource2.delete(); client.destroy(); } //GET readset/{sgid}/tags @Test public void testGetTags() { Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/" + setKey + "/tags"); ClientResponse response = webResource.type("application/json").get(ClientResponse.class); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); client.destroy(); } //GET readset/{sgid}/version @Test public void testGetVersion() { Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/" + setKey + "/version"); ClientResponse response = webResource.type("application/json").get(ClientResponse.class); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); client.destroy(); } //GET readset/{sgid}/permissions @Test public void testGetPermissions() { Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/" + setKey + "/permissions"); ClientResponse response = webResource.type("application/json").get(ClientResponse.class); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); client.destroy(); } //PUT readset/{sgid}/tag //GET readset/tags @Test public void testPutTag() { Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/" + setKey + "/tag?tagset_id=" + tagSetKey + "&key=test"); ClientResponse response = webResource.type("application/json").put(ClientResponse.class); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); WebResource webResource2 = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset/tags?tagset_id=" + tagSetKey + "&key=test"); ClientResponse response2 = webResource2.type("application/json").get(ClientResponse.class); Assert.assertTrue("Request failed: " + response2.getStatus(), response2.getStatus() == 200); client.destroy(); } protected static String extractRowKey(String output) { Pattern pattern = Pattern.compile("rowKey\":\"(.*?)\""); Matcher matcher = pattern.matcher(output); matcher.find(); String rowkey = matcher.group(1); return rowkey; } }
true
true
public static void setUpClass() { //Create a Test ReadSet Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset" ); String readSet = "{" + "\"readSetName\": \"ReadSetResourceTest\"}" + "}"; ClientResponse response = webResource.type("application/json").post(ClientResponse.class, readSet); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); String output = response.getEntity(String.class); setKey = extractRowKey(output); client.destroy(); //Create a TagSet for this test WebResource webResource2 = client.resource(WEBSERVICE_URL + "tagset"); String tagset = "{\n" + " \"name\": \"TestReferenceSetTagSet\"\n" + "}"; ClientResponse response2 = webResource2.type("application/json").post(ClientResponse.class, tagset); Assert.assertTrue("Request failed: " + response2.getStatus(), response2.getStatus() == 200); String output2 = response2.getEntity(String.class); tagSetKey = extractRowKey(output2); }
public static void setUpClass() { //Create a Test ReadSet Client client = Client.create(); WebResource webResource = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "readset" ); String readSet = "{" + "\"readSetName\": \"ReadSetResourceTest\"}" + "}"; ClientResponse response = webResource.type("application/json").post(ClientResponse.class, readSet); Assert.assertTrue("Request failed: " + response.getStatus(), response.getStatus() == 200); String output = response.getEntity(String.class); setKey = extractRowKey(output); client.destroy(); //Create a TagSet for this test WebResource webResource2 = client.resource(QEWSResourceTestSuite.WEBSERVICE_URL + "tagset"); String tagset = "{\n" + " \"name\": \"TestReferenceSetTagSet\"\n" + "}"; ClientResponse response2 = webResource2.type("application/json").post(ClientResponse.class, tagset); Assert.assertTrue("Request failed: " + response2.getStatus(), response2.getStatus() == 200); String output2 = response2.getEntity(String.class); tagSetKey = extractRowKey(output2); }
diff --git a/src/main/com/trendrr/oss/taskprocessor/TaskProcessor.java b/src/main/com/trendrr/oss/taskprocessor/TaskProcessor.java index 85f99eb..3b3cfd0 100644 --- a/src/main/com/trendrr/oss/taskprocessor/TaskProcessor.java +++ b/src/main/com/trendrr/oss/taskprocessor/TaskProcessor.java @@ -1,211 +1,211 @@ /** * */ package com.trendrr.oss.taskprocessor; import java.util.Comparator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.trendrr.oss.FileCache; import com.trendrr.oss.PriorityUpdateQueue; import com.trendrr.oss.concurrent.LazyInitObject; import com.trendrr.oss.executionreport.ExecutionReport; import com.trendrr.oss.executionreport.ExecutionReportIncrementor; import com.trendrr.oss.executionreport.ExecutionSubReport; import com.trendrr.oss.taskprocessor.Task.ASYNCH; /** * @author Dustin Norlander * @created Sep 24, 2012 * */ public class TaskProcessor { protected static Log log = LogFactory.getLog(TaskProcessor.class); static class TaskProcessorThreadFactory implements ThreadFactory { static final AtomicInteger poolNumber = new AtomicInteger(1); final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix; TaskProcessorThreadFactory(String name) { SecurityManager s = System.getSecurityManager(); group = (s != null)? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "TP-" + name +"-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (t.isDaemon()) t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } } static LazyInitObject<AsynchTaskRegistery> asynchTasks = new LazyInitObject<AsynchTaskRegistery>() { @Override public AsynchTaskRegistery init() { AsynchTaskRegistery reg = new AsynchTaskRegistery(); reg.start(); return reg; } }; protected ExecutorService threadPool = null; protected String name; protected TaskCallback callback; //example threadpool, blocks when queue is full. // ExecutorService threadPool = new ThreadPoolExecutor( // 1, // core size // 30, // max size // 130, // idle timeout // TimeUnit.SECONDS, // new ArrayBlockingQueue<Runnable>(30), // queue with a size // new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. // ); /** * creates a new TaskProcessor with a new executorService * ExecutorService threadPool = new ThreadPoolExecutor( 1, // core size numThreads, // max size 130, // idle timeout TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. ); * * @param name * @param callback * @param numThreads */ public static TaskProcessor defaultInstance(String name, TaskCallback callback, int numThreads) { ThreadPoolExecutor threadPool = new ThreadPoolExecutor( - 1, // core size + numThreads, // core size numThreads, // max size 130, // idle timeout TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size new TaskProcessorThreadFactory(name), new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. ); return new TaskProcessor(name, callback, threadPool); } /** * creates a new task processor. * * * * * @param name The name of this processor. used for execution reporting. * @param callback Methods called for every task execution. this callback is called before the callback specified in the task. can be null. * @param executor the executor */ public TaskProcessor(String name, TaskCallback callback, ExecutorService executor) { this.threadPool = executor; this.name = name; this.callback = callback; } /** * submits a task for execution. * @param task */ public void submitTask(Task task) { if (task.getSubmitted() == null) { task.submitted(); } task.setProcessor(this); //add to the executor service.. TaskFilterRunner runner = new TaskFilterRunner(task); this.threadPool.execute(runner); } public void setAsynch(Task t, ASYNCH asynch, long timeout) { asynchTasks.get().add(t, asynch, timeout); } /** * submit a future, a separate thread will poll it on interval and * call your callback when isDone is set, or cancel once the timeout has. * * callback is executed in one of this processors executor threads. * @param future * @param callback */ public void submitFuture(Task task, Future future, FuturePollerCallback callback, long timeout) { FuturePollerWrapper wrapper = new FuturePollerWrapper(future, callback, timeout, task); asynchTasks.get().addFuture(wrapper); } // public void resumeAsynch(String taskId) { // asynchTasks.get().resume(taskId); // } public void resumeAsynch(Task task) { asynchTasks.get().resume(task); } public ExecutorService getExecutor() { return this.threadPool; } /** * A unique name for this processor. only one instance per name will be allowed. * @return */ public String getName() { return this.name; } public void taskComplete(Task task) { if (this.callback != null) { this.callback.taskComplete(task); } if (task.getCallback() != null) { task.getCallback().taskComplete(task); } } public void taskError(Task task, Exception error) { if (this.callback != null) { this.callback.taskError(task, error); } if (task.getCallback() != null) { task.getCallback().taskError(task, error); } } /** * gets the execution report incrementor for TaskProcessor.{this.getName} * * @return */ public ExecutionReportIncrementor getExecutionReport() { return new ExecutionSubReport(this.getName(), ExecutionReport.instance("TaskProcessor")); } }
true
true
public static TaskProcessor defaultInstance(String name, TaskCallback callback, int numThreads) { ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 1, // core size numThreads, // max size 130, // idle timeout TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size new TaskProcessorThreadFactory(name), new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. ); return new TaskProcessor(name, callback, threadPool); }
public static TaskProcessor defaultInstance(String name, TaskCallback callback, int numThreads) { ThreadPoolExecutor threadPool = new ThreadPoolExecutor( numThreads, // core size numThreads, // max size 130, // idle timeout TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(numThreads), // queue with a size new TaskProcessorThreadFactory(name), new ThreadPoolExecutor.CallerRunsPolicy() //if queue is full run in current thread. ); return new TaskProcessor(name, callback, threadPool); }
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java index 6735077..2c889e4 100644 --- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java +++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/algorithm/AStar.java @@ -1,348 +1,348 @@ /* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentripplanner.routing.algorithm; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.opentripplanner.routing.core.Edge; import org.opentripplanner.routing.core.Graph; import org.opentripplanner.routing.core.State; import org.opentripplanner.routing.core.TraverseOptions; import org.opentripplanner.routing.core.TraverseResult; import org.opentripplanner.routing.core.Vertex; import org.opentripplanner.routing.location.StreetLocation; import org.opentripplanner.routing.pqueue.FibHeap; import org.opentripplanner.routing.spt.SPTVertex; import org.opentripplanner.routing.spt.ShortestPathTree; /** * * NullExtraEdges is used to speed up checks for extra edges in the (common) case * where there are none. Extra edges come from StreetLocationFinder, where * they represent the edges between a location on a street segment and the * corners at the ends of that segment. */ class NullExtraEdges implements Map<Vertex, Edge> { @Override public void clear() { } @Override public boolean containsKey(Object arg0) { return false; } @Override public boolean containsValue(Object arg0) { return false; } @Override public Set<java.util.Map.Entry<Vertex, Edge>> entrySet() { return null; } @Override public Edge get(Object arg0) { return null; } @Override public boolean isEmpty() { return false; } @Override public Set<Vertex> keySet() { return null; } @Override public Edge put(Vertex arg0, Edge arg1) { return null; } @Override public void putAll(Map<? extends Vertex, ? extends Edge> arg0) { } @Override public Edge remove(Object arg0) { return null; } @Override public int size() { return 0; } @Override public Collection<Edge> values() { return null; } } /** * Find the shortest path between graph vertices using A*. */ public class AStar { static final double MAX_SPEED = 10.0; /** * Plots a path on graph from origin to target, departing at the time * given in state and with the options options. * * @param graph * @param origin * @param target * @param init * @param options * @return the shortest path, or null if none is found */ public static ShortestPathTree getShortestPathTree(Graph gg, String from_label, String to_label, State init, TraverseOptions options) { // Goal Variables String origin_label = from_label; String target_label = to_label; // Get origin vertex to make sure it exists Vertex origin = gg.getVertex(origin_label); Vertex target = gg.getVertex(target_label); return getShortestPathTree(gg, origin, target, init, options); } public static ShortestPathTree getShortestPathTreeBack(Graph gg, String from_label, String to_label, State init, TraverseOptions options) { // Goal Variables String origin_label = from_label; String target_label = to_label; // Get origin vertex to make sure it exists Vertex origin = gg.getVertex(origin_label); Vertex target = gg.getVertex(target_label); return getShortestPathTreeBack(gg, origin, target, init, options); } /** * Plots a path on graph from origin to target, arriving at the time * given in state and with the options options. * * @param graph * @param origin * @param target * @param init * @param options * @return the shortest path, or null if none is found */ public static ShortestPathTree getShortestPathTreeBack(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* Run backwards from the target to the origin */ Vertex tmp = origin; origin = target; target = tmp; /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (target instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> outgoing = target.getOutgoing(); for (Edge edge : outgoing) { extraEdges.put(edge.getToVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> incoming = spt_u.mirror.getIncoming(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newIncoming = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) { newIncoming.add(edge); } newIncoming.add(extraEdges.get(spt_u.mirror)); incoming = newIncoming; } for (Edge edge : incoming) { TraverseResult wr = edge.traverseBack(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { - throw new NegativeWeightException(String.valueOf(wr.weight)); + throw new NegativeWeightException(String.valueOf(wr.weight) + " on edge " + edge); } Vertex fromv = edge.getFromVertex(); distance = fromv.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(fromv); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(fromv, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; } public static ShortestPathTree getShortestPathTree(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (origin instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> incoming = target.getIncoming(); for (Edge edge : incoming) { extraEdges.put(edge.getFromVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> outgoing = spt_u.mirror.getOutgoing(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newOutgoing = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) newOutgoing.add(edge); newOutgoing.add(extraEdges.get(spt_u.mirror)); outgoing = newOutgoing; } for (Edge edge : outgoing) { TraverseResult wr = edge.traverse(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { throw new NegativeWeightException(String.valueOf(wr.weight)); } Vertex tov = edge.getToVertex(); distance = tov.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(tov); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(tov, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; } }
true
true
public static ShortestPathTree getShortestPathTreeBack(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* Run backwards from the target to the origin */ Vertex tmp = origin; origin = target; target = tmp; /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (target instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> outgoing = target.getOutgoing(); for (Edge edge : outgoing) { extraEdges.put(edge.getToVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> incoming = spt_u.mirror.getIncoming(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newIncoming = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) { newIncoming.add(edge); } newIncoming.add(extraEdges.get(spt_u.mirror)); incoming = newIncoming; } for (Edge edge : incoming) { TraverseResult wr = edge.traverseBack(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { throw new NegativeWeightException(String.valueOf(wr.weight)); } Vertex fromv = edge.getFromVertex(); distance = fromv.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(fromv); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(fromv, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; }
public static ShortestPathTree getShortestPathTreeBack(Graph graph, Vertex origin, Vertex target, State init, TraverseOptions options) { if (origin == null || target == null) { return null; } /* Run backwards from the target to the origin */ Vertex tmp = origin; origin = target; target = tmp; /* generate extra edges for StreetLocations */ Map<Vertex, Edge> extraEdges; if (target instanceof StreetLocation) { extraEdges = new HashMap<Vertex, Edge>(); Iterable<Edge> outgoing = target.getOutgoing(); for (Edge edge : outgoing) { extraEdges.put(edge.getToVertex(), edge); } } else { extraEdges = new NullExtraEdges(); } // Return Tree ShortestPathTree spt = new ShortestPathTree(); double distance = origin.distance(target) / MAX_SPEED; SPTVertex spt_origin = spt.addVertex(origin, init, 0, options); // Priority Queue FibHeap pq = new FibHeap(graph.getVertices().size() + extraEdges.size()); pq.insert(spt_origin, spt_origin.weightSum + distance); // Iteration Variables SPTVertex spt_u, spt_v; while (!pq.empty()) { // Until the priority queue is empty: spt_u = (SPTVertex) pq.extract_min(); // get the lowest-weightSum Vertex 'u', if (spt_u.mirror == target) break; Iterable<Edge> incoming = spt_u.mirror.getIncoming(); if (extraEdges.containsKey(spt_u.mirror)) { List<Edge> newIncoming = new ArrayList<Edge>(); for (Edge edge : spt_u.mirror.getOutgoing()) { newIncoming.add(edge); } newIncoming.add(extraEdges.get(spt_u.mirror)); incoming = newIncoming; } for (Edge edge : incoming) { TraverseResult wr = edge.traverseBack(spt_u.state, options); // When an edge leads nowhere (as indicated by returning NULL), the iteration is // over. if (wr == null) { continue; } if (wr.weight < 0) { throw new NegativeWeightException(String.valueOf(wr.weight) + " on edge " + edge); } Vertex fromv = edge.getFromVertex(); distance = fromv.distance(target) / MAX_SPEED; double new_w = spt_u.weightSum + wr.weight; double old_w; spt_v = spt.getVertex(fromv); // if this is the first time edge.tov has been visited if (spt_v == null) { old_w = Integer.MAX_VALUE; spt_v = spt.addVertex(fromv, wr.state, new_w, options); } else { old_w = spt_v.weightSum + distance; } // If the new way of getting there is better, if (new_w + distance < old_w) { // Set the State of v in the SPT to the current winner spt_v.state = wr.state; spt_v.weightSum = new_w; if (old_w == Integer.MAX_VALUE) { pq.insert(spt_v, new_w + distance); } else { pq.insert_or_dec_key(spt_v, new_w + distance); } spt_v.setParent(spt_u, edge); } } } return spt; }
diff --git a/ATM/atm.java b/ATM/atm.java index da38885..98bca1f 100644 --- a/ATM/atm.java +++ b/ATM/atm.java @@ -1,121 +1,122 @@ //by HafizJef import java.io.*; class atm { public static void main(String args[]) throws IOException { String money; BufferedReader getinput = new BufferedReader(new InputStreamReader(System.in)); System.out.println("\n\n+Welcome to Maybank2Mu berhad, This machine can spit out :\n\n\t| 10, 20, 50 and 100 |"); int max100=10, max50=10, max20=10, max10=10, note100=0, note50=0, note20=0, note10=0; int loop=0; while (loop==0) { + note100=0; note50=0; note20=0; note10=0; System.out.print("\n\n+Please input amount of money that you want to withdraw(Min. RM 10) : "); money = getinput.readLine(); int amount = Integer.parseInt(money); int total=amount; if (amount<10) { System.out.println("\n\nThe entered value is invalid"); continue; //continue to loop, use return to end; } else if (amount>1500) { System.out.println("\n\nThe maximum amount to per withdrawal is RM1500"); continue; } if (amount>=100) { note100=amount/100; amount=amount%100; if (note100>max100) { amount=(amount%100)+(100*(note100-max100)); note100=max100; //System.out.println(amount); } max100=max100-note100; } if (amount>=50) { note50=amount/50; amount=amount%50; if (note50>max50) { amount=(amount%50)+(50*(note50-max50)); note50=max50; //System.out.println(amount); } max50=max50-note50; } if (amount>=20) { note20=amount/20; amount=amount%20; if (note20>max20) { amount=(amount%20)+(20*(note20-max20)); note20=max20; //System.out.println(amount); } max20=max20-note20; } if (amount>=10) { note10=amount/10; amount=amount%10; if (note10>max10) { amount=(amount%10)+(10*(note10-max10)); note10=max10; //System.out.println(amount); System.out.println("Sorry, our machine is out of service"); System.exit(0); } max10=max10-note10; } if (amount!=0) { System.out.println("Error!, Please input amount in multiple of 10"); return; } else { System.out.println("\n\n\t=====================\n"+"\t| Note $100\t= "+note100+" | "+"\n\t| Note $50\t= "+note50+" | "+"\n\t| Note $20\t= "+note20+" | "+"\n\t| Note $10\t= "+note10+" | "); System.out.println("\t=====================\n"+"\n\t Total\t\t= "+total); System.out.print("\n\nDo you want to make another transaction?[Y/N] : "); String userMenu = getinput.readLine(); - if ((userMenu.equals("y"))||(userMenu.equals("Y"))) + if ((userMenu.equalsIgnoreCase("Y"))) { loop=0; } else { System.out.println("Thanks for using our service"); loop=1; } } } } }
false
true
public static void main(String args[]) throws IOException { String money; BufferedReader getinput = new BufferedReader(new InputStreamReader(System.in)); System.out.println("\n\n+Welcome to Maybank2Mu berhad, This machine can spit out :\n\n\t| 10, 20, 50 and 100 |"); int max100=10, max50=10, max20=10, max10=10, note100=0, note50=0, note20=0, note10=0; int loop=0; while (loop==0) { System.out.print("\n\n+Please input amount of money that you want to withdraw(Min. RM 10) : "); money = getinput.readLine(); int amount = Integer.parseInt(money); int total=amount; if (amount<10) { System.out.println("\n\nThe entered value is invalid"); continue; //continue to loop, use return to end; } else if (amount>1500) { System.out.println("\n\nThe maximum amount to per withdrawal is RM1500"); continue; } if (amount>=100) { note100=amount/100; amount=amount%100; if (note100>max100) { amount=(amount%100)+(100*(note100-max100)); note100=max100; //System.out.println(amount); } max100=max100-note100; } if (amount>=50) { note50=amount/50; amount=amount%50; if (note50>max50) { amount=(amount%50)+(50*(note50-max50)); note50=max50; //System.out.println(amount); } max50=max50-note50; } if (amount>=20) { note20=amount/20; amount=amount%20; if (note20>max20) { amount=(amount%20)+(20*(note20-max20)); note20=max20; //System.out.println(amount); } max20=max20-note20; } if (amount>=10) { note10=amount/10; amount=amount%10; if (note10>max10) { amount=(amount%10)+(10*(note10-max10)); note10=max10; //System.out.println(amount); System.out.println("Sorry, our machine is out of service"); System.exit(0); } max10=max10-note10; } if (amount!=0) { System.out.println("Error!, Please input amount in multiple of 10"); return; } else { System.out.println("\n\n\t=====================\n"+"\t| Note $100\t= "+note100+" | "+"\n\t| Note $50\t= "+note50+" | "+"\n\t| Note $20\t= "+note20+" | "+"\n\t| Note $10\t= "+note10+" | "); System.out.println("\t=====================\n"+"\n\t Total\t\t= "+total); System.out.print("\n\nDo you want to make another transaction?[Y/N] : "); String userMenu = getinput.readLine(); if ((userMenu.equals("y"))||(userMenu.equals("Y"))) { loop=0; } else { System.out.println("Thanks for using our service"); loop=1; } } } }
public static void main(String args[]) throws IOException { String money; BufferedReader getinput = new BufferedReader(new InputStreamReader(System.in)); System.out.println("\n\n+Welcome to Maybank2Mu berhad, This machine can spit out :\n\n\t| 10, 20, 50 and 100 |"); int max100=10, max50=10, max20=10, max10=10, note100=0, note50=0, note20=0, note10=0; int loop=0; while (loop==0) { note100=0; note50=0; note20=0; note10=0; System.out.print("\n\n+Please input amount of money that you want to withdraw(Min. RM 10) : "); money = getinput.readLine(); int amount = Integer.parseInt(money); int total=amount; if (amount<10) { System.out.println("\n\nThe entered value is invalid"); continue; //continue to loop, use return to end; } else if (amount>1500) { System.out.println("\n\nThe maximum amount to per withdrawal is RM1500"); continue; } if (amount>=100) { note100=amount/100; amount=amount%100; if (note100>max100) { amount=(amount%100)+(100*(note100-max100)); note100=max100; //System.out.println(amount); } max100=max100-note100; } if (amount>=50) { note50=amount/50; amount=amount%50; if (note50>max50) { amount=(amount%50)+(50*(note50-max50)); note50=max50; //System.out.println(amount); } max50=max50-note50; } if (amount>=20) { note20=amount/20; amount=amount%20; if (note20>max20) { amount=(amount%20)+(20*(note20-max20)); note20=max20; //System.out.println(amount); } max20=max20-note20; } if (amount>=10) { note10=amount/10; amount=amount%10; if (note10>max10) { amount=(amount%10)+(10*(note10-max10)); note10=max10; //System.out.println(amount); System.out.println("Sorry, our machine is out of service"); System.exit(0); } max10=max10-note10; } if (amount!=0) { System.out.println("Error!, Please input amount in multiple of 10"); return; } else { System.out.println("\n\n\t=====================\n"+"\t| Note $100\t= "+note100+" | "+"\n\t| Note $50\t= "+note50+" | "+"\n\t| Note $20\t= "+note20+" | "+"\n\t| Note $10\t= "+note10+" | "); System.out.println("\t=====================\n"+"\n\t Total\t\t= "+total); System.out.print("\n\nDo you want to make another transaction?[Y/N] : "); String userMenu = getinput.readLine(); if ((userMenu.equalsIgnoreCase("Y"))) { loop=0; } else { System.out.println("Thanks for using our service"); loop=1; } } } }
diff --git a/fog/src/de/tuilmenau/ics/fog/packets/PleaseOpenConnection.java b/fog/src/de/tuilmenau/ics/fog/packets/PleaseOpenConnection.java index c6d7a8ff..3f72f5ec 100644 --- a/fog/src/de/tuilmenau/ics/fog/packets/PleaseOpenConnection.java +++ b/fog/src/de/tuilmenau/ics/fog/packets/PleaseOpenConnection.java @@ -1,737 +1,737 @@ /******************************************************************************* * Forwarding on Gates Simulator/Emulator * Copyright (C) 2012, Integrated Communication Systems Group, TU Ilmenau. * * This program and the accompanying materials are dual-licensed under either * the terms of the Eclipse Public License v1.0 as published by the Eclipse * Foundation * * or (per the licensee's choosing) * * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. ******************************************************************************/ package de.tuilmenau.ics.fog.packets; import java.util.HashMap; import java.util.Map; import de.tuilmenau.ics.fog.Config; import de.tuilmenau.ics.fog.FoGEntity; import de.tuilmenau.ics.fog.facade.Description; import de.tuilmenau.ics.fog.facade.Identity; import de.tuilmenau.ics.fog.facade.Name; import de.tuilmenau.ics.fog.facade.NetworkException; import de.tuilmenau.ics.fog.routing.Route; import de.tuilmenau.ics.fog.routing.RouteSegment; import de.tuilmenau.ics.fog.routing.RouteSegmentPath; import de.tuilmenau.ics.fog.transfer.ForwardingNode; import de.tuilmenau.ics.fog.transfer.forwardingNodes.ClientFN; import de.tuilmenau.ics.fog.transfer.forwardingNodes.ConnectionEndPoint; import de.tuilmenau.ics.fog.transfer.forwardingNodes.Multiplexer; import de.tuilmenau.ics.fog.transfer.forwardingNodes.ServerFN; import de.tuilmenau.ics.fog.transfer.manager.Process; import de.tuilmenau.ics.fog.transfer.manager.ProcessConnection; import de.tuilmenau.ics.fog.transfer.manager.ProcessGateCollectionConstruction; import de.tuilmenau.ics.fog.transfer.manager.Process.ProcessState; import de.tuilmenau.ics.fog.ui.Viewable; /** * Used as payload in signaling messages to build up a connection. */ public class PleaseOpenConnection extends SignallingRequest { private static final long serialVersionUID = 1488705063865574155L; /** * Initial connection request. * * @param pCallbackName The name of the connection demanding callback. * * @param pSendersProcess The the constructing process of the sender of this * connection request. * * @param pDescription The requirements for the connection. */ public PleaseOpenConnection(String pCallbackName, ProcessGateCollectionConstruction pSendersProcess, Description pDescription, boolean pToApplication) { super(pSendersProcess != null ? pSendersProcess.getID() : 0); mConnectionInitiatorName = pCallbackName; if(mConnectionInitiatorName == null) { mConnectionInitiatorName = "?*"; } incCounter(Index.INSTANCE_COUNTER); mSendersProcessNumber = pSendersProcess != null ? pSendersProcess.getID() : 0; mReceiversProcessNumber = 0; setDescription(pDescription); if(pSendersProcess != null) { mSendersRouteUpToHisClient = pSendersProcess.getRouteUpToClient(); ForwardingNode tFN = pSendersProcess.getBase(); mPeerRoutingName = tFN.getEntity().getRoutingService().getNameFor(tFN); } mToApplication = pToApplication; } /** * Connection request as response to an received one. * * @param pPredecessor The connection request preceding this one. * * @param pSendersProcess The the constructing process of the sender of this * connection request. * * @param pDescription The (new) requirements for the connection. */ private PleaseOpenConnection(PleaseOpenConnection pPredecessor, ProcessGateCollectionConstruction pSendersProcess, Description pDescription) { super(pSendersProcess != null ? pSendersProcess.getID() : 0); mConnectionInitiatorName = pPredecessor.mConnectionInitiatorName; if(mConnectionInitiatorName == null) { mConnectionInitiatorName = "?*"; } incCounter(Index.INSTANCE_COUNTER); mSendersProcessNumber = pSendersProcess != null ? pSendersProcess.getID() : 0; mReceiversProcessNumber = pPredecessor.mSendersProcessNumber; mSendersRouteUpToHisClient = pSendersProcess.getRouteUpToClient(); ForwardingNode tFN = pSendersProcess.getBase(); mPeerRoutingName = tFN.getEntity().getRoutingService().getNameFor(tFN); setDescription(pDescription); } /** * Short constructor for a dummy signaling message. The signal workflow * will create a connection end point locally and do not send any * signaling answers. * * @param pDescription Requirements for the connection end point. */ public PleaseOpenConnection(Description pDescription) { this(null, null, pDescription, true); mIsLocalDummy = true; } /** * @return The reference number to the constructing * process of the sender of this connection request. */ protected int getSendersProcessNumber() { return getProcessNumber(); } /** * @return The reference number to the constructing * process of the receiver of this connection request. */ protected int getReceiversProcessNumber() { return mReceiversProcessNumber; } @Override public boolean execute(ForwardingNode pFN, Packet pPacket, Identity pRequester) { pFN.getEntity().getLogger().log(this, "execute open connection request on " +pFN + " from reverse node process " +getSendersProcessNumber()); Process tProcess = null; try { if(!(pFN instanceof Multiplexer)) { - throw new NetworkException("open connection request can only be executed at multiplexing FNs, current FN is: " + pFN); + throw new NetworkException("open connection request can only be executed at multiplexing FNs\n -> current FN is: " + pFN + "\n -> signaling packet: " + pPacket); } if(pPacket == null) { throw new NetworkException("missing packet argument to execute open connection request"); } Route tPacketReturnRoute = pPacket.getReturnRoute(); if(tPacketReturnRoute == null || tPacketReturnRoute.isEmpty()) { throw new NetworkException("missing packet return route"); } tProcess = pFN.getEntity().getProcessRegister().getProcess(pFN, pRequester, getReceiversProcessNumber()); if(tProcess != null) { // Returning (maybe requirement-changing) connection request. if(tProcess.getState() == ProcessState.CLOSING) { throw new NetworkException("Connection process " +tProcess +" was closed."); } if(tProcess instanceof ProcessGateCollectionConstruction) { ProcessGateCollectionConstruction mReceiversProcess = (ProcessGateCollectionConstruction) tProcess; // Check base FN identity. if(mReceiversProcess.getBase() == pFN) { /* ***************************************************** * Use and complete the known instance of * ProcessConnection. ******************************************************/ mReturnRouteFromBaseFN = tPacketReturnRoute; Packet tRes = completeConnectionProcess(mReceiversProcess, pRequester); signAndSend(pFN, tRes); } else { throw new NetworkException("found referenced process " +tProcess.getID() + " starts at different forwarding node" ); } } else { // Wrong type origin process. throw new NetworkException("process " +tProcess.getID() + " (" +tProcess.getClass().getSimpleName() + ") is no instance of class ProcessSocketConstruction needed for open connection request execution" ); } } else { // Initial connection request. mReturnRouteFromBaseFN = tPacketReturnRoute; if(mToApplication) { if(pFN instanceof ServerFN) { ServerFN tServerFN = (ServerFN) pFN; if(Config.Connection.SERVER_REDIRECT_TO_MULTIPLEXER) { // Start the connection socket at central multiplexer. Multiplexer mNewBaseFN = redirectToMultiplexer(tServerFN); if(mNewBaseFN != null) { pFN = mNewBaseFN; } else { pFN.getEntity().getLogger().log(this, "can not redirect from server " +pFN + " to central multiplexer"); } } /* ************************************************************* * Create and start new instance of ProcessConnection. **************************************************************/ ProcessConnection tProcessConn = createAndStartConnectionProcess(pFN, pRequester); tProcess = tProcessConn; if(tProcess == null) { throw new NetworkException("Connection process creation failed."); } // inform app about new connection ConnectionEndPoint tCEP = new ConnectionEndPoint(tServerFN.getName(), pFN.getEntity().getLogger(), pPacket.getAuthentications()); ClientFN tFN = tProcessConn.getEndForwardingNode(); tCEP.setForwardingNode(tFN); tFN.setConnectionEndPoint(tCEP); tServerFN.addNewConnection(tCEP); // are we just a dummy? // -> send packet to connection end point if(mIsLocalDummy) { pPacket.getRoute().addLast(tProcessConn.getRouteUpToClient()); pFN.handlePacket(pPacket, null); } } else { // Connection request can also arrive at a // MultiplexerGate that is no ServerGate! // -> Need to know target service. -> Workaround. // -> TODO Search for relevant server and try to connect. throw new NetworkException("Destination forwarding node " +pFN +" is not attached to a higher layer, source of request is " + pRequester.getName()); } } else { /* ************************************************************* * Create and start new instance of ProcessConnection. **************************************************************/ tProcess = createAndStartGateProcess(pFN, pFN, pRequester); if(tProcess == null) { throw new NetworkException("Connection process creation failed."); } } } incCounter(Index.POSITIVE_EXECUTION_COUNTER); return true; } catch(NetworkException ne) { // Log the error. pFN.getEntity().getLogger().err(this, "Error during execution of open request on " +pFN, ne); // send error reply back if(pFN != null) { //TODO Differenciation between internal and real network exception // needed to prevent posting internals to remote system. Packet packet = new Packet(pPacket.getReturnRoute(), new OpenConnectionResponse(this, getReceiversProcessNumber(), ne)); signAndSend(pFN, packet); } if(tProcess != null && tProcess.getState() != null && !tProcess.isFinished()) { // De-construct existing elements. tProcess.terminate(ne); } incCounter(Index.NEGATIVE_EXECUTION_COUNTER); return false; } } /** * Create and start the connection process. * * @param pReceiveCallback The local {@link ReceiveCallback} instance to use. * @param pPacket The packet containing the connection request. * * @return The created local connection process. * @throws NetworkException on error */ @SuppressWarnings("unused") private ProcessConnection createAndStartConnectionProcess(ForwardingNode pBaseFN, Identity pRequester) throws NetworkException { // Create construction process. ProcessConnection tReceiversProcess = new ProcessConnection(pBaseFN, null, getDescription(), pRequester); // Create and register client FN. tReceiversProcess.start(); mReceiversProcessNumber = tReceiversProcess.getID(); if(Config.Connection.LAZY_REQUEST_RECEIVER && !mIsLocalDummy) { // Socket-path will not be created before next handshake arrives. // Send an answer. Description tReturnDescription = getDescription().calculateDescrForRemoteSystem(); Packet packet = new Packet(mReturnRouteFromBaseFN, new PleaseOpenConnection(this, tReceiversProcess, tReturnDescription)); signAndSend(pBaseFN, packet); } else { // Build up socket path. Packet answer = completeConnectionProcess(tReceiversProcess, pRequester); if(!mIsLocalDummy) { signAndSend(tReceiversProcess.getBase(), answer); } } if(Config.Connection.TERMINATE_WHEN_IDLE) { tReceiversProcess.activateIdleTimeout(); } if(Config.Connection.SEND_KEEP_ALIVE_MESSAGES_WHEN_IDLE) { tReceiversProcess.activateKeepAlive(); } return tReceiversProcess; } /** * Create and start the connection process. * * @param pReceiveCallback The local {@link ReceiveCallback} instance to use. * @param pPacket The packet containing the connection request. * * @return The created local connection process. * @throws NetworkException on error */ private ProcessGateCollectionConstruction createAndStartGateProcess(ForwardingNode pBaseFN, ForwardingNode pOutgoingFN, Identity pRequester) throws NetworkException { // Create construction process. ProcessGateCollectionConstruction tReceiversProcess = new ProcessGateCollectionConstruction(pBaseFN, pOutgoingFN, getDescription(), pRequester); // Create and register client FN. tReceiversProcess.disableHorizontal(); tReceiversProcess.start(); mReceiversProcessNumber = tReceiversProcess.getID(); // Build up socket path. Packet answer = completeConnectionProcess(tReceiversProcess, pRequester); signAndSend(tReceiversProcess.getBase(), answer); if(Config.Connection.TERMINATE_WHEN_IDLE) { tReceiversProcess.activateIdleTimeout(); } return tReceiversProcess; } /** * Call an existing process to (re)create the socket-path. * * @param pPacket The packet containing the connection request. * * @throws NetworkException on error */ private Packet completeConnectionProcess(ProcessGateCollectionConstruction pReceiversProcess, Identity pRequester) throws NetworkException { if(pReceiversProcess == null || pReceiversProcess.getState() == null || pReceiversProcess.isFinished()) { throw new NetworkException("Connection process failed."); } /* ********************************************************************* * (Re-)Build socket path. **********************************************************************/ pReceiversProcess.recreatePath(getDescription(), mReturnRouteFromBaseFN); if(mSendersRouteUpToHisClient != null) { /* ***************************************************************** * Path from remote base FN to remote client FN available so * horizontal tunnel gate can be updated with route and consequently * the own process can be finished. * -> Reply with an OpenConnectionResponse. ******************************************************************/ // Update the route the client leaving gate should use. pReceiversProcess.updateRoute(mReturnRouteFromBaseFN, mSendersRouteUpToHisClient, mPeerRoutingName, pRequester); // Send an answer; ForwardingNode tFN = pReceiversProcess.getBase(); Name tLocalServiceName = tFN.getEntity().getRoutingService().getNameFor(tFN); Packet packet = new Packet(mReturnRouteFromBaseFN, new OpenConnectionResponse(this, pReceiversProcess, tLocalServiceName)); return packet; } else { /* ***************************************************************** * No path from remote base FN to remote client FN available so * can not update route for horizontal tunnel gate and consequently * not finish the own process as well. * -> Reply with an additional PleaseOpenConnection. ******************************************************************/ Description tReturnDescription = getDescription().calculateDescrForRemoteSystem(); Packet packet = new Packet(mReturnRouteFromBaseFN, new PleaseOpenConnection(this, pReceiversProcess, tReturnDescription)); return packet; } } /** * Try to replace the actual starting point by central multiplexer. * * @return {@code true} if redirection could be initialized and * {@code false} if former base and routes will still be used. */ private Multiplexer redirectToMultiplexer(ForwardingNode mBaseFN) { FoGEntity tEntity = mBaseFN.getEntity(); Multiplexer tMux = tEntity.getCentralFN(); if(tMux == mBaseFN) { tEntity.getLogger().debug(this, "server-self-redirection skipped"); return null; } Name tMuxName = tMux.getEntity().getRoutingService().getNameFor(tMux); if(tMux == mBaseFN) { tEntity.getLogger().warn(this, "unknown central multiplexer"); return null; } // Packets return route should run through local central // MultiplexerGate. The path from ServerGate to central // MultiplexerGate has to be removed from packets return // route to guide the response-packet from MultiplexerGate // to remote system. Route tReturnRoute = new Route(mReturnRouteFromBaseFN); RouteSegment tRouteSegment = tReturnRoute.removeFirst(); if(tRouteSegment == null) { // No reverse route. return null; } if(!(tRouteSegment instanceof RouteSegmentPath)) { // No local internal path in reverse route. return null; } // Get to know the first path in packets return route. RouteSegmentPath tReturnRouteFirstPath = new RouteSegmentPath((RouteSegmentPath)tRouteSegment); if(tReturnRouteFirstPath.isEmpty()) { // Internal path in reverse route is empty. return null; } // Get to know the internal route from server to multiplexer. Route tRouteToMux = null; try { tRouteToMux = mBaseFN.getEntity().getTransferPlane().getRoute(mBaseFN, tMuxName, null, null); } catch (NetworkException e) {} if(tRouteToMux == null) { // Unknown route from server to multiplexer. return null; } tRouteSegment = null; RouteSegmentPath tPathToMux = new RouteSegmentPath(); while(!tRouteToMux.isEmpty() && (tRouteSegment = tRouteToMux.removeFirst()) != null) { if(tRouteSegment instanceof RouteSegmentPath) { tPathToMux.addAll((RouteSegmentPath) tRouteSegment); } else { // Internal route segment is no path segment. return null; } } if(tPathToMux.isEmpty()) { // No internal path from server to central multiplexer. return null; } // Remove the path from server to multiplexer from return path. while(!tReturnRouteFirstPath.isEmpty() && !tPathToMux.isEmpty()) { if(!tReturnRouteFirstPath.removeFirst().equals(tPathToMux.removeFirst())) { // Different path to mux or server is connected to other mux. return null; } } if(!tPathToMux.isEmpty()) { // Path to mux longer than internal reverse path from server to mux. return null; } if(!tReturnRouteFirstPath.isEmpty()) { tReturnRoute.addFirst(tReturnRouteFirstPath); } // Switch base from server to mux. mReturnRouteFromBaseFN = tReturnRoute; return tMux; } /** * @return The description for the demanded Connection including * functional requirements in well-defined order. */ protected Description getDescription() { return mDescription; } /** * @param pDescription The description for the demanded connection to set. * May include functional requirements in well-defined order. */ private void setDescription(Description pDescription) { mDescription = pDescription; if(mDescription == null) { mDescription = new Description(); } } /** * @return The route starting at senders base FN and ending at his client FN. */ protected Route getSendersRouteUpToHisClient() { return mSendersRouteUpToHisClient; } /** * @param pSendersRouteUpToHisClient The route starting at senders base FN * and ending at his client FN. */ public void setSendersRouteUpToHisClient(Route pSendersRouteUpToHisClient) { this.mSendersRouteUpToHisClient = pSendersRouteUpToHisClient; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(super.toString()); sb.append('('); sb.append("[S_Proc: "); sb.append(mSendersProcessNumber); sb.append(']'); sb.append("[S_RouteUp: "); sb.append(mSendersRouteUpToHisClient); sb.append(']'); sb.append("[R_Proc: "); sb.append(mReceiversProcessNumber); sb.append(']'); /* sb.append("[R_FNName: "); sb.append(mBaseFNName); sb.append(']'); sb.append("[R_Svc: "); sb.append(mServiceName); sb.append(']'); */ sb.append("[Descr: "); sb.append(mDescription); sb.append(']'); sb.append(')'); return sb.toString(); } /** * @param pClientName The name of the client that instantiated the signal(s). * * @return Total number of instances created at given node. * * <br/>As every static field relative to concrete JavaVM and ClassLoader. */ public static long getInstanceCounter(String pClientName) { return getCounter(pClientName, Index.INSTANCE_COUNTER); } /** * @param pClientName The name of the client that instantiated the signal(s). * * @return Total number of executions called at given node returned true. * * <br/>As every static field relative to concrete JavaVM and ClassLoader. */ public static long getExecutedPositiveCounter(String pNodeName) { return getCounter(pNodeName, Index.POSITIVE_EXECUTION_COUNTER); } /** * @param pClientName The name of the client that instantiated the signal(s). * * @return Total number of executions called at given node returned false. * * <br/>As every static field relative to concrete JavaVM and ClassLoader. */ public static long getExecutedNegativeCounter(String pNodeName) { return getCounter(pNodeName, Index.NEGATIVE_EXECUTION_COUNTER); } /** * @param pClientName The name of the client that instantiated the signal(s). * @param pIndex The Index given by {@link Index#INSTANCE_COUNTER}, * {@link Index#POSITIVE_EXECUTION_COUNTER} and * {@link Index#NEGATIVE_EXECUTION_COUNTER}. * * @return The counter per node and index. */ private static long getCounter(String pNodeName, Index pIndex) { if(pNodeName == null) { pNodeName = "?*"; } if(pIndex != null && sCounterMap != null) { long[] tCounterArray = sCounterMap.get(pNodeName); if(tCounterArray != null) { return tCounterArray[pIndex.ordinal()]; } } return 0L; } /** * Increments counter relative to the name of the client that * instantiated the Connection. * * @param pIndex The Index given by {@link Index#INSTANCE_COUNTER}, * {@link Index#POSITIVE_EXECUTION_COUNTER} and * {@link Index#NEGATIVE_EXECUTION_COUNTER}. */ private void incCounter(Index pIndex) { if(pIndex != null) { long[] tCounterArray = null; if(sCounterMap == null) { sCounterMap = new HashMap<String, long[]>(); } else { tCounterArray = sCounterMap.get(mConnectionInitiatorName); } if(tCounterArray == null) { tCounterArray = new long[]{0, 0, 0}; sCounterMap.put(mConnectionInitiatorName, tCounterArray); } tCounterArray[pIndex.ordinal()]++; } } public String getConnectionInitiatorName() { return mConnectionInitiatorName; } /* ************************************************************************* * Members **************************************************************************/ /** The route starting at senders base FN and ending at his client FN. */ @Viewable("Senders route up to its client") private Route mSendersRouteUpToHisClient; /** * The route starting at receivers (local) {@code mBaseFN} and ending at * senders base FN to answer this request. */ @Viewable("Return route from base FN") private Route mReturnRouteFromBaseFN; /** * The description for the demanded Connection. * May include functional requirements in well-defined order. */ @Viewable("Description") private Description mDescription; /** Receivers related process number. */ @Viewable("Receivers process number") private int mReceiversProcessNumber; /** Senders related process number just for gui. */ @Viewable("Senders process number") private int mSendersProcessNumber; /** Name of connection initiating client. */ @Viewable("Connection initiator name") private String mConnectionInitiatorName = null; /** Routing name of the responding entity */ @Viewable("Peer routing name") private Name mPeerRoutingName; @Viewable("To application") private boolean mToApplication; @Viewable("Local dummy for creating connection") private boolean mIsLocalDummy = false; /* ************************************************************************* * Static fields **************************************************************************/ private static enum Index { /** Index of the total number of instances created. */ INSTANCE_COUNTER, /** Index of the total number of executions returned true. */ POSITIVE_EXECUTION_COUNTER, /** Index of the total number of executions returned false. */ NEGATIVE_EXECUTION_COUNTER; } /** Map with counter for instances and positive and negative executions. */ private static volatile Map<String, long[]> sCounterMap; }
true
true
public boolean execute(ForwardingNode pFN, Packet pPacket, Identity pRequester) { pFN.getEntity().getLogger().log(this, "execute open connection request on " +pFN + " from reverse node process " +getSendersProcessNumber()); Process tProcess = null; try { if(!(pFN instanceof Multiplexer)) { throw new NetworkException("open connection request can only be executed at multiplexing FNs, current FN is: " + pFN); } if(pPacket == null) { throw new NetworkException("missing packet argument to execute open connection request"); } Route tPacketReturnRoute = pPacket.getReturnRoute(); if(tPacketReturnRoute == null || tPacketReturnRoute.isEmpty()) { throw new NetworkException("missing packet return route"); } tProcess = pFN.getEntity().getProcessRegister().getProcess(pFN, pRequester, getReceiversProcessNumber()); if(tProcess != null) { // Returning (maybe requirement-changing) connection request. if(tProcess.getState() == ProcessState.CLOSING) { throw new NetworkException("Connection process " +tProcess +" was closed."); } if(tProcess instanceof ProcessGateCollectionConstruction) { ProcessGateCollectionConstruction mReceiversProcess = (ProcessGateCollectionConstruction) tProcess; // Check base FN identity. if(mReceiversProcess.getBase() == pFN) { /* ***************************************************** * Use and complete the known instance of * ProcessConnection. ******************************************************/ mReturnRouteFromBaseFN = tPacketReturnRoute; Packet tRes = completeConnectionProcess(mReceiversProcess, pRequester); signAndSend(pFN, tRes); } else { throw new NetworkException("found referenced process " +tProcess.getID() + " starts at different forwarding node" ); } } else { // Wrong type origin process. throw new NetworkException("process " +tProcess.getID() + " (" +tProcess.getClass().getSimpleName() + ") is no instance of class ProcessSocketConstruction needed for open connection request execution" ); } } else { // Initial connection request. mReturnRouteFromBaseFN = tPacketReturnRoute; if(mToApplication) { if(pFN instanceof ServerFN) { ServerFN tServerFN = (ServerFN) pFN; if(Config.Connection.SERVER_REDIRECT_TO_MULTIPLEXER) { // Start the connection socket at central multiplexer. Multiplexer mNewBaseFN = redirectToMultiplexer(tServerFN); if(mNewBaseFN != null) { pFN = mNewBaseFN; } else { pFN.getEntity().getLogger().log(this, "can not redirect from server " +pFN + " to central multiplexer"); } } /* ************************************************************* * Create and start new instance of ProcessConnection. **************************************************************/ ProcessConnection tProcessConn = createAndStartConnectionProcess(pFN, pRequester); tProcess = tProcessConn; if(tProcess == null) { throw new NetworkException("Connection process creation failed."); } // inform app about new connection ConnectionEndPoint tCEP = new ConnectionEndPoint(tServerFN.getName(), pFN.getEntity().getLogger(), pPacket.getAuthentications()); ClientFN tFN = tProcessConn.getEndForwardingNode(); tCEP.setForwardingNode(tFN); tFN.setConnectionEndPoint(tCEP); tServerFN.addNewConnection(tCEP); // are we just a dummy? // -> send packet to connection end point if(mIsLocalDummy) { pPacket.getRoute().addLast(tProcessConn.getRouteUpToClient()); pFN.handlePacket(pPacket, null); } } else { // Connection request can also arrive at a // MultiplexerGate that is no ServerGate! // -> Need to know target service. -> Workaround. // -> TODO Search for relevant server and try to connect. throw new NetworkException("Destination forwarding node " +pFN +" is not attached to a higher layer, source of request is " + pRequester.getName()); } } else { /* ************************************************************* * Create and start new instance of ProcessConnection. **************************************************************/ tProcess = createAndStartGateProcess(pFN, pFN, pRequester); if(tProcess == null) { throw new NetworkException("Connection process creation failed."); } } } incCounter(Index.POSITIVE_EXECUTION_COUNTER); return true; } catch(NetworkException ne) { // Log the error. pFN.getEntity().getLogger().err(this, "Error during execution of open request on " +pFN, ne); // send error reply back if(pFN != null) { //TODO Differenciation between internal and real network exception // needed to prevent posting internals to remote system. Packet packet = new Packet(pPacket.getReturnRoute(), new OpenConnectionResponse(this, getReceiversProcessNumber(), ne)); signAndSend(pFN, packet); } if(tProcess != null && tProcess.getState() != null && !tProcess.isFinished()) { // De-construct existing elements. tProcess.terminate(ne); } incCounter(Index.NEGATIVE_EXECUTION_COUNTER); return false; } }
public boolean execute(ForwardingNode pFN, Packet pPacket, Identity pRequester) { pFN.getEntity().getLogger().log(this, "execute open connection request on " +pFN + " from reverse node process " +getSendersProcessNumber()); Process tProcess = null; try { if(!(pFN instanceof Multiplexer)) { throw new NetworkException("open connection request can only be executed at multiplexing FNs\n -> current FN is: " + pFN + "\n -> signaling packet: " + pPacket); } if(pPacket == null) { throw new NetworkException("missing packet argument to execute open connection request"); } Route tPacketReturnRoute = pPacket.getReturnRoute(); if(tPacketReturnRoute == null || tPacketReturnRoute.isEmpty()) { throw new NetworkException("missing packet return route"); } tProcess = pFN.getEntity().getProcessRegister().getProcess(pFN, pRequester, getReceiversProcessNumber()); if(tProcess != null) { // Returning (maybe requirement-changing) connection request. if(tProcess.getState() == ProcessState.CLOSING) { throw new NetworkException("Connection process " +tProcess +" was closed."); } if(tProcess instanceof ProcessGateCollectionConstruction) { ProcessGateCollectionConstruction mReceiversProcess = (ProcessGateCollectionConstruction) tProcess; // Check base FN identity. if(mReceiversProcess.getBase() == pFN) { /* ***************************************************** * Use and complete the known instance of * ProcessConnection. ******************************************************/ mReturnRouteFromBaseFN = tPacketReturnRoute; Packet tRes = completeConnectionProcess(mReceiversProcess, pRequester); signAndSend(pFN, tRes); } else { throw new NetworkException("found referenced process " +tProcess.getID() + " starts at different forwarding node" ); } } else { // Wrong type origin process. throw new NetworkException("process " +tProcess.getID() + " (" +tProcess.getClass().getSimpleName() + ") is no instance of class ProcessSocketConstruction needed for open connection request execution" ); } } else { // Initial connection request. mReturnRouteFromBaseFN = tPacketReturnRoute; if(mToApplication) { if(pFN instanceof ServerFN) { ServerFN tServerFN = (ServerFN) pFN; if(Config.Connection.SERVER_REDIRECT_TO_MULTIPLEXER) { // Start the connection socket at central multiplexer. Multiplexer mNewBaseFN = redirectToMultiplexer(tServerFN); if(mNewBaseFN != null) { pFN = mNewBaseFN; } else { pFN.getEntity().getLogger().log(this, "can not redirect from server " +pFN + " to central multiplexer"); } } /* ************************************************************* * Create and start new instance of ProcessConnection. **************************************************************/ ProcessConnection tProcessConn = createAndStartConnectionProcess(pFN, pRequester); tProcess = tProcessConn; if(tProcess == null) { throw new NetworkException("Connection process creation failed."); } // inform app about new connection ConnectionEndPoint tCEP = new ConnectionEndPoint(tServerFN.getName(), pFN.getEntity().getLogger(), pPacket.getAuthentications()); ClientFN tFN = tProcessConn.getEndForwardingNode(); tCEP.setForwardingNode(tFN); tFN.setConnectionEndPoint(tCEP); tServerFN.addNewConnection(tCEP); // are we just a dummy? // -> send packet to connection end point if(mIsLocalDummy) { pPacket.getRoute().addLast(tProcessConn.getRouteUpToClient()); pFN.handlePacket(pPacket, null); } } else { // Connection request can also arrive at a // MultiplexerGate that is no ServerGate! // -> Need to know target service. -> Workaround. // -> TODO Search for relevant server and try to connect. throw new NetworkException("Destination forwarding node " +pFN +" is not attached to a higher layer, source of request is " + pRequester.getName()); } } else { /* ************************************************************* * Create and start new instance of ProcessConnection. **************************************************************/ tProcess = createAndStartGateProcess(pFN, pFN, pRequester); if(tProcess == null) { throw new NetworkException("Connection process creation failed."); } } } incCounter(Index.POSITIVE_EXECUTION_COUNTER); return true; } catch(NetworkException ne) { // Log the error. pFN.getEntity().getLogger().err(this, "Error during execution of open request on " +pFN, ne); // send error reply back if(pFN != null) { //TODO Differenciation between internal and real network exception // needed to prevent posting internals to remote system. Packet packet = new Packet(pPacket.getReturnRoute(), new OpenConnectionResponse(this, getReceiversProcessNumber(), ne)); signAndSend(pFN, packet); } if(tProcess != null && tProcess.getState() != null && !tProcess.isFinished()) { // De-construct existing elements. tProcess.terminate(ne); } incCounter(Index.NEGATIVE_EXECUTION_COUNTER); return false; } }
diff --git a/commons/src/main/java/org/soluvas/commons/tenant/TenantInjection.java b/commons/src/main/java/org/soluvas/commons/tenant/TenantInjection.java index 99c99dc3..4cc4e29e 100644 --- a/commons/src/main/java/org/soluvas/commons/tenant/TenantInjection.java +++ b/commons/src/main/java/org/soluvas/commons/tenant/TenantInjection.java @@ -1,141 +1,141 @@ package org.soluvas.commons.tenant; import java.lang.reflect.Field; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.Nonnull; import javax.inject.Inject; import org.apache.commons.lang3.reflect.FieldUtils; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.soluvas.commons.ReflectionUtils; import org.soluvas.commons.inject.Filter; import org.soluvas.commons.inject.Namespace; import com.google.common.base.Throwables; /** * Base implementation to injects {@link Inject} {@link TenantRef} services using lifecycle methods * inject and uninject. * @author ceefour */ public class TenantInjection { private static Logger log = LoggerFactory .getLogger(TenantInjection.class); private final BundleContext bundleContext; private final String tenantId; private final String tenantEnv; /** * List of get-ed services (to unget). */ private final Map<Field, ServiceReference<?>> serviceRefs = new HashMap<Field, ServiceReference<?>>(); /** * @param bundleContext * @param tenantId * @param tenantEnv */ public TenantInjection(@Nonnull final BundleContext bundleContext, @Nonnull final String tenantId, @Nonnull final String tenantEnv) { super(); this.bundleContext = bundleContext; this.tenantId = tenantId; this.tenantEnv = tenantEnv; } /** * Perform injection. * @param component * @param phase */ @SuppressWarnings({ "rawtypes", "unchecked" }) public void inject(@Nonnull final Object component, @Nonnull final String componentId, @Nonnull final String phase) { final List<Field> nonSuppliedFields = ReflectionUtils.getNonSuppliedFields(component.getClass()); for (final Field field : nonSuppliedFields) { try { Object currentValue = FieldUtils.readField(field, component, true); if (currentValue != null) continue; } catch (IllegalAccessException e) { Throwables.propagate(e); return; } final Namespace namespaced = field.getAnnotation(Namespace.class); final String namespace = namespaced != null ? namespaced.value() : null; final String namespaceFilter = namespace != null ? "(namespace=" + namespace + ")" : ""; final Filter filtered = field.getAnnotation(Filter.class); final String additionalFilter = filtered != null ? filtered.value() : ""; final Class serviceClass = field.getType(); log.trace("Field {}#{} looking up {} for tenantId={} tenantEnv={} namespace={} filter: {}", componentId, field.getName(), serviceClass.getName(), tenantId, tenantEnv, namespace, additionalFilter ); - final String filter = String.format("(&(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*)))", + final String filter = String.format("(&(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*))%s%s)", tenantId, tenantEnv, namespaceFilter, additionalFilter); final ServiceReference<?> serviceRef; try { final Collection<ServiceReference<?>> foundRefs = bundleContext.getServiceReferences(serviceClass, filter); if (foundRefs == null || foundRefs.isEmpty()) { throw new RuntimeException("Cannot inject " + componentId + "#" + field.getName() + ", " + serviceClass.getName() + " service with " + filter + " not found"); } serviceRef = foundRefs.iterator().next(); } catch (InvalidSyntaxException e) { throw new RuntimeException("Cannot inject " + componentId + "#" + field.getName() + ", invalid " + serviceClass.getName() + " service with " + filter); } final Object bean = bundleContext.getService(serviceRef); try { log.trace("Injecting {}#{} as {}", componentId, field.getName(), bean); FieldUtils.writeField(field, component, bean, true); serviceRefs.put(field, serviceRef); } catch (Exception e) { bundleContext.ungetService(serviceRef); serviceRefs.remove(field); throw new RuntimeException("Cannot set field " + componentId + "#" + field.getName() + " using " + serviceClass.getName() + " service with " + filter, e); } } if (!serviceRefs.isEmpty()) { log.debug("Injected {} services to {} in {}", serviceRefs.size(), componentId, phase); } } /** * Uninjects injected fields. * @param component * @param phase */ public void uninject(@Nonnull final Object component, @Nonnull final String componentId, @Nonnull final String phase) { if (!serviceRefs.isEmpty()) { log.debug("Uninjecting {} services from {} due to {}", serviceRefs.size(), componentId, phase); final Iterator<Entry<Field, ServiceReference<?>>> serviceRefIterator = serviceRefs.entrySet().iterator(); while (serviceRefIterator.hasNext()) { final Entry<Field, ServiceReference<?>> entry = serviceRefIterator.next(); final Field field = entry.getKey(); log.trace("Unsetting {}#{}", componentId, field.getName() ); try { FieldUtils.writeField(field, component, null, true); } catch (Exception e) { log.warn("Cannot unset " + componentId + "#" + field.getName(), e); } bundleContext.ungetService(entry.getValue()); serviceRefIterator.remove(); } } } }
true
true
public void inject(@Nonnull final Object component, @Nonnull final String componentId, @Nonnull final String phase) { final List<Field> nonSuppliedFields = ReflectionUtils.getNonSuppliedFields(component.getClass()); for (final Field field : nonSuppliedFields) { try { Object currentValue = FieldUtils.readField(field, component, true); if (currentValue != null) continue; } catch (IllegalAccessException e) { Throwables.propagate(e); return; } final Namespace namespaced = field.getAnnotation(Namespace.class); final String namespace = namespaced != null ? namespaced.value() : null; final String namespaceFilter = namespace != null ? "(namespace=" + namespace + ")" : ""; final Filter filtered = field.getAnnotation(Filter.class); final String additionalFilter = filtered != null ? filtered.value() : ""; final Class serviceClass = field.getType(); log.trace("Field {}#{} looking up {} for tenantId={} tenantEnv={} namespace={} filter: {}", componentId, field.getName(), serviceClass.getName(), tenantId, tenantEnv, namespace, additionalFilter ); final String filter = String.format("(&(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*)))", tenantId, tenantEnv, namespaceFilter, additionalFilter); final ServiceReference<?> serviceRef; try { final Collection<ServiceReference<?>> foundRefs = bundleContext.getServiceReferences(serviceClass, filter); if (foundRefs == null || foundRefs.isEmpty()) { throw new RuntimeException("Cannot inject " + componentId + "#" + field.getName() + ", " + serviceClass.getName() + " service with " + filter + " not found"); } serviceRef = foundRefs.iterator().next(); } catch (InvalidSyntaxException e) { throw new RuntimeException("Cannot inject " + componentId + "#" + field.getName() + ", invalid " + serviceClass.getName() + " service with " + filter); } final Object bean = bundleContext.getService(serviceRef); try { log.trace("Injecting {}#{} as {}", componentId, field.getName(), bean); FieldUtils.writeField(field, component, bean, true); serviceRefs.put(field, serviceRef); } catch (Exception e) { bundleContext.ungetService(serviceRef); serviceRefs.remove(field); throw new RuntimeException("Cannot set field " + componentId + "#" + field.getName() + " using " + serviceClass.getName() + " service with " + filter, e); } } if (!serviceRefs.isEmpty()) { log.debug("Injected {} services to {} in {}", serviceRefs.size(), componentId, phase); } }
public void inject(@Nonnull final Object component, @Nonnull final String componentId, @Nonnull final String phase) { final List<Field> nonSuppliedFields = ReflectionUtils.getNonSuppliedFields(component.getClass()); for (final Field field : nonSuppliedFields) { try { Object currentValue = FieldUtils.readField(field, component, true); if (currentValue != null) continue; } catch (IllegalAccessException e) { Throwables.propagate(e); return; } final Namespace namespaced = field.getAnnotation(Namespace.class); final String namespace = namespaced != null ? namespaced.value() : null; final String namespaceFilter = namespace != null ? "(namespace=" + namespace + ")" : ""; final Filter filtered = field.getAnnotation(Filter.class); final String additionalFilter = filtered != null ? filtered.value() : ""; final Class serviceClass = field.getType(); log.trace("Field {}#{} looking up {} for tenantId={} tenantEnv={} namespace={} filter: {}", componentId, field.getName(), serviceClass.getName(), tenantId, tenantEnv, namespace, additionalFilter ); final String filter = String.format("(&(|(tenantId=%s)(tenantId=\\*))(|(tenantEnv=%s)(tenantEnv=\\*))%s%s)", tenantId, tenantEnv, namespaceFilter, additionalFilter); final ServiceReference<?> serviceRef; try { final Collection<ServiceReference<?>> foundRefs = bundleContext.getServiceReferences(serviceClass, filter); if (foundRefs == null || foundRefs.isEmpty()) { throw new RuntimeException("Cannot inject " + componentId + "#" + field.getName() + ", " + serviceClass.getName() + " service with " + filter + " not found"); } serviceRef = foundRefs.iterator().next(); } catch (InvalidSyntaxException e) { throw new RuntimeException("Cannot inject " + componentId + "#" + field.getName() + ", invalid " + serviceClass.getName() + " service with " + filter); } final Object bean = bundleContext.getService(serviceRef); try { log.trace("Injecting {}#{} as {}", componentId, field.getName(), bean); FieldUtils.writeField(field, component, bean, true); serviceRefs.put(field, serviceRef); } catch (Exception e) { bundleContext.ungetService(serviceRef); serviceRefs.remove(field); throw new RuntimeException("Cannot set field " + componentId + "#" + field.getName() + " using " + serviceClass.getName() + " service with " + filter, e); } } if (!serviceRefs.isEmpty()) { log.debug("Injected {} services to {} in {}", serviceRefs.size(), componentId, phase); } }
diff --git a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java index 6cdd541d5..6c22873eb 100644 --- a/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java +++ b/bundles/org.eclipse.wst.sse.ui/src/org/eclipse/wst/sse/ui/internal/debug/ToggleBreakpointAction.java @@ -1,213 +1,213 @@ /******************************************************************************* * Copyright (c) 2001, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Jens Lukowski/Innoopract - initial renaming/restructuring * *******************************************************************************/ package org.eclipse.wst.sse.ui.internal.debug; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.content.IContentType; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IBreakpointManager; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.ui.DebugUITools; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jface.action.IAction; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.source.IVerticalRulerInfo; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.IDocumentProviderExtension4; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.wst.sse.core.StructuredModelManager; import org.eclipse.wst.sse.core.internal.provisional.IModelManager; import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel; import org.eclipse.wst.sse.core.internal.util.Debug; import org.eclipse.wst.sse.ui.internal.Logger; import org.eclipse.wst.sse.ui.internal.SSEUIMessages; import org.eclipse.wst.sse.ui.internal.SSEUIPlugin; import org.eclipse.wst.sse.ui.internal.extension.BreakpointProviderBuilder; import org.eclipse.wst.sse.ui.internal.provisional.extensions.ISourceEditingTextTools; import org.eclipse.wst.sse.ui.internal.provisional.extensions.breakpoint.IBreakpointProvider; /** * ToggleBreakpointAction */ public class ToggleBreakpointAction extends BreakpointRulerAction { IAction fFallbackAction; /** * @param editor * @param rulerInfo */ public ToggleBreakpointAction(ITextEditor editor, IVerticalRulerInfo rulerInfo) { super(editor, rulerInfo); setText(SSEUIMessages.ToggleBreakpointAction_0); //$NON-NLS-1$ setImageDescriptor(DebugUITools.getImageDescriptor(IDebugUIConstants.IMG_OBJS_BREAKPOINT)); } public ToggleBreakpointAction(ITextEditor editor, IVerticalRulerInfo rulerInfo, IAction fallbackAction) { this(editor, rulerInfo); fFallbackAction = fallbackAction; } protected boolean createBreakpoints(int lineNumber) { /* * Note: we'll always allow processing to continue, even for a "read * only" IStorageEditorInput, for the ActiveScript debugger. But this * means sometimes the ActiveScript provider might get an input from * CVS or something that is not related to debugging. */ ITextEditor editor = getTextEditor(); IEditorInput input = editor.getEditorInput(); IDocument document = editor.getDocumentProvider().getDocument(input); if (document == null) return false; String contentType = getContentType(document); IBreakpointProvider[] providers = BreakpointProviderBuilder.getInstance().getBreakpointProviders(editor, contentType, getFileExtension(input)); int pos = -1; ISourceEditingTextTools tools = (ISourceEditingTextTools) editor.getAdapter(ISourceEditingTextTools.class); if (tools != null) { pos = tools.getCaretOffset(); } final int n = providers.length; List errors = new ArrayList(0); for (int i = 0; i < n; i++) { try { if (Debug.debugBreakpoints) System.out.println(providers[i].getClass().getName() + " adding breakpoint to line " + lineNumber); //$NON-NLS-1$ IStatus status = providers[i].addBreakpoint(document, input, lineNumber, pos); if (status != null && !status.isOK()) { errors.add(status); } } catch (CoreException e) { errors.add(e.getStatus()); } catch (Exception t) { Logger.logException("exception while adding breakpoint", t); //$NON-NLS-1$ } } IStatus status = null; if (errors.size() > 0) { Shell shell = editor.getSite().getShell(); if (errors.size() > 1) { status = new MultiStatus(SSEUIPlugin.ID, IStatus.OK, (IStatus[]) errors.toArray(new IStatus[0]), SSEUIMessages.ManageBreakpoints_error_adding_message1, null); //$NON-NLS-1$ } else { status = (IStatus) errors.get(0); } if ((status.getSeverity() > IStatus.INFO) || (Platform.inDebugMode() && !status.isOK())) { Platform.getLog(SSEUIPlugin.getDefault().getBundle()).log(status); } /* * Show for conditions more severe than INFO or when no * breakpoints were created */ - if (status.getSeverity() > IStatus.INFO || getBreakpoints(getMarkers()).length < 1) { + if (status.getSeverity() > IStatus.INFO && getBreakpoints(getMarkers()).length < 1) { ErrorDialog.openError(shell, SSEUIMessages.ManageBreakpoints_error_adding_title1, status.getMessage(), status); //$NON-NLS-1$ //$NON-NLS-2$ return false; } } /* * Although no errors were reported, no breakpoints exist on this line * after having run the existing providers. Run the fallback action. */ if ((status == null || status.getSeverity() < IStatus.WARNING) && fFallbackAction != null && !hasMarkers()) { if (fFallbackAction instanceof ISelectionListener) { ((ISelectionListener) fFallbackAction).selectionChanged(null, null); } fFallbackAction.run(); } return true; } protected String getContentType(IDocument document) { IModelManager mgr = StructuredModelManager.getModelManager(); String contentType = null; IDocumentProvider provider = fTextEditor.getDocumentProvider(); if (provider instanceof IDocumentProviderExtension4) { try { IContentType type = ((IDocumentProviderExtension4) provider).getContentType(fTextEditor.getEditorInput()); if (type != null) contentType = type.getId(); } catch (CoreException e) { /* * A failure accessing the underlying store really isn't * interesting, although it can be a problem for * IStorageEditorInputs. */ } } if (contentType == null) { IStructuredModel model = null; try { model = mgr.getExistingModelForRead(document); if (model != null) { contentType = model.getContentTypeIdentifier(); } } finally { if (model != null) { model.releaseFromRead(); } } } return contentType; } protected void removeBreakpoints(int lineNumber) { IBreakpointManager breakpointManager = DebugPlugin.getDefault().getBreakpointManager(); IBreakpoint[] breakpoints = getBreakpoints(getMarkers()); for (int i = 0; i < breakpoints.length; i++) { try { breakpoints[i].getMarker().delete(); breakpointManager.removeBreakpoint(breakpoints[i], true); } catch (CoreException e) { Logger.logException(e); } } } public void run() { int lineNumber = fRulerInfo.getLineOfLastMouseButtonActivity() + 1; boolean doAdd = !hasMarkers(); if (doAdd) createBreakpoints(lineNumber); else removeBreakpoints(lineNumber); } /* * (non-Javadoc) * * @see org.eclipse.ui.texteditor.IUpdate#update() */ public void update() { } }
true
true
protected boolean createBreakpoints(int lineNumber) { /* * Note: we'll always allow processing to continue, even for a "read * only" IStorageEditorInput, for the ActiveScript debugger. But this * means sometimes the ActiveScript provider might get an input from * CVS or something that is not related to debugging. */ ITextEditor editor = getTextEditor(); IEditorInput input = editor.getEditorInput(); IDocument document = editor.getDocumentProvider().getDocument(input); if (document == null) return false; String contentType = getContentType(document); IBreakpointProvider[] providers = BreakpointProviderBuilder.getInstance().getBreakpointProviders(editor, contentType, getFileExtension(input)); int pos = -1; ISourceEditingTextTools tools = (ISourceEditingTextTools) editor.getAdapter(ISourceEditingTextTools.class); if (tools != null) { pos = tools.getCaretOffset(); } final int n = providers.length; List errors = new ArrayList(0); for (int i = 0; i < n; i++) { try { if (Debug.debugBreakpoints) System.out.println(providers[i].getClass().getName() + " adding breakpoint to line " + lineNumber); //$NON-NLS-1$ IStatus status = providers[i].addBreakpoint(document, input, lineNumber, pos); if (status != null && !status.isOK()) { errors.add(status); } } catch (CoreException e) { errors.add(e.getStatus()); } catch (Exception t) { Logger.logException("exception while adding breakpoint", t); //$NON-NLS-1$ } } IStatus status = null; if (errors.size() > 0) { Shell shell = editor.getSite().getShell(); if (errors.size() > 1) { status = new MultiStatus(SSEUIPlugin.ID, IStatus.OK, (IStatus[]) errors.toArray(new IStatus[0]), SSEUIMessages.ManageBreakpoints_error_adding_message1, null); //$NON-NLS-1$ } else { status = (IStatus) errors.get(0); } if ((status.getSeverity() > IStatus.INFO) || (Platform.inDebugMode() && !status.isOK())) { Platform.getLog(SSEUIPlugin.getDefault().getBundle()).log(status); } /* * Show for conditions more severe than INFO or when no * breakpoints were created */ if (status.getSeverity() > IStatus.INFO || getBreakpoints(getMarkers()).length < 1) { ErrorDialog.openError(shell, SSEUIMessages.ManageBreakpoints_error_adding_title1, status.getMessage(), status); //$NON-NLS-1$ //$NON-NLS-2$ return false; } } /* * Although no errors were reported, no breakpoints exist on this line * after having run the existing providers. Run the fallback action. */ if ((status == null || status.getSeverity() < IStatus.WARNING) && fFallbackAction != null && !hasMarkers()) { if (fFallbackAction instanceof ISelectionListener) { ((ISelectionListener) fFallbackAction).selectionChanged(null, null); } fFallbackAction.run(); } return true; }
protected boolean createBreakpoints(int lineNumber) { /* * Note: we'll always allow processing to continue, even for a "read * only" IStorageEditorInput, for the ActiveScript debugger. But this * means sometimes the ActiveScript provider might get an input from * CVS or something that is not related to debugging. */ ITextEditor editor = getTextEditor(); IEditorInput input = editor.getEditorInput(); IDocument document = editor.getDocumentProvider().getDocument(input); if (document == null) return false; String contentType = getContentType(document); IBreakpointProvider[] providers = BreakpointProviderBuilder.getInstance().getBreakpointProviders(editor, contentType, getFileExtension(input)); int pos = -1; ISourceEditingTextTools tools = (ISourceEditingTextTools) editor.getAdapter(ISourceEditingTextTools.class); if (tools != null) { pos = tools.getCaretOffset(); } final int n = providers.length; List errors = new ArrayList(0); for (int i = 0; i < n; i++) { try { if (Debug.debugBreakpoints) System.out.println(providers[i].getClass().getName() + " adding breakpoint to line " + lineNumber); //$NON-NLS-1$ IStatus status = providers[i].addBreakpoint(document, input, lineNumber, pos); if (status != null && !status.isOK()) { errors.add(status); } } catch (CoreException e) { errors.add(e.getStatus()); } catch (Exception t) { Logger.logException("exception while adding breakpoint", t); //$NON-NLS-1$ } } IStatus status = null; if (errors.size() > 0) { Shell shell = editor.getSite().getShell(); if (errors.size() > 1) { status = new MultiStatus(SSEUIPlugin.ID, IStatus.OK, (IStatus[]) errors.toArray(new IStatus[0]), SSEUIMessages.ManageBreakpoints_error_adding_message1, null); //$NON-NLS-1$ } else { status = (IStatus) errors.get(0); } if ((status.getSeverity() > IStatus.INFO) || (Platform.inDebugMode() && !status.isOK())) { Platform.getLog(SSEUIPlugin.getDefault().getBundle()).log(status); } /* * Show for conditions more severe than INFO or when no * breakpoints were created */ if (status.getSeverity() > IStatus.INFO && getBreakpoints(getMarkers()).length < 1) { ErrorDialog.openError(shell, SSEUIMessages.ManageBreakpoints_error_adding_title1, status.getMessage(), status); //$NON-NLS-1$ //$NON-NLS-2$ return false; } } /* * Although no errors were reported, no breakpoints exist on this line * after having run the existing providers. Run the fallback action. */ if ((status == null || status.getSeverity() < IStatus.WARNING) && fFallbackAction != null && !hasMarkers()) { if (fFallbackAction instanceof ISelectionListener) { ((ISelectionListener) fFallbackAction).selectionChanged(null, null); } fFallbackAction.run(); } return true; }
diff --git a/src/com/zwitserloot/cmdreader/CmdReader.java b/src/com/zwitserloot/cmdreader/CmdReader.java index 2cfc738..e690bbe 100644 --- a/src/com/zwitserloot/cmdreader/CmdReader.java +++ b/src/com/zwitserloot/cmdreader/CmdReader.java @@ -1,499 +1,503 @@ package com.zwitserloot.cmdreader; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; /** * Parses command line arguments. * * The CmdReader can turn strings like<br> * <code>-fmv /foo/bar /bar/baz --color=white *.xyzzy *.cheese</code><br> * into something that easier to work with programatically. * <p> * To use it, first create a 'descriptor' class; this is a class that contains just fields and no code. * Each field represents a command line option. Annotate it with the various annotations in the cmdreader package * to influence its behaviour. A short description of all annotations (they are all optional): * <dl> * <dt>FullName * <dd>(defaults to field name). The name of the option. Used in the Excludes and Mandatory annotations, * and also allowed on the command line itself as --fullname(=value) * <dt>Shorthand * <dd>Instead of --fullname, -shorthand is also allowed. You can have as many shorthands as you want. Usually single characters. * <dt>Description * <dd>A human readable description of the field. Used to auto-generate command line help. * <dt>Excludes * <dd>A list of names (see FullName) that cannot co-exist together with this option. If this option is present * as well as one of the excluded ones, an error will be generated. * <dt>Mandatory * <dd>Indicates that the option must be present. You may optionally specify 'onlyIf' and 'onlyIfNot', which are lists of * names (see FullName). onlyIf means: This is mandatory only if at least one of these options is present. onlyIfNot means: * I am not optional only if one of these options is present, otherwise I am optional. * <dt>Parameterized * <dd>I take a parameter. If using the longhard form, the syntax is --fullname=value but for shorthand it's -shorthand value. * If this annotation isn't there, the type of your field must be boolean. Otherwise, it can be any primitive, or String, * or an array or Collection of a primitive or String. In the latter case, the option may appear multiple times. If the string * cannot be coerced to the provided type (via e.g. Integer.parseInt) a command line error is generated with a useful message. * If using a Collection, you must (A) initialize the field yourself, and (B) use generics. * <dt>Sequential * <dd>Use me if there is no option name. In other words, those command line options that do not 'belong' to a -something, * go here. You can have as many as you like, but only the last one can be a List or array. It is an error if a Sequential * annotated field is not also parameterized. * </dl> * * Fields that do not show up aren't modified, so if you want a default, just set the field in the descriptor class. */ public class CmdReader<T> { private final Class<T> settingsDescriptor; private final List<ParseItem> items; private final Map<Character, ParseItem> shorthands; private final List<ParseItem> seqList; private CmdReader(Class<T> settingsDescriptor) { this.settingsDescriptor = settingsDescriptor; this.items = Collections.unmodifiableList(init()); this.shorthands = ParseItem.makeShortHandMap(this.items); this.seqList = makeSeqList(this.items); } /** * Create a new CmdReader with the specified class as the template that defines what each option means. * * See the class javadoc for more information on how to make these classes. * * @param settingsDescriptor Class with fields which will be filled with the command line variables. * @throws IllegalArgumentException If the <em>settingsDescriptor</em> contains flaws, for example * if two different fields both use the same 'full name'. See the class javadoc for a more complete list of causes. */ public static <T> CmdReader<T> of(Class<T> settingsDescriptor) { return new CmdReader<T>(settingsDescriptor); } private List<ParseItem> init() { Class<?> c = settingsDescriptor; List<ParseItem> out = new ArrayList<ParseItem>(); while (c != Object.class) { Field[] fields = settingsDescriptor.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (Modifier.isStatic(field.getModifiers())) continue; out.add(new ParseItem(field)); } c = c.getSuperclass(); } ParseItem.multiSanityChecks(out); return out; } private static List<ParseItem> makeSeqList(List<ParseItem> items) { List<ParseItem> list = new ArrayList<ParseItem>(); for (ParseItem item : items) if (item.isSeq()) list.add(item); return list; } private static final int SCREEN_WIDTH = 72; /** * Generates an extensive string explaining the command line options. * You should print this if the make() method throws an InvalidCommandLineException, for example. * The detail lies between your average GNU manpage and your average GNU command's output if you specify --help. * * Is automatically wordwrapped at standard screen width (72 characters). Specific help for each option is mostly * gleaned from the {@link com.zwitserloot.cmdreader.Description} annotations. * * @param commandName used to prefix the example usages. */ public String generateCommandLineHelp(String commandName) { StringBuilder out = new StringBuilder(); int maxFullName = 0; int maxShorthand = 0; for (ParseItem item : items) { if (item.isSeq()) continue; maxFullName = Math.max(maxFullName, item.getFullName().length() + (item.isParameterized() ? 4 : 0)); maxShorthand = Math.max(maxShorthand, item.getShorthand().length()); } if (maxShorthand > 0) maxShorthand++; generateShortSummary(commandName, out); generateSequentialArgsHelp(out); generateMandatoryArgsHelp(maxFullName, maxShorthand, out); generateOptionalArgsHelp(maxFullName, maxShorthand, out); return out.toString(); } private void generateShortSummary(String commandName, StringBuilder out) { if (commandName != null && commandName.length() > 0) out.append(commandName).append(" "); StringBuilder sb = new StringBuilder(); for (ParseItem item : items) if (!item.isSeq() && !item.isMandatory()) sb.append(item.getShorthand()); if (sb.length() > 0) { out.append("[-").append(sb).append("] "); sb.setLength(0); } for (ParseItem item : items) if (!item.isSeq() && item.isMandatory()) sb.append(item.getShorthand()); if (sb.length() > 0) { out.append("-").append(sb).append(" "); sb.setLength(0); } for (ParseItem item : items) if (!item.isSeq() && item.isMandatory() && item.getShorthand().length() == 0) { out.append("--").append(item.getFullName()).append("=val "); } for (ParseItem item : items) if (item.isSeq()) { if (!item.isMandatory()) out.append('['); out.append(item.getFullName()); if (!item.isMandatory()) out.append(']'); out.append(' '); } out.append("\n"); } private void generateSequentialArgsHelp(StringBuilder out) { List<ParseItem> items = new ArrayList<ParseItem>(); for (ParseItem item : this.items) if (item.isSeq() && item.getFullDescription().length() > 0) items.add(item); if (items.size() == 0) return; int maxSeqArg = 0; for (ParseItem item : items) maxSeqArg = Math.max(maxSeqArg, item.getFullName().length()); out.append("\n Sequential arguments:\n"); for (ParseItem item : items) generateSequentialArgHelp(maxSeqArg, item, out); } private void generateMandatoryArgsHelp(int maxFullName, int maxShorthand, StringBuilder out) { List<ParseItem> items = new ArrayList<ParseItem>(); for (ParseItem item : this.items) if (item.isMandatory() && !item.isSeq()) items.add(item); if (items.size() == 0) return; out.append("\n Mandatory arguments:\n"); for (ParseItem item : items) generateArgHelp(maxFullName, maxShorthand, item, out); } private void generateOptionalArgsHelp(int maxFullName, int maxShorthand, StringBuilder out) { List<ParseItem> items = new ArrayList<ParseItem>(); for (ParseItem item : this.items) if (!item.isMandatory() && !item.isSeq()) items.add(item); if (items.size() == 0) return; out.append("\n Optional arguments:\n"); for (ParseItem item : items) generateArgHelp(maxFullName, maxShorthand, item, out); } private void generateArgHelp(int maxFullName, int maxShorthand, ParseItem item, StringBuilder out) { out.append(" "); String fn = item.getFullName() + (item.isParameterized() ? "=val" : ""); out.append(String.format("--%-" + maxFullName + "s ", fn)); String sh = item.getShorthand().length() == 0 ? "" : "-" + item.getShorthand(); out.append(String.format("%-" + maxShorthand + "s ", sh)); int left = SCREEN_WIDTH - 8 - maxShorthand - maxFullName; String description = item.getFullDescription(); if (description.length() == 0 || description.length() < left) { out.append(description).append("\n"); return; } for (String line : wordbreak(item.getFullDescription(), SCREEN_WIDTH -8)) { out.append("\n ").append(line); } out.append("\n"); } private void generateSequentialArgHelp(int maxSeqArg, ParseItem item, StringBuilder out) { out.append(" "); out.append(String.format("%-" + maxSeqArg + "s ", item.getFullName())); int left = SCREEN_WIDTH - 7 - maxSeqArg; String description = item.getFullDescription(); if (description.length() == 0 || description.length() < left) { out.append(description).append("\n"); return; } for (String line : wordbreak(item.getFullDescription(), SCREEN_WIDTH -8)) { out.append("\n ").append(line); } out.append("\n"); } private static List<String> wordbreak(String text, int width) { StringBuilder line = new StringBuilder(); List<String> out = new ArrayList<String>(); int lastSpace = -1; for (char c : text.toCharArray()) { if (c == '\t') c = ' '; if (c == '\n') { out.add(line.toString()); line.setLength(0); lastSpace = -1; continue; } if (c == ' ') { lastSpace = line.length(); line.append(' '); } else line.append(c); if (line.length() > width && lastSpace > 8) { out.add(line.substring(0, lastSpace)); String left = line.substring(lastSpace+1); line.setLength(0); line.append(left); lastSpace = -1; } } if (line.length() > 0) out.add(line.toString()); return out; } /** * Parses the provided command line into an instance of your command line descriptor class. * * The string is split on spaces. However, quote symbols can be used to prevent this behaviour. To write literal quotes, * use the \ escape. a double \\ is seen as a single backslash. * * @param in A command line string, such as -frl "foo bar" * @throws InvalidCommandLineException If the user entered a wrong command line. * The exception's message is english and human readable - print it back to the user! * @throws IllegalArgumentException If your descriptor class has a bug in it. A list of causes can be found in the class javadoc. */ public T make(String in) throws InvalidCommandLineException, IllegalArgumentException { List<String> out = new ArrayList<String>(); StringBuilder sb = new StringBuilder(); boolean inQuote = false; boolean inBack = false; for (char c : in.toCharArray()) { if (inBack) { inBack = false; if (c == '\n') continue; sb.append(c); } if (c == '\\') { inBack = true; continue; } if (c == '"') { inQuote = !inQuote; continue; } if (c == ' ' && !inQuote) { String p = sb.toString(); sb.setLength(0); if (p.equals("")) continue; out.add(p); } } return make(out.toArray(new String[out.size()])); } /** * Parses the provided command line into an instance of your command line descriptor class. * * Each part of the string array is taken literally as a single argument; quotes are not parsed and things are not split * on spaces. Normally the shell does this for you. * * If you want to parse the String[] passed to java <code>main</code> methods, use this method. * * @param in A command line string chopped into pieces, such as ["-frl", "foo bar"]. * @throws InvalidCommandLineException If the user entered a wrong command line. * The exception's message is english and human readable - print it back to the user! * @throws IllegalArgumentException If your descriptor class has a bug in it. A list of causes can be found in the class javadoc. */ public T make(String[] in) throws InvalidCommandLineException { final T obj = construct(); if (in == null) in = new String[0]; int seq = 0; class State { List<ParseItem> used = new ArrayList<ParseItem>(); void handle(ParseItem item, String value) { item.set(obj, value); used.add(item); } void finish() throws InvalidCommandLineException { checkForGlobalMandatories(); checkForExcludes(); checkForRequires(); checkForMandatoriesIf(); checkForMandatoriesIfNot(); } private void checkForGlobalMandatories() throws InvalidCommandLineException { for (ParseItem item : items) if (item.isMandatory() && !used.contains(item)) throw new InvalidCommandLineException( "You did not specify mandatory parameter " + item.getFullName()); } private void checkForExcludes() throws InvalidCommandLineException { for (ParseItem item : items) if (used.contains(item)) { for (String n : item.getExcludes()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) throw new InvalidCommandLineException( "You specified parameter " + i.getFullName() + " which cannot be used together with " + item.getFullName()); } } } private void checkForRequires() throws InvalidCommandLineException { for (ParseItem item : items) if (used.contains(item)) { for (String n : item.getRequires()) { for (ParseItem i : items) if (i.getFullName().equals(n) && !used.contains(i)) throw new InvalidCommandLineException( "You specified parameter " + item.getFullName() + " which requires that you also supply " + i.getFullName()); } } } private void checkForMandatoriesIf() throws InvalidCommandLineException { for (ParseItem item : items) { if (used.contains(item) || item.getMandatoryIf().size() == 0) continue; for (String n : item.getMandatoryIf()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) throw new InvalidCommandLineException( "You did not specify parameter " + item.getFullName() + " which is mandatory if you use " + i.getFullName()); } } } private void checkForMandatoriesIfNot() throws InvalidCommandLineException { nextItem: for (ParseItem item : items) { if (used.contains(item) || item.getMandatoryIfNot().size() == 0) continue; for (String n : item.getMandatoryIfNot()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) continue nextItem; } StringBuilder alternatives = new StringBuilder(); if (item.getMandatoryIfNot().size() > 1) alternatives.append("one of "); for (String n : item.getMandatoryIfNot()) alternatives.append(n).append(", "); alternatives.setLength(alternatives.length() - 2); throw new InvalidCommandLineException( "You did not specify parameter " + item.getFullName() + " which is mandatory unless you use " + alternatives); } } } State state = new State(); for (int i = 0; i < in.length; i++) { if (in[i].startsWith("--")) { int idx = in[i].indexOf('='); String key = idx == -1 ? in[i].substring(2) : in[i].substring(2, idx); String value = idx == -1 ? "" : in[i].substring(idx+1); if (value.length() == 0 && idx != -1) throw new InvalidCommandLineException( "invalid command line argument - you should write something after the '=': " + in[i]); boolean handled = false; for (ParseItem item : items) if (item.getFullName().equalsIgnoreCase(key)) { - if (item.isParameterized() && value.length() == 0) throw new InvalidCommandLineException(String.format( - "invalid command line argument - %s requires a parameter but there is none.", key)); - state.handle(item, idx == -1 ? null : value); + if (item.isParameterized() && value.length() == 0) { + if (i < in.length - 1 && !in[i+1].startsWith("-")) value = in[++i]; + else throw new InvalidCommandLineException(String.format( + "invalid command line argument - %s requires a parameter but there is none.", key)); + } + state.handle(item, !item.isParameterized() && value.length() == 0 ? null : value); handled = true; break; } if (!handled) throw new InvalidCommandLineException( "invalid command line argument - I don't know about that option: " + in[i]); } else if (in[i].startsWith("-")) { for (char c : in[i].substring(1).toCharArray()) { ParseItem item = shorthands.get(c); if (item == null) throw new InvalidCommandLineException(String.format( "invalid command line argument - %s is not a known option: %s", c, in[i])); if (item.isParameterized()) { - if (i == in.length-1) throw new InvalidCommandLineException(String.format( + String value; + if (i < in.length - 1 && !in[i+1].startsWith("-")) value = in[++i]; + else throw new InvalidCommandLineException(String.format( "invalid command line argument - %s requires a parameter but there is none.", c)); - String value = in[++i]; state.handle(item, value); } else state.handle(item, null); } } else { seq++; if (seqList.size() < seq) { if (seqList.size() > 0 && seqList.get(seqList.size()-1).isCollection()) { state.handle(seqList.get(seqList.size()-1), in[i]); } else throw new InvalidCommandLineException(String.format( "invalid command line argument - you've provided too many free-standing arguments: %s", in[i])); } else { ParseItem item = seqList.get(seq-1); state.handle(item, in[i]); } } } state.finish(); return obj; } private T construct() { try { Constructor<T> constructor = settingsDescriptor.getDeclaredConstructor(); constructor.setAccessible(true); return constructor.newInstance(); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(String.format( "A CmdReader class must have a no-args constructor: %s", settingsDescriptor)); } catch (InstantiationException e) { throw new IllegalArgumentException(String.format( "A CmdReader class must not be an interface or abstract: %s", settingsDescriptor)); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Huh?"); } catch (InvocationTargetException e) { throw new IllegalArgumentException( "Exception occurred when constructing CmdReader class " + settingsDescriptor, e.getCause()); } } /** * Turns a list of strings, such as "Hello", "World!" into a single string, each element separated by a space. * Use it if you want to grab the rest of the command line as a single string, spaces and all; include a @Sequential * List of Strings and run squash on it to do this. */ public static String squash(Collection<String> collection) { Iterator<String> i = collection.iterator(); StringBuilder out = new StringBuilder(); while (i.hasNext()) { out.append(i.next()); if (i.hasNext()) out.append(' '); } return out.toString(); } }
false
true
public T make(String[] in) throws InvalidCommandLineException { final T obj = construct(); if (in == null) in = new String[0]; int seq = 0; class State { List<ParseItem> used = new ArrayList<ParseItem>(); void handle(ParseItem item, String value) { item.set(obj, value); used.add(item); } void finish() throws InvalidCommandLineException { checkForGlobalMandatories(); checkForExcludes(); checkForRequires(); checkForMandatoriesIf(); checkForMandatoriesIfNot(); } private void checkForGlobalMandatories() throws InvalidCommandLineException { for (ParseItem item : items) if (item.isMandatory() && !used.contains(item)) throw new InvalidCommandLineException( "You did not specify mandatory parameter " + item.getFullName()); } private void checkForExcludes() throws InvalidCommandLineException { for (ParseItem item : items) if (used.contains(item)) { for (String n : item.getExcludes()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) throw new InvalidCommandLineException( "You specified parameter " + i.getFullName() + " which cannot be used together with " + item.getFullName()); } } } private void checkForRequires() throws InvalidCommandLineException { for (ParseItem item : items) if (used.contains(item)) { for (String n : item.getRequires()) { for (ParseItem i : items) if (i.getFullName().equals(n) && !used.contains(i)) throw new InvalidCommandLineException( "You specified parameter " + item.getFullName() + " which requires that you also supply " + i.getFullName()); } } } private void checkForMandatoriesIf() throws InvalidCommandLineException { for (ParseItem item : items) { if (used.contains(item) || item.getMandatoryIf().size() == 0) continue; for (String n : item.getMandatoryIf()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) throw new InvalidCommandLineException( "You did not specify parameter " + item.getFullName() + " which is mandatory if you use " + i.getFullName()); } } } private void checkForMandatoriesIfNot() throws InvalidCommandLineException { nextItem: for (ParseItem item : items) { if (used.contains(item) || item.getMandatoryIfNot().size() == 0) continue; for (String n : item.getMandatoryIfNot()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) continue nextItem; } StringBuilder alternatives = new StringBuilder(); if (item.getMandatoryIfNot().size() > 1) alternatives.append("one of "); for (String n : item.getMandatoryIfNot()) alternatives.append(n).append(", "); alternatives.setLength(alternatives.length() - 2); throw new InvalidCommandLineException( "You did not specify parameter " + item.getFullName() + " which is mandatory unless you use " + alternatives); } } } State state = new State(); for (int i = 0; i < in.length; i++) { if (in[i].startsWith("--")) { int idx = in[i].indexOf('='); String key = idx == -1 ? in[i].substring(2) : in[i].substring(2, idx); String value = idx == -1 ? "" : in[i].substring(idx+1); if (value.length() == 0 && idx != -1) throw new InvalidCommandLineException( "invalid command line argument - you should write something after the '=': " + in[i]); boolean handled = false; for (ParseItem item : items) if (item.getFullName().equalsIgnoreCase(key)) { if (item.isParameterized() && value.length() == 0) throw new InvalidCommandLineException(String.format( "invalid command line argument - %s requires a parameter but there is none.", key)); state.handle(item, idx == -1 ? null : value); handled = true; break; } if (!handled) throw new InvalidCommandLineException( "invalid command line argument - I don't know about that option: " + in[i]); } else if (in[i].startsWith("-")) { for (char c : in[i].substring(1).toCharArray()) { ParseItem item = shorthands.get(c); if (item == null) throw new InvalidCommandLineException(String.format( "invalid command line argument - %s is not a known option: %s", c, in[i])); if (item.isParameterized()) { if (i == in.length-1) throw new InvalidCommandLineException(String.format( "invalid command line argument - %s requires a parameter but there is none.", c)); String value = in[++i]; state.handle(item, value); } else state.handle(item, null); } } else { seq++; if (seqList.size() < seq) { if (seqList.size() > 0 && seqList.get(seqList.size()-1).isCollection()) { state.handle(seqList.get(seqList.size()-1), in[i]); } else throw new InvalidCommandLineException(String.format( "invalid command line argument - you've provided too many free-standing arguments: %s", in[i])); } else { ParseItem item = seqList.get(seq-1); state.handle(item, in[i]); } } } state.finish(); return obj; }
public T make(String[] in) throws InvalidCommandLineException { final T obj = construct(); if (in == null) in = new String[0]; int seq = 0; class State { List<ParseItem> used = new ArrayList<ParseItem>(); void handle(ParseItem item, String value) { item.set(obj, value); used.add(item); } void finish() throws InvalidCommandLineException { checkForGlobalMandatories(); checkForExcludes(); checkForRequires(); checkForMandatoriesIf(); checkForMandatoriesIfNot(); } private void checkForGlobalMandatories() throws InvalidCommandLineException { for (ParseItem item : items) if (item.isMandatory() && !used.contains(item)) throw new InvalidCommandLineException( "You did not specify mandatory parameter " + item.getFullName()); } private void checkForExcludes() throws InvalidCommandLineException { for (ParseItem item : items) if (used.contains(item)) { for (String n : item.getExcludes()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) throw new InvalidCommandLineException( "You specified parameter " + i.getFullName() + " which cannot be used together with " + item.getFullName()); } } } private void checkForRequires() throws InvalidCommandLineException { for (ParseItem item : items) if (used.contains(item)) { for (String n : item.getRequires()) { for (ParseItem i : items) if (i.getFullName().equals(n) && !used.contains(i)) throw new InvalidCommandLineException( "You specified parameter " + item.getFullName() + " which requires that you also supply " + i.getFullName()); } } } private void checkForMandatoriesIf() throws InvalidCommandLineException { for (ParseItem item : items) { if (used.contains(item) || item.getMandatoryIf().size() == 0) continue; for (String n : item.getMandatoryIf()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) throw new InvalidCommandLineException( "You did not specify parameter " + item.getFullName() + " which is mandatory if you use " + i.getFullName()); } } } private void checkForMandatoriesIfNot() throws InvalidCommandLineException { nextItem: for (ParseItem item : items) { if (used.contains(item) || item.getMandatoryIfNot().size() == 0) continue; for (String n : item.getMandatoryIfNot()) { for (ParseItem i : items) if (i.getFullName().equals(n) && used.contains(i)) continue nextItem; } StringBuilder alternatives = new StringBuilder(); if (item.getMandatoryIfNot().size() > 1) alternatives.append("one of "); for (String n : item.getMandatoryIfNot()) alternatives.append(n).append(", "); alternatives.setLength(alternatives.length() - 2); throw new InvalidCommandLineException( "You did not specify parameter " + item.getFullName() + " which is mandatory unless you use " + alternatives); } } } State state = new State(); for (int i = 0; i < in.length; i++) { if (in[i].startsWith("--")) { int idx = in[i].indexOf('='); String key = idx == -1 ? in[i].substring(2) : in[i].substring(2, idx); String value = idx == -1 ? "" : in[i].substring(idx+1); if (value.length() == 0 && idx != -1) throw new InvalidCommandLineException( "invalid command line argument - you should write something after the '=': " + in[i]); boolean handled = false; for (ParseItem item : items) if (item.getFullName().equalsIgnoreCase(key)) { if (item.isParameterized() && value.length() == 0) { if (i < in.length - 1 && !in[i+1].startsWith("-")) value = in[++i]; else throw new InvalidCommandLineException(String.format( "invalid command line argument - %s requires a parameter but there is none.", key)); } state.handle(item, !item.isParameterized() && value.length() == 0 ? null : value); handled = true; break; } if (!handled) throw new InvalidCommandLineException( "invalid command line argument - I don't know about that option: " + in[i]); } else if (in[i].startsWith("-")) { for (char c : in[i].substring(1).toCharArray()) { ParseItem item = shorthands.get(c); if (item == null) throw new InvalidCommandLineException(String.format( "invalid command line argument - %s is not a known option: %s", c, in[i])); if (item.isParameterized()) { String value; if (i < in.length - 1 && !in[i+1].startsWith("-")) value = in[++i]; else throw new InvalidCommandLineException(String.format( "invalid command line argument - %s requires a parameter but there is none.", c)); state.handle(item, value); } else state.handle(item, null); } } else { seq++; if (seqList.size() < seq) { if (seqList.size() > 0 && seqList.get(seqList.size()-1).isCollection()) { state.handle(seqList.get(seqList.size()-1), in[i]); } else throw new InvalidCommandLineException(String.format( "invalid command line argument - you've provided too many free-standing arguments: %s", in[i])); } else { ParseItem item = seqList.get(seq-1); state.handle(item, in[i]); } } } state.finish(); return obj; }
diff --git a/source/org/jivesoftware/smack/util/XmlUtil.java b/source/org/jivesoftware/smack/util/XmlUtil.java index 7100e149..611410f5 100644 --- a/source/org/jivesoftware/smack/util/XmlUtil.java +++ b/source/org/jivesoftware/smack/util/XmlUtil.java @@ -1,210 +1,210 @@ /** * Copyright 2011 Glenn Maynard * * All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jivesoftware.smack.util; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; public class XmlUtil { /** * Parse an XML document, and return the resulting {@link Document}. * * @throws SAXException if XML parsing fails * @throws IOException if reading from stream fails */ public static Document parseXML(InputSource stream) throws SAXException, IOException { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); dbfac.setNamespaceAware(true); DocumentBuilder docBuilder; try { docBuilder = dbfac.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } return docBuilder.parse(stream); } /** * Parse an XML document, and return the resulting root {@link Node}. * * @throws SAXException if XML parsing fails * @throws IOException if reading from stream fails */ public static Element getXMLRootNode(InputSource stream) throws SAXException, IOException { Document doc = parseXML(stream); for(Element data: XmlUtil.getChildElements(doc)) return data; throw new RuntimeException("Document had no root node"); } /** * Return an iterable Collection<Node> of the child Elements of the specified * node. * * @param parent The parent node. * @return A collection of child nodes. */ public static Collection<Element> getChildElements(Node node) { NodeList children = node.getChildNodes(); ArrayList<Element> result = new ArrayList<Element>(children.getLength()); for(int i = 0; i < children.getLength(); ++i) { Node child = children.item(i); if(!(child instanceof Element)) continue; result.add((Element) child); } return result; } /** * Implement Node.getTextContent(), which isn't available in DOM Level 2. */ public static String getTextContent(Node node) { String result = ""; if(node instanceof Text) result = ((Text) node).getData(); for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) result += getTextContent(child); return result; } /** * Return the current XML element as a string. * @param an {@link XmlPullParser} with a current event type of START_TAG * @return an XML string */ public static String parserNodeToString(XmlPullParser parser) throws XmlPullParserException, IOException { StringBuilder content = new StringBuilder(); parserNodeToString(content, parser, new HashMap<String, String>()); return content.toString(); } private static void parserNodeToString(StringBuilder content, XmlPullParser parser, Map<String, String> namespaceNodes) throws XmlPullParserException, IOException { // This is made more complicated due to many XmlPullParser implementations // support neither FEATURE_XML_ROUNDTRIP nor FEATURE_REPORT_NAMESPACE_ATTRIBUTES. if (parser.getEventType() != XmlPullParser.START_TAG) throw new IllegalArgumentException("parseContent must start at a start tag"); { HashMap<String,String> neededNamespaces = new HashMap<String,String>(); content.append("<"); // Append the element prefix, if any. String elemPrefix = parser.getPrefix(); if(elemPrefix != null) content.append(elemPrefix + ":"); neededNamespaces.put(elemPrefix == null? "":elemPrefix, parser.getNamespace()); content.append(parser.getName()); for(int i = 0; i < parser.getAttributeCount(); ++i) { content.append(" "); // Append the attribute prefix, if any. String attrPrefix = parser.getAttributePrefix(i); if(attrPrefix != null) neededNamespaces.put(attrPrefix, parser.getAttributeNamespace(i)); if(attrPrefix != null) content.append(attrPrefix + ":"); String attrName = parser.getAttributeName(i); content.append(attrName + "='"); String attrValue = parser.getAttributeValue(i); content.append(StringUtils.escapeForXML(attrValue)); content.append("'"); } // Check the prefixes used by this element and its attributes for ones that // aren't already declared, and output new xmlns attributes as needed. boolean clonedNamespaceMap = false; for(Map.Entry<String,String> entry: neededNamespaces.entrySet()) { String prefix = entry.getKey(); String namespace = entry.getValue(); String existingNamespace = namespaceNodes.get(prefix); if(existingNamespace != null && existingNamespace.equals(namespace)) continue; // This is a new or changed namespace prefix. Make a copy of the namespace // map, if we havn't already, and output a namespace declaration. if(!clonedNamespaceMap) { clonedNamespaceMap = true; HashMap<String, String> clonedNodes = new HashMap<String, String>(); clonedNodes.putAll(namespaceNodes); namespaceNodes = clonedNodes; } namespaceNodes.put(prefix, namespace); content.append(" xmlns"); - if(!prefix.isEmpty()) + if(prefix.length() == 0) content.append(":" + prefix); content.append("='"); content.append(StringUtils.escapeForXML(namespace)); content.append("'"); } content.append(">"); } while (true) { parser.next(); switch(parser.getEventType()) { case XmlPullParser.START_TAG: parserNodeToString(content, parser, namespaceNodes); break; case XmlPullParser.END_TAG: content.append("</"); if(parser.getPrefix() != null) content.append(parser.getPrefix() + ":"); content.append(parser.getName() + ">"); return; case XmlPullParser.END_DOCUMENT: return; default: String text = parser.getText(); if(text == null) throw new RuntimeException("Unexpected null result from parser.getText"); content.append(StringUtils.escapeForXML(text)); break; } } } };
true
true
private static void parserNodeToString(StringBuilder content, XmlPullParser parser, Map<String, String> namespaceNodes) throws XmlPullParserException, IOException { // This is made more complicated due to many XmlPullParser implementations // support neither FEATURE_XML_ROUNDTRIP nor FEATURE_REPORT_NAMESPACE_ATTRIBUTES. if (parser.getEventType() != XmlPullParser.START_TAG) throw new IllegalArgumentException("parseContent must start at a start tag"); { HashMap<String,String> neededNamespaces = new HashMap<String,String>(); content.append("<"); // Append the element prefix, if any. String elemPrefix = parser.getPrefix(); if(elemPrefix != null) content.append(elemPrefix + ":"); neededNamespaces.put(elemPrefix == null? "":elemPrefix, parser.getNamespace()); content.append(parser.getName()); for(int i = 0; i < parser.getAttributeCount(); ++i) { content.append(" "); // Append the attribute prefix, if any. String attrPrefix = parser.getAttributePrefix(i); if(attrPrefix != null) neededNamespaces.put(attrPrefix, parser.getAttributeNamespace(i)); if(attrPrefix != null) content.append(attrPrefix + ":"); String attrName = parser.getAttributeName(i); content.append(attrName + "='"); String attrValue = parser.getAttributeValue(i); content.append(StringUtils.escapeForXML(attrValue)); content.append("'"); } // Check the prefixes used by this element and its attributes for ones that // aren't already declared, and output new xmlns attributes as needed. boolean clonedNamespaceMap = false; for(Map.Entry<String,String> entry: neededNamespaces.entrySet()) { String prefix = entry.getKey(); String namespace = entry.getValue(); String existingNamespace = namespaceNodes.get(prefix); if(existingNamespace != null && existingNamespace.equals(namespace)) continue; // This is a new or changed namespace prefix. Make a copy of the namespace // map, if we havn't already, and output a namespace declaration. if(!clonedNamespaceMap) { clonedNamespaceMap = true; HashMap<String, String> clonedNodes = new HashMap<String, String>(); clonedNodes.putAll(namespaceNodes); namespaceNodes = clonedNodes; } namespaceNodes.put(prefix, namespace); content.append(" xmlns"); if(!prefix.isEmpty()) content.append(":" + prefix); content.append("='"); content.append(StringUtils.escapeForXML(namespace)); content.append("'"); } content.append(">"); } while (true) { parser.next(); switch(parser.getEventType()) { case XmlPullParser.START_TAG: parserNodeToString(content, parser, namespaceNodes); break; case XmlPullParser.END_TAG: content.append("</"); if(parser.getPrefix() != null) content.append(parser.getPrefix() + ":"); content.append(parser.getName() + ">"); return; case XmlPullParser.END_DOCUMENT: return; default: String text = parser.getText(); if(text == null) throw new RuntimeException("Unexpected null result from parser.getText"); content.append(StringUtils.escapeForXML(text)); break; } } }
private static void parserNodeToString(StringBuilder content, XmlPullParser parser, Map<String, String> namespaceNodes) throws XmlPullParserException, IOException { // This is made more complicated due to many XmlPullParser implementations // support neither FEATURE_XML_ROUNDTRIP nor FEATURE_REPORT_NAMESPACE_ATTRIBUTES. if (parser.getEventType() != XmlPullParser.START_TAG) throw new IllegalArgumentException("parseContent must start at a start tag"); { HashMap<String,String> neededNamespaces = new HashMap<String,String>(); content.append("<"); // Append the element prefix, if any. String elemPrefix = parser.getPrefix(); if(elemPrefix != null) content.append(elemPrefix + ":"); neededNamespaces.put(elemPrefix == null? "":elemPrefix, parser.getNamespace()); content.append(parser.getName()); for(int i = 0; i < parser.getAttributeCount(); ++i) { content.append(" "); // Append the attribute prefix, if any. String attrPrefix = parser.getAttributePrefix(i); if(attrPrefix != null) neededNamespaces.put(attrPrefix, parser.getAttributeNamespace(i)); if(attrPrefix != null) content.append(attrPrefix + ":"); String attrName = parser.getAttributeName(i); content.append(attrName + "='"); String attrValue = parser.getAttributeValue(i); content.append(StringUtils.escapeForXML(attrValue)); content.append("'"); } // Check the prefixes used by this element and its attributes for ones that // aren't already declared, and output new xmlns attributes as needed. boolean clonedNamespaceMap = false; for(Map.Entry<String,String> entry: neededNamespaces.entrySet()) { String prefix = entry.getKey(); String namespace = entry.getValue(); String existingNamespace = namespaceNodes.get(prefix); if(existingNamespace != null && existingNamespace.equals(namespace)) continue; // This is a new or changed namespace prefix. Make a copy of the namespace // map, if we havn't already, and output a namespace declaration. if(!clonedNamespaceMap) { clonedNamespaceMap = true; HashMap<String, String> clonedNodes = new HashMap<String, String>(); clonedNodes.putAll(namespaceNodes); namespaceNodes = clonedNodes; } namespaceNodes.put(prefix, namespace); content.append(" xmlns"); if(prefix.length() == 0) content.append(":" + prefix); content.append("='"); content.append(StringUtils.escapeForXML(namespace)); content.append("'"); } content.append(">"); } while (true) { parser.next(); switch(parser.getEventType()) { case XmlPullParser.START_TAG: parserNodeToString(content, parser, namespaceNodes); break; case XmlPullParser.END_TAG: content.append("</"); if(parser.getPrefix() != null) content.append(parser.getPrefix() + ":"); content.append(parser.getName() + ">"); return; case XmlPullParser.END_DOCUMENT: return; default: String text = parser.getText(); if(text == null) throw new RuntimeException("Unexpected null result from parser.getText"); content.append(StringUtils.escapeForXML(text)); break; } } }
diff --git a/src/main/java/net/citizensnpcs/api/npc/SimpleNPCDataStore.java b/src/main/java/net/citizensnpcs/api/npc/SimpleNPCDataStore.java index 87d5086..97c8315 100644 --- a/src/main/java/net/citizensnpcs/api/npc/SimpleNPCDataStore.java +++ b/src/main/java/net/citizensnpcs/api/npc/SimpleNPCDataStore.java @@ -1,113 +1,113 @@ package net.citizensnpcs.api.npc; import net.citizensnpcs.api.util.DataKey; import net.citizensnpcs.api.util.Messaging; import net.citizensnpcs.api.util.Storage; import org.bukkit.entity.EntityType; public class SimpleNPCDataStore implements NPCDataStore { private final Storage root; private SimpleNPCDataStore(Storage saves) { root = saves; } @Override public void clearData(NPC npc) { root.getKey("npc").removeKey(Integer.toString(npc.getId())); } @Override public int createUniqueNPCId(NPCRegistry registry) { DataKey key = root.getKey(""); - int newId; - if (!key.keyExists("last-created-npc-id")) { + int newId = key.getInt("last-created-npc-id", -1); + if (newId == -1 || registry.getById(newId + 1) != null) { int maxId = Integer.MIN_VALUE; for (NPC npc : registry) { if (npc.getId() > maxId) { maxId = npc.getId(); } } newId = maxId == Integer.MIN_VALUE ? 0 : maxId + 1; } else { - newId = key.getInt("last-created-npc-id") + 1; + newId++; } key.setInt("last-created-npc-id", newId); return newId; } @Override public void loadInto(NPCRegistry registry) { for (DataKey key : root.getKey("npc").getIntegerSubKeys()) { int id = Integer.parseInt(key.name()); if (!key.keyExists("name")) { Messaging.logTr(LOAD_NAME_NOT_FOUND, id); continue; } String unparsedEntityType = key.getString("traits.type", "PLAYER"); EntityType type = matchEntityType(unparsedEntityType); if (type == null) { Messaging.logTr(LOAD_UNKNOWN_NPC_TYPE, unparsedEntityType); continue; } NPC npc = registry.createNPC(type, id, key.getString("name")); npc.load(key); } } @Override public void saveToDisk() { new Thread() { @Override public void run() { root.save(); } }.start(); } @Override public void saveToDiskImmediate() { root.save(); } @Override public void store(NPC npc) { npc.save(root.getKey("npc." + npc.getId())); } @Override public void storeAll(NPCRegistry registry) { for (NPC npc : registry) store(npc); } public static NPCDataStore create(Storage storage) { return new SimpleNPCDataStore(storage); } private static EntityType matchEntityType(String toMatch) { EntityType type = EntityType.fromName(toMatch); if (type != null) return type; return matchEnum(EntityType.values(), toMatch); } private static <T extends Enum<?>> T matchEnum(T[] values, String toMatch) { T type = null; for (T check : values) { String name = check.name(); if (name.matches(toMatch) || name.equalsIgnoreCase(toMatch) || name.replace("_", "").equalsIgnoreCase(toMatch) || name.replace('_', '-').equalsIgnoreCase(toMatch) || name.replace('_', ' ').equalsIgnoreCase(toMatch) || name.startsWith(toMatch)) { type = check; break; } } return type; } private static final String LOAD_NAME_NOT_FOUND = "citizens.notifications.npc-name-not-found"; private static final String LOAD_UNKNOWN_NPC_TYPE = "citizens.notifications.unknown-npc-type"; }
false
true
public int createUniqueNPCId(NPCRegistry registry) { DataKey key = root.getKey(""); int newId; if (!key.keyExists("last-created-npc-id")) { int maxId = Integer.MIN_VALUE; for (NPC npc : registry) { if (npc.getId() > maxId) { maxId = npc.getId(); } } newId = maxId == Integer.MIN_VALUE ? 0 : maxId + 1; } else { newId = key.getInt("last-created-npc-id") + 1; } key.setInt("last-created-npc-id", newId); return newId; }
public int createUniqueNPCId(NPCRegistry registry) { DataKey key = root.getKey(""); int newId = key.getInt("last-created-npc-id", -1); if (newId == -1 || registry.getById(newId + 1) != null) { int maxId = Integer.MIN_VALUE; for (NPC npc : registry) { if (npc.getId() > maxId) { maxId = npc.getId(); } } newId = maxId == Integer.MIN_VALUE ? 0 : maxId + 1; } else { newId++; } key.setInt("last-created-npc-id", newId); return newId; }
diff --git a/src/main/java/org/monitoring/queryapisql/preaggregation/PostgreSQLDatabase.java b/src/main/java/org/monitoring/queryapisql/preaggregation/PostgreSQLDatabase.java index 26d47c0..ec15105 100644 --- a/src/main/java/org/monitoring/queryapisql/preaggregation/PostgreSQLDatabase.java +++ b/src/main/java/org/monitoring/queryapisql/preaggregation/PostgreSQLDatabase.java @@ -1,145 +1,146 @@ package org.monitoring.queryapisql.preaggregation; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import java.util.LinkedList; import java.util.List; import org.monitoring.queryapi.Event; /** * * @author Michal */ public class PostgreSQLDatabase { Connection conn = null; List<Event> events = new LinkedList<Event>(); PostgreSQLDatabaseMapper mapper = new PostgreSQLDatabaseMapper(); public PostgreSQLDatabase() { try { Class.forName("org.postgresql.Driver"); conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/preaggregate", "postgres", "root"); mapper = new PostgreSQLDatabaseMapper(); } catch (SQLException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } } public List<Event> getAllEvents() { try { String query = "SELECT * " + "FROM MeterEvent event " + "ORDER BY event.time"; PreparedStatement st = conn.prepareStatement(query); ResultSet result = st.executeQuery(); return mapper.getResult(result); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public void save(Event event) { try { String query = "INSERT INTO event (source,date,value) VALUES (?,?,?)"; PreparedStatement st = conn.prepareStatement(query); mapper.set(st, event); int result = st.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } } public List<Event> getAggregate() { try { String query = "SELECT esource , sum(evalue) as sum " + "FROM MeterEvent event" + "GROUP BY event.edate"; PreparedStatement st = conn.prepareStatement(query); ResultSet result = st.executeQuery(); while (result.next()) { //TODO result.getDate("date"); result.getDouble("sum"); } } catch (SQLException ex) { ex.printStackTrace(); } return null; } public List<Event> updateAggregate(int timeActual, int timeNext, Date date, String field, Event event) { try { String query = "WITH upsert AS" - + "(UPDATE aggregate" + timeActual + " SET sum" + field + " = sum" + field + " + ?, count" + field + " = count" + field + " + 1, avg" + field + " = sum"+field+" / (1+count"+field+") " + + "(UPDATE aggregate" + timeActual + " SET sum" + field + " = sum" + field + " + ?, count" + field + " = count" + field + " + 1, avg" + field + " = (sum"+field+" + ?) / (1+count"+field+") " + "WHERE date = ? returning id) " + "INSERT INTO aggregate" + timeActual + " (sum" + field + ", avg" + field + ",count" + field + ", date, source) " + "SELECT ?,?,?,?,? WHERE NOT EXISTS (SELECT 1 FROM upsert) ; "; PreparedStatement st = conn.prepareStatement(query); st.setDouble(1, event.getValue()); - st.setTimestamp(2, new java.sql.Timestamp(date.getTime())); - st.setDouble(3, event.getValue()); + st.setDouble(2, event.getValue()); + st.setTimestamp(3, new java.sql.Timestamp(date.getTime())); st.setDouble(4, event.getValue()); - st.setDouble(5, 1D); - st.setTimestamp(6, new java.sql.Timestamp(date.getTime())); - st.setString(7, event.getSource()); + st.setDouble(5, event.getValue()); + st.setDouble(6, 1D); + st.setTimestamp(7, new java.sql.Timestamp(date.getTime())); + st.setString(8, event.getSource()); String q = st.toString(); int result = st.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public void execute(String query) { try { PreparedStatement st = conn.prepareStatement(query); int result = st.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } } public void dropTable() { try { String query = "DROP TABLE aggregate60;"; PreparedStatement st = conn.prepareStatement(query); int result = st.executeUpdate(); query = "DROP TABLE event"; st = conn.prepareStatement(query); result = st.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } } public void createTable(String table, int timeActual, int timeNext, String[] fields) { StringBuilder builder = new StringBuilder(); builder.append("CREATE TABLE "); builder.append(table); builder.append("("); builder.append("id SERIAL, "); builder.append("date TIMESTAMP, "); builder.append("source VARCHAR(100), "); for (Integer j = 0; j < timeNext / timeActual; j++) { for (String field : fields) { builder.append(field).append(j).append(" DOUBLE precision DEFAULT 0,"); } } builder.append(" CONSTRAINT pk_agg60_id PRIMARY KEY (id) "); builder.append(")"); execute(builder.toString()); execute("CREATE TABLE event(id serial NOT NULL, source character(100),date timestamp without time zone," + "value integer, CONSTRAINT pk_id PRIMARY KEY (id))"); execute("CREATE INDEX date_agg ON aggregate60 (date);"); execute("CREATE INDEX date_event ON event (date);"); } }
false
true
public List<Event> updateAggregate(int timeActual, int timeNext, Date date, String field, Event event) { try { String query = "WITH upsert AS" + "(UPDATE aggregate" + timeActual + " SET sum" + field + " = sum" + field + " + ?, count" + field + " = count" + field + " + 1, avg" + field + " = sum"+field+" / (1+count"+field+") " + "WHERE date = ? returning id) " + "INSERT INTO aggregate" + timeActual + " (sum" + field + ", avg" + field + ",count" + field + ", date, source) " + "SELECT ?,?,?,?,? WHERE NOT EXISTS (SELECT 1 FROM upsert) ; "; PreparedStatement st = conn.prepareStatement(query); st.setDouble(1, event.getValue()); st.setTimestamp(2, new java.sql.Timestamp(date.getTime())); st.setDouble(3, event.getValue()); st.setDouble(4, event.getValue()); st.setDouble(5, 1D); st.setTimestamp(6, new java.sql.Timestamp(date.getTime())); st.setString(7, event.getSource()); String q = st.toString(); int result = st.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } return null; }
public List<Event> updateAggregate(int timeActual, int timeNext, Date date, String field, Event event) { try { String query = "WITH upsert AS" + "(UPDATE aggregate" + timeActual + " SET sum" + field + " = sum" + field + " + ?, count" + field + " = count" + field + " + 1, avg" + field + " = (sum"+field+" + ?) / (1+count"+field+") " + "WHERE date = ? returning id) " + "INSERT INTO aggregate" + timeActual + " (sum" + field + ", avg" + field + ",count" + field + ", date, source) " + "SELECT ?,?,?,?,? WHERE NOT EXISTS (SELECT 1 FROM upsert) ; "; PreparedStatement st = conn.prepareStatement(query); st.setDouble(1, event.getValue()); st.setDouble(2, event.getValue()); st.setTimestamp(3, new java.sql.Timestamp(date.getTime())); st.setDouble(4, event.getValue()); st.setDouble(5, event.getValue()); st.setDouble(6, 1D); st.setTimestamp(7, new java.sql.Timestamp(date.getTime())); st.setString(8, event.getSource()); String q = st.toString(); int result = st.executeUpdate(); } catch (SQLException ex) { ex.printStackTrace(); } return null; }
diff --git a/apps/routerconsole/java/src/net/i2p/router/web/SearchHelper.java b/apps/routerconsole/java/src/net/i2p/router/web/SearchHelper.java index 29afd1592..a556e6cf0 100644 --- a/apps/routerconsole/java/src/net/i2p/router/web/SearchHelper.java +++ b/apps/routerconsole/java/src/net/i2p/router/web/SearchHelper.java @@ -1,105 +1,105 @@ package net.i2p.router.web; import java.util.Map; import java.util.TreeMap; import net.i2p.data.DataHelper; import net.i2p.util.PortMapper; /** * Helper for searches. * * @since 0.9 */ public class SearchHelper extends HelperBase { private String _engine; private String _query; private Map<String, String> _engines = new TreeMap(); private static final char S = ','; // in case engines need to know where it came from private static final String SOURCE = "&amp;ref=console"; static final String PROP_ENGINES = "routerconsole.searchEngines"; private static final String PROP_DEFAULT = "routerconsole.searchEngine"; static final String ENGINES_DEFAULT = "eepsites.i2p" + S + "http://eepsites.i2p/Content/Search/SearchResults.aspx?inpQuery=%s" + SOURCE + S + "epsilon.i2p" + S + "http://epsilon.i2p/search.jsp?q=%s" + SOURCE + S + //"searchthis.i2p" + S + "http://searchthis.i2p/cgi-bin/search.cgi?q=%s" + SOURCE + S + //"simple-search.i2p" + S + "http://simple-search.i2p/search.sh?search=%s" + SOURCE + S + //"sprongle.i2p" + S + "http://sprongle.i2p/sprongle.php?q=%s" + SOURCE + S + ""; public void setEngine(String s) { _engine = s; if (s != null) { String dflt = _context.getProperty(PROP_DEFAULT); if (!s.equals(dflt)) _context.router().saveConfig(PROP_DEFAULT, s); } } public void setQuery(String s) { _query = s; } private void buildEngineMap() { String config = _context.getProperty(PROP_ENGINES, ENGINES_DEFAULT); String[] args = config.split("" + S); for (int i = 0; i < args.length - 1; i += 2) { String name = args[i]; String url = args[i+1]; _engines.put(name, url); } } public String getSelector() { buildEngineMap(); if (_engines.isEmpty()) return "<b>No search engines specified</b>"; String dflt = _context.getProperty(PROP_DEFAULT); if (dflt == null || !_engines.containsKey(dflt)) { // pick a randome one as default and save it int idx = _context.random().nextInt(_engines.size()); int i = 0; for (String name : _engines.keySet()) { dflt = name; if (i++ >= idx) { _context.router().saveConfig(PROP_DEFAULT, dflt); break; } } } StringBuilder buf = new StringBuilder(1024); buf.append("<select name=\"engine\">"); for (String name : _engines.keySet()) { buf.append("<option value=\"").append(name).append('\"'); if (name.equals(dflt)) - buf.append(" selected=\"true\""); + buf.append(" selected=\"selected\""); buf.append('>').append(name).append("</option>\n"); } buf.append("</select>\n"); return buf.toString(); } /** * @return null on error */ public String getURL() { if (_engine == null || _query == null) return null; _query = DataHelper.escapeHTML(_query).trim(); if (_query.length() <= 0) return null; buildEngineMap(); String url = _engines.get(_engine); if (url == null) return null; if (url.contains("%s")) url = url.replace("%s", _query); else url += _query; return url; } }
true
true
public String getSelector() { buildEngineMap(); if (_engines.isEmpty()) return "<b>No search engines specified</b>"; String dflt = _context.getProperty(PROP_DEFAULT); if (dflt == null || !_engines.containsKey(dflt)) { // pick a randome one as default and save it int idx = _context.random().nextInt(_engines.size()); int i = 0; for (String name : _engines.keySet()) { dflt = name; if (i++ >= idx) { _context.router().saveConfig(PROP_DEFAULT, dflt); break; } } } StringBuilder buf = new StringBuilder(1024); buf.append("<select name=\"engine\">"); for (String name : _engines.keySet()) { buf.append("<option value=\"").append(name).append('\"'); if (name.equals(dflt)) buf.append(" selected=\"true\""); buf.append('>').append(name).append("</option>\n"); } buf.append("</select>\n"); return buf.toString(); }
public String getSelector() { buildEngineMap(); if (_engines.isEmpty()) return "<b>No search engines specified</b>"; String dflt = _context.getProperty(PROP_DEFAULT); if (dflt == null || !_engines.containsKey(dflt)) { // pick a randome one as default and save it int idx = _context.random().nextInt(_engines.size()); int i = 0; for (String name : _engines.keySet()) { dflt = name; if (i++ >= idx) { _context.router().saveConfig(PROP_DEFAULT, dflt); break; } } } StringBuilder buf = new StringBuilder(1024); buf.append("<select name=\"engine\">"); for (String name : _engines.keySet()) { buf.append("<option value=\"").append(name).append('\"'); if (name.equals(dflt)) buf.append(" selected=\"selected\""); buf.append('>').append(name).append("</option>\n"); } buf.append("</select>\n"); return buf.toString(); }
diff --git a/src/org/opensolaris/opengrok/search/context/Context.java b/src/org/opensolaris/opengrok/search/context/Context.java index 3507afdc..446c20d4 100644 --- a/src/org/opensolaris/opengrok/search/context/Context.java +++ b/src/org/opensolaris/opengrok/search/context/Context.java @@ -1,278 +1,276 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * See LICENSE.txt included in this distribution for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. */ /** * This is supposed to get the matching lines from sourcefile. * since lucene does not easily give the match context. */ package org.opensolaris.opengrok.search.context; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.logging.Level; import org.apache.lucene.search.Query; import org.opensolaris.opengrok.OpenGrokLogger; import org.opensolaris.opengrok.analysis.Definitions; import org.opensolaris.opengrok.configuration.RuntimeEnvironment; import org.opensolaris.opengrok.search.Hit; import org.opensolaris.opengrok.web.Util; public class Context { private final LineMatcher[] m; static final int MAXFILEREAD = 1024 * 1024; private char[] buffer; PlainLineTokenizer tokens; String queryAsURI; /** * Map whose keys tell which fields to look for in the source file, and * whose values tell if the field is case insensitive (true for * insensitivity, false for sensitivity). */ private static final Map<String, Boolean> tokenFields = new HashMap<String, Boolean>(); static { tokenFields.put("full", true); tokenFields.put("refs", false); tokenFields.put("defs", false); } /** * Constructs a context generator * @param query the query to generate the result for * @param queryStrings map from field names to queries against the fields */ public Context(Query query, Map<String, String> queryStrings) { QueryMatchers qm = new QueryMatchers(); m = qm.getMatchers(query, tokenFields); if (m != null) { buildQueryAsURI(queryStrings); //System.err.println("Found Matchers = "+ m.length + " for " + query); buffer = new char[MAXFILEREAD]; tokens = new PlainLineTokenizer((Reader) null); } } public boolean isEmpty() { return m == null; } /** * Build the {@code queryAsURI} string that holds the query in a form * that's suitable for sending it as part of a URI. * * @param subqueries a map containing the query text for each field */ private void buildQueryAsURI(Map<String, String> subqueries) { boolean first = true; StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : subqueries.entrySet()) { String field = entry.getKey(); String queryText = entry.getValue(); if (!first) { sb.append('&'); } sb.append(field).append("=").append(Util.URIEncode(queryText)); first = false; } queryAsURI = sb.toString(); } private boolean alt = true; /** * * @param in File to be matched * @param out to write the context * @param morePrefix to link to more... page * @param path path of the file * @param tags format to highlight defs. * @param limit should the number of matching lines be limited? * @return Did it get any matching context? */ public boolean getContext(Reader in, Writer out, String urlPrefix, String morePrefix, String path, Definitions tags, boolean limit, List<Hit> hits) { alt = !alt; if (m == null) { return false; } boolean anything = false; TreeMap<Integer, String[]> matchingTags = null; if (tags != null) { matchingTags = new TreeMap<Integer, String[]>(); try { for (Definitions.Tag tag : tags.getTags()) { for (int i = 0; i < m.length; i++) { - //TODO symbol.toLowerCase makes below check work for all searches and shows the proper tag, hence QueryMatchers or someone from the matchers incorrectly lowercases search for index which IS case sensitive !!! - // please fix bug 17582 if (m[i].match(tag.symbol) == LineMatcher.MATCHED) { /* * desc[1] is line number * desc[2] is type * desc[3] is matching line; */ String[] desc = { tag.symbol, Integer.toString(tag.line), tag.type, tag.text,}; if (in == null) { if (out == null) { Hit hit = new Hit(path, Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>"), desc[1], false, alt); hits.add(hit); anything = true; } else { out.write("<a class=\"s\" href=\""); out.write(Util.URIEncodePath(urlPrefix)); out.write(Util.URIEncodePath(path)); out.write("#"); out.write(desc[1]); out.write("\"><span class=\"l\">"); out.write(desc[1]); out.write("</span> "); out.write(Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>")); out.write("</a> <i> "); out.write(desc[2]); out.write(" </i><br/>"); anything = true; } } else { matchingTags.put(tag.line, desc); } break; } } } } catch (IOException e) { if (hits != null) { // @todo verify why we ignore all exceptions? OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } } } /** * Just to get the matching tag send a null in */ if (in == null) { return anything; } int charsRead = 0; boolean truncated = false; boolean lim = limit; if (!RuntimeEnvironment.getInstance().isQuickContextScan()) { lim = false; } if (lim) { try { charsRead = in.read(buffer); if (charsRead == MAXFILEREAD) { // we probably only read parts of the file, so set the // truncated flag to enable the [all...] link that // requests all matches truncated = true; // truncate to last line read (don't look more than 100 // characters back) for (int i = charsRead - 1; i > charsRead - 100; i--) { if (buffer[i] == '\n') { charsRead = i; break; } } } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while reading data", e); return anything; } if (charsRead == 0) { return anything; } tokens.reInit(buffer, charsRead, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } else { tokens.reInit(in, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } if (hits != null) { tokens.setAlt(alt); tokens.setHitList(hits); tokens.setFilename(path); } try { String token; int matchState = LineMatcher.NOT_MATCHED; int matchedLines = 0; while ((token = tokens.yylex()) != null && (!lim || matchedLines < 10)) { for (int i = 0; i < m.length; i++) { matchState = m[i].match(token); if (matchState == LineMatcher.MATCHED) { tokens.printContext(); matchedLines++; //out.write("<br> <i>Matched " + token + " maxlines = " + matchedLines + "</i><br>"); break; } else if (matchState == LineMatcher.WAIT) { tokens.holdOn(); } else { tokens.neverMind(); } } } anything = matchedLines > 0; tokens.dumpRest(); if (lim && (truncated || matchedLines == 10) && out != null) { out.write("&nbsp; &nbsp; [<a href=\"" + Util.URIEncodePath(morePrefix + path) + "?" + queryAsURI + "\">all</a>...]"); } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream", e); } } if (out != null) { try { out.flush(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while flushing stream", e); } } } return anything; } }
true
true
public boolean getContext(Reader in, Writer out, String urlPrefix, String morePrefix, String path, Definitions tags, boolean limit, List<Hit> hits) { alt = !alt; if (m == null) { return false; } boolean anything = false; TreeMap<Integer, String[]> matchingTags = null; if (tags != null) { matchingTags = new TreeMap<Integer, String[]>(); try { for (Definitions.Tag tag : tags.getTags()) { for (int i = 0; i < m.length; i++) { //TODO symbol.toLowerCase makes below check work for all searches and shows the proper tag, hence QueryMatchers or someone from the matchers incorrectly lowercases search for index which IS case sensitive !!! // please fix bug 17582 if (m[i].match(tag.symbol) == LineMatcher.MATCHED) { /* * desc[1] is line number * desc[2] is type * desc[3] is matching line; */ String[] desc = { tag.symbol, Integer.toString(tag.line), tag.type, tag.text,}; if (in == null) { if (out == null) { Hit hit = new Hit(path, Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>"), desc[1], false, alt); hits.add(hit); anything = true; } else { out.write("<a class=\"s\" href=\""); out.write(Util.URIEncodePath(urlPrefix)); out.write(Util.URIEncodePath(path)); out.write("#"); out.write(desc[1]); out.write("\"><span class=\"l\">"); out.write(desc[1]); out.write("</span> "); out.write(Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>")); out.write("</a> <i> "); out.write(desc[2]); out.write(" </i><br/>"); anything = true; } } else { matchingTags.put(tag.line, desc); } break; } } } } catch (IOException e) { if (hits != null) { // @todo verify why we ignore all exceptions? OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } } } /** * Just to get the matching tag send a null in */ if (in == null) { return anything; } int charsRead = 0; boolean truncated = false; boolean lim = limit; if (!RuntimeEnvironment.getInstance().isQuickContextScan()) { lim = false; } if (lim) { try { charsRead = in.read(buffer); if (charsRead == MAXFILEREAD) { // we probably only read parts of the file, so set the // truncated flag to enable the [all...] link that // requests all matches truncated = true; // truncate to last line read (don't look more than 100 // characters back) for (int i = charsRead - 1; i > charsRead - 100; i--) { if (buffer[i] == '\n') { charsRead = i; break; } } } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while reading data", e); return anything; } if (charsRead == 0) { return anything; } tokens.reInit(buffer, charsRead, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } else { tokens.reInit(in, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } if (hits != null) { tokens.setAlt(alt); tokens.setHitList(hits); tokens.setFilename(path); } try { String token; int matchState = LineMatcher.NOT_MATCHED; int matchedLines = 0; while ((token = tokens.yylex()) != null && (!lim || matchedLines < 10)) { for (int i = 0; i < m.length; i++) { matchState = m[i].match(token); if (matchState == LineMatcher.MATCHED) { tokens.printContext(); matchedLines++; //out.write("<br> <i>Matched " + token + " maxlines = " + matchedLines + "</i><br>"); break; } else if (matchState == LineMatcher.WAIT) { tokens.holdOn(); } else { tokens.neverMind(); } } } anything = matchedLines > 0; tokens.dumpRest(); if (lim && (truncated || matchedLines == 10) && out != null) { out.write("&nbsp; &nbsp; [<a href=\"" + Util.URIEncodePath(morePrefix + path) + "?" + queryAsURI + "\">all</a>...]"); } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream", e); } } if (out != null) { try { out.flush(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while flushing stream", e); } } } return anything; }
public boolean getContext(Reader in, Writer out, String urlPrefix, String morePrefix, String path, Definitions tags, boolean limit, List<Hit> hits) { alt = !alt; if (m == null) { return false; } boolean anything = false; TreeMap<Integer, String[]> matchingTags = null; if (tags != null) { matchingTags = new TreeMap<Integer, String[]>(); try { for (Definitions.Tag tag : tags.getTags()) { for (int i = 0; i < m.length; i++) { if (m[i].match(tag.symbol) == LineMatcher.MATCHED) { /* * desc[1] is line number * desc[2] is type * desc[3] is matching line; */ String[] desc = { tag.symbol, Integer.toString(tag.line), tag.type, tag.text,}; if (in == null) { if (out == null) { Hit hit = new Hit(path, Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>"), desc[1], false, alt); hits.add(hit); anything = true; } else { out.write("<a class=\"s\" href=\""); out.write(Util.URIEncodePath(urlPrefix)); out.write(Util.URIEncodePath(path)); out.write("#"); out.write(desc[1]); out.write("\"><span class=\"l\">"); out.write(desc[1]); out.write("</span> "); out.write(Util.htmlize(desc[3]).replaceAll( desc[0], "<b>" + desc[0] + "</b>")); out.write("</a> <i> "); out.write(desc[2]); out.write(" </i><br/>"); anything = true; } } else { matchingTags.put(tag.line, desc); } break; } } } } catch (IOException e) { if (hits != null) { // @todo verify why we ignore all exceptions? OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } } } /** * Just to get the matching tag send a null in */ if (in == null) { return anything; } int charsRead = 0; boolean truncated = false; boolean lim = limit; if (!RuntimeEnvironment.getInstance().isQuickContextScan()) { lim = false; } if (lim) { try { charsRead = in.read(buffer); if (charsRead == MAXFILEREAD) { // we probably only read parts of the file, so set the // truncated flag to enable the [all...] link that // requests all matches truncated = true; // truncate to last line read (don't look more than 100 // characters back) for (int i = charsRead - 1; i > charsRead - 100; i--) { if (buffer[i] == '\n') { charsRead = i; break; } } } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while reading data", e); return anything; } if (charsRead == 0) { return anything; } tokens.reInit(buffer, charsRead, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } else { tokens.reInit(in, out, Util.URIEncodePath(urlPrefix + path) + "#", matchingTags); } if (hits != null) { tokens.setAlt(alt); tokens.setHitList(hits); tokens.setFilename(path); } try { String token; int matchState = LineMatcher.NOT_MATCHED; int matchedLines = 0; while ((token = tokens.yylex()) != null && (!lim || matchedLines < 10)) { for (int i = 0; i < m.length; i++) { matchState = m[i].match(token); if (matchState == LineMatcher.MATCHED) { tokens.printContext(); matchedLines++; //out.write("<br> <i>Matched " + token + " maxlines = " + matchedLines + "</i><br>"); break; } else if (matchState == LineMatcher.WAIT) { tokens.holdOn(); } else { tokens.neverMind(); } } } anything = matchedLines > 0; tokens.dumpRest(); if (lim && (truncated || matchedLines == 10) && out != null) { out.write("&nbsp; &nbsp; [<a href=\"" + Util.URIEncodePath(morePrefix + path) + "?" + queryAsURI + "\">all</a>...]"); } } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "Could not get context for " + path, e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while closing stream", e); } } if (out != null) { try { out.flush(); } catch (IOException e) { OpenGrokLogger.getLogger().log(Level.WARNING, "An error occured while flushing stream", e); } } } return anything; }
diff --git a/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java b/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java index 03ac47df1..5372aa0a9 100644 --- a/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java +++ b/src/main/java/org/apache/hadoop/hbase/client/MetaScanner.java @@ -1,244 +1,241 @@ /** * Copyright 2009 The Apache Software Foundation * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.client; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.HRegionInfo; import org.apache.hadoop.hbase.TableNotFoundException; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Writables; /** * Scanner class that contains the <code>.META.</code> table scanning logic * and uses a Retryable scanner. Provided visitors will be called * for each row. * * Although public visibility, this is not a public-facing API and may evolve in * minor releases. */ public class MetaScanner { private static final Log LOG = LogFactory.getLog(MetaScanner.class); /** * Scans the meta table and calls a visitor on each RowResult and uses a empty * start row value as table name. * * @param configuration conf * @param visitor A custom visitor * @throws IOException e */ public static void metaScan(Configuration configuration, MetaScannerVisitor visitor) throws IOException { metaScan(configuration, visitor, null); } /** * Scans the meta table and calls a visitor on each RowResult. Uses a table * name to locate meta regions. * * @param configuration config * @param visitor visitor object * @param tableName table name * @throws IOException e */ public static void metaScan(Configuration configuration, MetaScannerVisitor visitor, byte[] tableName) throws IOException { metaScan(configuration, visitor, tableName, null, Integer.MAX_VALUE); } /** * Scans the meta table and calls a visitor on each RowResult. Uses a table * name and a row name to locate meta regions. And it only scans at most * <code>rowLimit</code> of rows. * * @param configuration HBase configuration. * @param visitor Visitor object. * @param tableName User table name. * @param row Name of the row at the user table. The scan will start from * the region row where the row resides. * @param rowLimit Max of processed rows. If it is less than 0, it * will be set to default value <code>Integer.MAX_VALUE</code>. * @throws IOException e */ public static void metaScan(Configuration configuration, MetaScannerVisitor visitor, byte[] tableName, byte[] row, int rowLimit) throws IOException { int rowUpperLimit = rowLimit > 0 ? rowLimit: Integer.MAX_VALUE; HConnection connection = HConnectionManager.getConnection(configuration); // if row is not null, we want to use the startKey of the row's region as // the startRow for the meta scan. byte[] startRow; - // row could be non-null but empty -- the HConstants.EMPTY_START_ROW - if (row != null && row.length > 0) { + if (row != null) { // Scan starting at a particular row in a particular table assert tableName != null; byte[] searchRow = HRegionInfo.createRegionName(tableName, row, HConstants.NINES, false); HTable metaTable = new HTable(configuration, HConstants.META_TABLE_NAME); Result startRowResult = metaTable.getRowOrBefore(searchRow, HConstants.CATALOG_FAMILY); if (startRowResult == null) { throw new TableNotFoundException("Cannot find row in .META. for table: " + Bytes.toString(tableName) + ", row=" + Bytes.toString(searchRow)); } byte[] value = startRowResult.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER); if (value == null || value.length == 0) { throw new IOException("HRegionInfo was null or empty in Meta for " + Bytes.toString(tableName) + ", row=" + Bytes.toString(searchRow)); } HRegionInfo regionInfo = Writables.getHRegionInfo(value); byte[] rowBefore = regionInfo.getStartKey(); startRow = HRegionInfo.createRegionName(tableName, rowBefore, HConstants.ZEROES, false); - } else if (row == null || - (row != null && Bytes.equals(HConstants.EMPTY_START_ROW, row)) || - (tableName == null || tableName.length == 0)) { + } else if (tableName == null || tableName.length == 0) { // Full META scan startRow = HConstants.EMPTY_START_ROW; } else { // Scan META for an entire table startRow = HRegionInfo.createRegionName( tableName, HConstants.EMPTY_START_ROW, HConstants.ZEROES, false); } // Scan over each meta region ScannerCallable callable; int rows = Math.min(rowLimit, configuration.getInt("hbase.meta.scanner.caching", 100)); do { final Scan scan = new Scan(startRow).addFamily(HConstants.CATALOG_FAMILY); byte [] metaTableName = Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME)? HConstants.ROOT_TABLE_NAME: HConstants.META_TABLE_NAME; LOG.debug("Scanning " + Bytes.toString(metaTableName) + " starting at row=" + Bytes.toString(startRow) + " for max=" + rowUpperLimit + " rows"); callable = new ScannerCallable(connection, metaTableName, scan); // Open scanner connection.getRegionServerWithRetries(callable); int processedRows = 0; try { callable.setCaching(rows); done: do { if (processedRows >= rowUpperLimit) { break; } //we have all the rows here Result [] rrs = connection.getRegionServerWithRetries(callable); if (rrs == null || rrs.length == 0 || rrs[0].size() == 0) { break; //exit completely } for (Result rr : rrs) { if (processedRows >= rowUpperLimit) { break done; } if (!visitor.processRow(rr)) break done; //exit completely processedRows++; } //here, we didn't break anywhere. Check if we have more rows } while(true); // Advance the startRow to the end key of the current region startRow = callable.getHRegionInfo().getEndKey(); } finally { // Close scanner callable.setClose(); connection.getRegionServerWithRetries(callable); } } while (Bytes.compareTo(startRow, HConstants.LAST_ROW) != 0); } /** * Lists all of the regions currently in META. * @param conf * @return List of all user-space regions. * @throws IOException */ public static List<HRegionInfo> listAllRegions(Configuration conf) throws IOException { return listAllRegions(conf, true); } /** * Lists all of the regions currently in META. * @param conf * @param offlined True if we are to include offlined regions, false and we'll * leave out offlined regions from returned list. * @return List of all user-space regions. * @throws IOException */ public static List<HRegionInfo> listAllRegions(Configuration conf, final boolean offlined) throws IOException { final List<HRegionInfo> regions = new ArrayList<HRegionInfo>(); MetaScannerVisitor visitor = new MetaScannerVisitor() { @Override public boolean processRow(Result result) throws IOException { if (result == null || result.isEmpty()) { return true; } byte [] bytes = result.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER); if (bytes == null) { LOG.warn("Null REGIONINFO_QUALIFIER: " + result); return true; } HRegionInfo regionInfo = Writables.getHRegionInfo(bytes); // If region offline AND we are not to include offlined regions, return. if (regionInfo.isOffline() && !offlined) return true; regions.add(regionInfo); return true; } }; metaScan(conf, visitor); return regions; } /** * Visitor class called to process each row of the .META. table */ public interface MetaScannerVisitor { /** * Visitor method that accepts a RowResult and the meta region location. * Implementations can return false to stop the region's loop if it becomes * unnecessary for some reason. * * @param rowResult result * @return A boolean to know if it should continue to loop in the region * @throws IOException e */ public boolean processRow(Result rowResult) throws IOException; } }
false
true
public static void metaScan(Configuration configuration, MetaScannerVisitor visitor, byte[] tableName, byte[] row, int rowLimit) throws IOException { int rowUpperLimit = rowLimit > 0 ? rowLimit: Integer.MAX_VALUE; HConnection connection = HConnectionManager.getConnection(configuration); // if row is not null, we want to use the startKey of the row's region as // the startRow for the meta scan. byte[] startRow; // row could be non-null but empty -- the HConstants.EMPTY_START_ROW if (row != null && row.length > 0) { // Scan starting at a particular row in a particular table assert tableName != null; byte[] searchRow = HRegionInfo.createRegionName(tableName, row, HConstants.NINES, false); HTable metaTable = new HTable(configuration, HConstants.META_TABLE_NAME); Result startRowResult = metaTable.getRowOrBefore(searchRow, HConstants.CATALOG_FAMILY); if (startRowResult == null) { throw new TableNotFoundException("Cannot find row in .META. for table: " + Bytes.toString(tableName) + ", row=" + Bytes.toString(searchRow)); } byte[] value = startRowResult.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER); if (value == null || value.length == 0) { throw new IOException("HRegionInfo was null or empty in Meta for " + Bytes.toString(tableName) + ", row=" + Bytes.toString(searchRow)); } HRegionInfo regionInfo = Writables.getHRegionInfo(value); byte[] rowBefore = regionInfo.getStartKey(); startRow = HRegionInfo.createRegionName(tableName, rowBefore, HConstants.ZEROES, false); } else if (row == null || (row != null && Bytes.equals(HConstants.EMPTY_START_ROW, row)) || (tableName == null || tableName.length == 0)) { // Full META scan startRow = HConstants.EMPTY_START_ROW; } else { // Scan META for an entire table startRow = HRegionInfo.createRegionName( tableName, HConstants.EMPTY_START_ROW, HConstants.ZEROES, false); } // Scan over each meta region ScannerCallable callable; int rows = Math.min(rowLimit, configuration.getInt("hbase.meta.scanner.caching", 100)); do { final Scan scan = new Scan(startRow).addFamily(HConstants.CATALOG_FAMILY); byte [] metaTableName = Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME)? HConstants.ROOT_TABLE_NAME: HConstants.META_TABLE_NAME; LOG.debug("Scanning " + Bytes.toString(metaTableName) + " starting at row=" + Bytes.toString(startRow) + " for max=" + rowUpperLimit + " rows"); callable = new ScannerCallable(connection, metaTableName, scan); // Open scanner connection.getRegionServerWithRetries(callable); int processedRows = 0; try { callable.setCaching(rows); done: do { if (processedRows >= rowUpperLimit) { break; } //we have all the rows here Result [] rrs = connection.getRegionServerWithRetries(callable); if (rrs == null || rrs.length == 0 || rrs[0].size() == 0) { break; //exit completely } for (Result rr : rrs) { if (processedRows >= rowUpperLimit) { break done; } if (!visitor.processRow(rr)) break done; //exit completely processedRows++; } //here, we didn't break anywhere. Check if we have more rows } while(true); // Advance the startRow to the end key of the current region startRow = callable.getHRegionInfo().getEndKey(); } finally { // Close scanner callable.setClose(); connection.getRegionServerWithRetries(callable); } } while (Bytes.compareTo(startRow, HConstants.LAST_ROW) != 0); }
public static void metaScan(Configuration configuration, MetaScannerVisitor visitor, byte[] tableName, byte[] row, int rowLimit) throws IOException { int rowUpperLimit = rowLimit > 0 ? rowLimit: Integer.MAX_VALUE; HConnection connection = HConnectionManager.getConnection(configuration); // if row is not null, we want to use the startKey of the row's region as // the startRow for the meta scan. byte[] startRow; if (row != null) { // Scan starting at a particular row in a particular table assert tableName != null; byte[] searchRow = HRegionInfo.createRegionName(tableName, row, HConstants.NINES, false); HTable metaTable = new HTable(configuration, HConstants.META_TABLE_NAME); Result startRowResult = metaTable.getRowOrBefore(searchRow, HConstants.CATALOG_FAMILY); if (startRowResult == null) { throw new TableNotFoundException("Cannot find row in .META. for table: " + Bytes.toString(tableName) + ", row=" + Bytes.toString(searchRow)); } byte[] value = startRowResult.getValue(HConstants.CATALOG_FAMILY, HConstants.REGIONINFO_QUALIFIER); if (value == null || value.length == 0) { throw new IOException("HRegionInfo was null or empty in Meta for " + Bytes.toString(tableName) + ", row=" + Bytes.toString(searchRow)); } HRegionInfo regionInfo = Writables.getHRegionInfo(value); byte[] rowBefore = regionInfo.getStartKey(); startRow = HRegionInfo.createRegionName(tableName, rowBefore, HConstants.ZEROES, false); } else if (tableName == null || tableName.length == 0) { // Full META scan startRow = HConstants.EMPTY_START_ROW; } else { // Scan META for an entire table startRow = HRegionInfo.createRegionName( tableName, HConstants.EMPTY_START_ROW, HConstants.ZEROES, false); } // Scan over each meta region ScannerCallable callable; int rows = Math.min(rowLimit, configuration.getInt("hbase.meta.scanner.caching", 100)); do { final Scan scan = new Scan(startRow).addFamily(HConstants.CATALOG_FAMILY); byte [] metaTableName = Bytes.equals(tableName, HConstants.ROOT_TABLE_NAME)? HConstants.ROOT_TABLE_NAME: HConstants.META_TABLE_NAME; LOG.debug("Scanning " + Bytes.toString(metaTableName) + " starting at row=" + Bytes.toString(startRow) + " for max=" + rowUpperLimit + " rows"); callable = new ScannerCallable(connection, metaTableName, scan); // Open scanner connection.getRegionServerWithRetries(callable); int processedRows = 0; try { callable.setCaching(rows); done: do { if (processedRows >= rowUpperLimit) { break; } //we have all the rows here Result [] rrs = connection.getRegionServerWithRetries(callable); if (rrs == null || rrs.length == 0 || rrs[0].size() == 0) { break; //exit completely } for (Result rr : rrs) { if (processedRows >= rowUpperLimit) { break done; } if (!visitor.processRow(rr)) break done; //exit completely processedRows++; } //here, we didn't break anywhere. Check if we have more rows } while(true); // Advance the startRow to the end key of the current region startRow = callable.getHRegionInfo().getEndKey(); } finally { // Close scanner callable.setClose(); connection.getRegionServerWithRetries(callable); } } while (Bytes.compareTo(startRow, HConstants.LAST_ROW) != 0); }
diff --git a/src/main/java/com/powertac/tourney/actions/ActionTournament.java b/src/main/java/com/powertac/tourney/actions/ActionTournament.java index b9e1704..fc6abe9 100644 --- a/src/main/java/com/powertac/tourney/actions/ActionTournament.java +++ b/src/main/java/com/powertac/tourney/actions/ActionTournament.java @@ -1,520 +1,520 @@ package com.powertac.tourney.actions; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Properties; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; import org.apache.commons.codec.digest.DigestUtils; import org.apache.myfaces.custom.fileupload.UploadedFile; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import com.powertac.tourney.beans.Competition; import com.powertac.tourney.beans.Game; import com.powertac.tourney.beans.Games; import com.powertac.tourney.beans.Machine; import com.powertac.tourney.beans.Machines; import com.powertac.tourney.beans.Scheduler; import com.powertac.tourney.beans.Tournament; import com.powertac.tourney.beans.Tournaments; import com.powertac.tourney.services.CreateProperties; import com.powertac.tourney.services.Database; import com.powertac.tourney.services.RunBootstrap; import com.powertac.tourney.services.RunGame; import com.powertac.tourney.services.Upload; @Component("actionTournament") @Scope("session") public class ActionTournament { @Autowired private Upload upload; @Autowired private Scheduler scheduler; public enum TourneyType { SINGLE_GAME, MULTI_GAME; } private String selectedPom; private Calendar initTime = Calendar.getInstance(); private Date startTime = new Date(); // Default to current date/time private Date fromTime = new Date(); private Date toTime = new Date(); private String tournamentName; private int maxBrokers; // -1 means inf, otherwise integer specific //private List<Integer> machines; private List<String> locations; private String pomName; private String bootName; private String propertiesName; private UploadedFile pom; private UploadedFile boot; private UploadedFile properties; private TourneyType type = TourneyType.SINGLE_GAME; private int size1 = 2; private int numberSize1; private int size2 = 4; private int numberSize2; private int size3 = 8; private int numberSize3; public ActionTournament(){ initTime.set(2009, 2, 3); fromTime.setTime(initTime.getTimeInMillis()); initTime.set(2011, 2, 3); toTime.setTime(initTime.getTimeInMillis()); } public void formType(ActionEvent event){ //Get submit button id SelectItem ls = (SelectItem) event.getSource(); ls.getValue(); } public TourneyType getMulti(){ return TourneyType.MULTI_GAME; } public TourneyType getSingle(){ return TourneyType.SINGLE_GAME; } /** * @return the properties */ public UploadedFile getProperties() { return properties; } /** * @param properties * the properties to set */ public void setProperties(UploadedFile properties) { this.properties = properties; } /** * @return the boot */ public UploadedFile getBoot() { return boot; } /** * @param boot * the boot to set */ public void setBoot(UploadedFile boot) { this.boot = boot; } /** * @return the pom */ public UploadedFile getPom() { return pom; } /** * @param pom * the pom to set */ public void setPom(UploadedFile pom) { this.pom = pom; } /** * @return the propertiesName */ public String getPropertiesName() { return propertiesName; } /** * @param propertiesName * the propertiesName to set */ public void setPropertiesName(String propertiesName) { // Generate MD5 hash this.propertiesName = DigestUtils.md5Hex(propertiesName + (new Date()).toString() + Math.random()); } /** * @return the bootName */ public String getBootName() { return bootName; } /** * @param bootName * the bootName to set */ public void setBootName(String bootName) { // Generate MD5 hash this.bootName = DigestUtils.md5Hex(bootName + (new Date()).toString() + Math.random()); } public String getPomName() { return pomName; } public void setPomName(String pomName) { // Generate MD5 hash this.pomName = DigestUtils.md5Hex(pomName + (new Date()).toString() + Math.random()); } // Method to list the type enumeration in the jsf select Item component public SelectItem[] getTypes() { SelectItem[] items = new SelectItem[TourneyType.values().length]; int i = 0; for (TourneyType t : TourneyType.values()) { items[i++] = new SelectItem(t, t.name()); } return items; } public TourneyType getType() { return type; } public void setType(TourneyType type) { this.type = type; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public int getMaxBrokers() { return maxBrokers; } public void setMaxBrokers(int maxBrokers) { this.maxBrokers = maxBrokers; } public String getTournamentName() { return tournamentName; } public void setTournamentName(String tournamentName) { this.tournamentName = tournamentName; } public String createTournament() { // Create a tournament and insert it into the application context Tournament newTourney = new Tournament(); if (type == TourneyType.SINGLE_GAME) { /*this.setPomName(pom.getName()); upload.setUploadedFile(getPom()); String finalFile = upload.submit(this.getPomName());*/ newTourney.setPomName(selectedPom); String hostip = "http://"; try { InetAddress thisIp =InetAddress.getLocalHost(); hostip += thisIp.getHostAddress() + ":8080"; } catch (UnknownHostException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } Database db = new Database(); newTourney.setPomUrl(hostip+"/TournamentScheduler/faces/pom.jsp?location="+newTourney.getPomName()); newTourney.setMaxBrokers(getMaxBrokers()); newTourney.setStartTime(getStartTime()); newTourney.setTournamentName(getTournamentName()); // Add one game to the global context and to the tournament // Add game to all games and to Tournament //allGames.addGame(newGame); //newTourney.addGame(newGame); //Tournaments.getAllTournaments().addTournament(newTourney); // Start a single game and send jenkins request to kick the server // at the appropriate time String allLocations = ""; for (String s : locations){ allLocations += s + ","; } int tourneyId = 0; int gameId = 0; try { //Starts new transaction to prevent race conditions System.out.println("Starting transaction"); db.startTrans(); //Adds new tournament to the database System.out.println("Adding tourney"); db.addTournament(newTourney.getTournamentName(), true, 1, new java.sql.Date(newTourney.getStartTime().getTime()), "SINGLE_GAME", newTourney.getPomUrl(), allLocations, maxBrokers); //Grabs the tourney Id System.out.println("Getting tourneyId"); tourneyId = db.getMaxTourneyId(); // Adds a new game to the database System.out.println("Adding game"); db.addGame(newTourney.getTournamentName(), tourneyId, size1, new java.sql.Date(startTime.getTime())); // Grabs the game id System.out.println("Getting gameId"); gameId = db.getMaxGameId(); System.out.println("Creating game: "+ gameId +" properties"); CreateProperties.genProperties(gameId, locations, fromTime, toTime); // Sets the url for the properties file based on the game id. // Properties are created at random withing specified parameters System.out.println("Updating properties game: " + gameId); db.updateGamePropertiesById(gameId); System.out.println("Committing transaction"); db.commitTrans(); Properties props = new Properties(); try { props.load(Database.class.getClassLoader().getResourceAsStream( "/tournament.properties")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } db.closeConnection(); // Only schedule the bootstrap and sim if db was updated successfully - Scheduler.getScheduler().schedule(new RunBootstrap(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), new Date()); + scheduler.runBootTimer(gameId,new RunBootstrap(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), new Date()); // A sim will only run if the bootstrap exists - Scheduler.getScheduler().schedule(new RunGame(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), startTime); + scheduler.runBootTimer(gameId,new RunGame(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), startTime); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Scheduler.getScheduler().schedule( // new StartServer(newGame, Machines.getAllMachines(), // Tournaments.getAllTournaments()), //newGame.getStartTime()); try { // TODO:REMOVE this is only to simulate the message from the // server // Thread.sleep(6000); // URL test = new // URL("http://localhost:8080/TournamentScheduler/faces/serverInterface.jsp?action=status&status=ready&gameId="+newGame.getGameId()); // test.openConnection().getInputStream(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (type == TourneyType.MULTI_GAME) { // First create the tournament // Use schedule code to create the set of games and place them in the database as placeholders // Create a timer to check for idle machines and schedule games } else { } // Tournaments allTournaments = (Tournaments) // FacesContext.getCurrentInstance() // .getExternalContext().getApplicationMap().get(Tournaments.getKey()); // allTournaments.addTournament(newTourney); return "Success"; } public List<Database.Pom> getPomList(){ List<Database.Pom> poms = new ArrayList<Database.Pom>(); Database db = new Database(); try { poms = db.getPoms(); db.closeConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return poms; } public List<Machine> getAvailableMachineList(){ List<Machine> machines = new ArrayList<Machine>(); Database db = new Database(); try { List<Machine> all = db.getMachines(); for(Machine m : all){ if(m.isAvailable()){ machines.add(m); } } db.closeConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return machines; } public Date getFromTime() { return fromTime; } public void setFromTime(Date fromTime) { this.fromTime = fromTime; } public Date getToTime() { return toTime; } public void setToTime(Date toTime) { this.toTime = toTime; } public List<String> getLocations() { return locations; } public void setLocations(List<String> locations) { this.locations = locations; } public String getSelectedPom() { return selectedPom; } public void setSelectedPom(String selectedPom) { this.selectedPom = selectedPom; } public int getSize1() { return size1; } public void setSize1(int size1) { this.size1 = size1; } public int getNumberSize1() { return numberSize1; } public void setNumberSize1(int numberSize1) { this.numberSize1 = numberSize1; } public int getSize2() { return size2; } public void setSize2(int size2) { this.size2 = size2; } public int getNumberSize2() { return numberSize2; } public void setNumberSize2(int numberSize2) { this.numberSize2 = numberSize2; } public int getSize3() { return size3; } public void setSize3(int size3) { this.size3 = size3; } public int getNumberSize3() { return numberSize3; } public void setNumberSize3(int numberSize3) { this.numberSize3 = numberSize3; } }
false
true
public String createTournament() { // Create a tournament and insert it into the application context Tournament newTourney = new Tournament(); if (type == TourneyType.SINGLE_GAME) { /*this.setPomName(pom.getName()); upload.setUploadedFile(getPom()); String finalFile = upload.submit(this.getPomName());*/ newTourney.setPomName(selectedPom); String hostip = "http://"; try { InetAddress thisIp =InetAddress.getLocalHost(); hostip += thisIp.getHostAddress() + ":8080"; } catch (UnknownHostException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } Database db = new Database(); newTourney.setPomUrl(hostip+"/TournamentScheduler/faces/pom.jsp?location="+newTourney.getPomName()); newTourney.setMaxBrokers(getMaxBrokers()); newTourney.setStartTime(getStartTime()); newTourney.setTournamentName(getTournamentName()); // Add one game to the global context and to the tournament // Add game to all games and to Tournament //allGames.addGame(newGame); //newTourney.addGame(newGame); //Tournaments.getAllTournaments().addTournament(newTourney); // Start a single game and send jenkins request to kick the server // at the appropriate time String allLocations = ""; for (String s : locations){ allLocations += s + ","; } int tourneyId = 0; int gameId = 0; try { //Starts new transaction to prevent race conditions System.out.println("Starting transaction"); db.startTrans(); //Adds new tournament to the database System.out.println("Adding tourney"); db.addTournament(newTourney.getTournamentName(), true, 1, new java.sql.Date(newTourney.getStartTime().getTime()), "SINGLE_GAME", newTourney.getPomUrl(), allLocations, maxBrokers); //Grabs the tourney Id System.out.println("Getting tourneyId"); tourneyId = db.getMaxTourneyId(); // Adds a new game to the database System.out.println("Adding game"); db.addGame(newTourney.getTournamentName(), tourneyId, size1, new java.sql.Date(startTime.getTime())); // Grabs the game id System.out.println("Getting gameId"); gameId = db.getMaxGameId(); System.out.println("Creating game: "+ gameId +" properties"); CreateProperties.genProperties(gameId, locations, fromTime, toTime); // Sets the url for the properties file based on the game id. // Properties are created at random withing specified parameters System.out.println("Updating properties game: " + gameId); db.updateGamePropertiesById(gameId); System.out.println("Committing transaction"); db.commitTrans(); Properties props = new Properties(); try { props.load(Database.class.getClassLoader().getResourceAsStream( "/tournament.properties")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } db.closeConnection(); // Only schedule the bootstrap and sim if db was updated successfully Scheduler.getScheduler().schedule(new RunBootstrap(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), new Date()); // A sim will only run if the bootstrap exists Scheduler.getScheduler().schedule(new RunGame(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), startTime); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Scheduler.getScheduler().schedule( // new StartServer(newGame, Machines.getAllMachines(), // Tournaments.getAllTournaments()), //newGame.getStartTime()); try { // TODO:REMOVE this is only to simulate the message from the // server // Thread.sleep(6000); // URL test = new // URL("http://localhost:8080/TournamentScheduler/faces/serverInterface.jsp?action=status&status=ready&gameId="+newGame.getGameId()); // test.openConnection().getInputStream(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (type == TourneyType.MULTI_GAME) { // First create the tournament // Use schedule code to create the set of games and place them in the database as placeholders // Create a timer to check for idle machines and schedule games } else { } // Tournaments allTournaments = (Tournaments) // FacesContext.getCurrentInstance() // .getExternalContext().getApplicationMap().get(Tournaments.getKey()); // allTournaments.addTournament(newTourney); return "Success"; }
public String createTournament() { // Create a tournament and insert it into the application context Tournament newTourney = new Tournament(); if (type == TourneyType.SINGLE_GAME) { /*this.setPomName(pom.getName()); upload.setUploadedFile(getPom()); String finalFile = upload.submit(this.getPomName());*/ newTourney.setPomName(selectedPom); String hostip = "http://"; try { InetAddress thisIp =InetAddress.getLocalHost(); hostip += thisIp.getHostAddress() + ":8080"; } catch (UnknownHostException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } Database db = new Database(); newTourney.setPomUrl(hostip+"/TournamentScheduler/faces/pom.jsp?location="+newTourney.getPomName()); newTourney.setMaxBrokers(getMaxBrokers()); newTourney.setStartTime(getStartTime()); newTourney.setTournamentName(getTournamentName()); // Add one game to the global context and to the tournament // Add game to all games and to Tournament //allGames.addGame(newGame); //newTourney.addGame(newGame); //Tournaments.getAllTournaments().addTournament(newTourney); // Start a single game and send jenkins request to kick the server // at the appropriate time String allLocations = ""; for (String s : locations){ allLocations += s + ","; } int tourneyId = 0; int gameId = 0; try { //Starts new transaction to prevent race conditions System.out.println("Starting transaction"); db.startTrans(); //Adds new tournament to the database System.out.println("Adding tourney"); db.addTournament(newTourney.getTournamentName(), true, 1, new java.sql.Date(newTourney.getStartTime().getTime()), "SINGLE_GAME", newTourney.getPomUrl(), allLocations, maxBrokers); //Grabs the tourney Id System.out.println("Getting tourneyId"); tourneyId = db.getMaxTourneyId(); // Adds a new game to the database System.out.println("Adding game"); db.addGame(newTourney.getTournamentName(), tourneyId, size1, new java.sql.Date(startTime.getTime())); // Grabs the game id System.out.println("Getting gameId"); gameId = db.getMaxGameId(); System.out.println("Creating game: "+ gameId +" properties"); CreateProperties.genProperties(gameId, locations, fromTime, toTime); // Sets the url for the properties file based on the game id. // Properties are created at random withing specified parameters System.out.println("Updating properties game: " + gameId); db.updateGamePropertiesById(gameId); System.out.println("Committing transaction"); db.commitTrans(); Properties props = new Properties(); try { props.load(Database.class.getClassLoader().getResourceAsStream( "/tournament.properties")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } db.closeConnection(); // Only schedule the bootstrap and sim if db was updated successfully scheduler.runBootTimer(gameId,new RunBootstrap(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), new Date()); // A sim will only run if the bootstrap exists scheduler.runBootTimer(gameId,new RunGame(gameId, hostip+"/TournamentScheduler/", newTourney.getPomUrl(), props.getProperty("destination")), startTime); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Scheduler.getScheduler().schedule( // new StartServer(newGame, Machines.getAllMachines(), // Tournaments.getAllTournaments()), //newGame.getStartTime()); try { // TODO:REMOVE this is only to simulate the message from the // server // Thread.sleep(6000); // URL test = new // URL("http://localhost:8080/TournamentScheduler/faces/serverInterface.jsp?action=status&status=ready&gameId="+newGame.getGameId()); // test.openConnection().getInputStream(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (type == TourneyType.MULTI_GAME) { // First create the tournament // Use schedule code to create the set of games and place them in the database as placeholders // Create a timer to check for idle machines and schedule games } else { } // Tournaments allTournaments = (Tournaments) // FacesContext.getCurrentInstance() // .getExternalContext().getApplicationMap().get(Tournaments.getKey()); // allTournaments.addTournament(newTourney); return "Success"; }
diff --git a/org.whole.lang/src/org/whole/lang/operations/ArtifactsGeneratorOperation.java b/org.whole.lang/src/org/whole/lang/operations/ArtifactsGeneratorOperation.java index c42ae55d2..bb5abed3c 100755 --- a/org.whole.lang/src/org/whole/lang/operations/ArtifactsGeneratorOperation.java +++ b/org.whole.lang/src/org/whole/lang/operations/ArtifactsGeneratorOperation.java @@ -1,66 +1,66 @@ /** * Copyright 2004-2012 Riccardo Solmi. All rights reserved. * This file is part of the Whole Platform. * * The Whole Platform is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * The Whole Platform is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the Whole Platform. If not, see <http://www.gnu.org/licenses/>. */ package org.whole.lang.operations; import org.whole.lang.bindings.IBindingManager; import org.whole.lang.matchers.Matcher; import org.whole.lang.model.IEntity; import org.whole.lang.reflect.ReflectionFactory; import org.whole.lang.util.BehaviorUtils; /** * @author Riccardo Solmi */ public class ArtifactsGeneratorOperation extends AbstractOperation { public static final String ID = "ArtifactsGenerator"; public static void generate(IEntity program, IBindingManager args) { ArtifactsGeneratorOperation gen = new ArtifactsGeneratorOperation(args); gen.stagedVisit(program); gen.stagedVisit(gen.getResult()); } protected ArtifactsGeneratorOperation(IBindingManager args) { super(ID, args, false); if (!args.wIsSet("workspace")) { IEntity ws = ReflectionFactory.getLanguageKit("http://lang.whole.org/Artifacts", false, null).getTemplateManager().create("workspace template"); ws = BehaviorUtils.evaluate(ws, 1, args); args.wDef("workspace", ws); } getEnvironmentManager().createEnvironment("artifacts", args).wEnterScope(); } public IEntity getResult() { IBindingManager bm = getArtifactsEnvironment(); - if (bm.wGet("packageArtifactsPoint").wIsEmpty() && + if (bm.wIsSet("packageArtifactsPoint") && bm.wGet("packageArtifactsPoint").wIsEmpty() && bm.wGet("packagesPoint").wSize() == 1 && bm.wGet("projectArtifactsPoint").wSize() == 1) bm.wGet("projectsPoint").wRemove(bm.wGet("projectArtifactsPoint").wGetParent()); IEntity workspace = bm.wGet("workspace"); Matcher.substitute(workspace, bm, false); Matcher.removeVars(workspace, false); return workspace; } public IBindingManager getArtifactsEnvironment() { return getEnvironmentManager().getEnvironment("artifacts"); } }
true
true
public IEntity getResult() { IBindingManager bm = getArtifactsEnvironment(); if (bm.wGet("packageArtifactsPoint").wIsEmpty() && bm.wGet("packagesPoint").wSize() == 1 && bm.wGet("projectArtifactsPoint").wSize() == 1) bm.wGet("projectsPoint").wRemove(bm.wGet("projectArtifactsPoint").wGetParent()); IEntity workspace = bm.wGet("workspace"); Matcher.substitute(workspace, bm, false); Matcher.removeVars(workspace, false); return workspace; }
public IEntity getResult() { IBindingManager bm = getArtifactsEnvironment(); if (bm.wIsSet("packageArtifactsPoint") && bm.wGet("packageArtifactsPoint").wIsEmpty() && bm.wGet("packagesPoint").wSize() == 1 && bm.wGet("projectArtifactsPoint").wSize() == 1) bm.wGet("projectsPoint").wRemove(bm.wGet("projectArtifactsPoint").wGetParent()); IEntity workspace = bm.wGet("workspace"); Matcher.substitute(workspace, bm, false); Matcher.removeVars(workspace, false); return workspace; }
diff --git a/src/tconstruct/util/config/PHConstruct.java b/src/tconstruct/util/config/PHConstruct.java index 07ab34891..bf2cf0c42 100644 --- a/src/tconstruct/util/config/PHConstruct.java +++ b/src/tconstruct/util/config/PHConstruct.java @@ -1,708 +1,709 @@ package tconstruct.util.config; import java.io.File; import java.io.IOException; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.Property; import tconstruct.TConstruct; import tconstruct.library.tools.AbilityHelper; public class PHConstruct { public static void initProps (File location) { /* Here we will set up the config file for the mod * First: Create a folder inside the config folder * Second: Create the actual config file * Note: Configs are a pain, but absolutely necessary for every mod. */ //File file = new File(TConstruct.proxy.getLocation() + "/config"); //file.mkdir(); //File newFile = new File(TConstruct.proxy.getLocation() + "/config/TinkersWorkshop.txt"); File newFile = new File(location + "/TinkersWorkshop.txt"); /* Some basic debugging will go a long way */ try { newFile.createNewFile(); } catch (IOException e) { TConstruct.logger.severe("Could not create configuration file for TConstruct. Reason:"); TConstruct.logger.severe(e.getLocalizedMessage()); } /* [Forge] Configuration class, used as config method */ Configuration config = new Configuration(newFile); cfglocation = location; /* Load the configuration file */ config.load(); /* Define the mod's IDs. * Avoid values below 4096 for items and in the 250-450 range for blocks */ keepHunger = config.get("Difficulty Changes", "Keep hunger on death", true).getBoolean(true); keepLevels = config.get("Difficulty Changes", "Keep levels on death", true).getBoolean(true); beginnerBook = config.get("Difficulty Changes", "Spawn beginner book", true).getBoolean(true); alphaRegen = config.get("Alpha Behavior", "Regenerate HP from food", false).getBoolean(false); alphaHunger = config.get("Alpha Behavior", "Remove hunger", false).getBoolean(false); superfunWorld = config.get("Superfun", "All the world is Superfun", false).getBoolean(false); enableTWood = config.get("Difficulty Changes", "Enable mod wooden tools", true).getBoolean(true); enableTStone = config.get("Difficulty Changes", "Enable mod stone tools", true).getBoolean(true); enableTCactus = config.get("Difficulty Changes", "Enable mod cactus tools", true).getBoolean(true); enableTBone = config.get("Difficulty Changes", "Enable mod bone tools", true).getBoolean(true); enableTFlint = config.get("Difficulty Changes", "Enable mod flint tools", true).getBoolean(true); enableTNetherrack = config.get("Difficulty Changes", "Enable mod netherrack tools", true).getBoolean(true); enableTSlime = config.get("Difficulty Changes", "Enable mod slime tools", true).getBoolean(true); enableTPaper = config.get("Difficulty Changes", "Enable mod paper tools", true).getBoolean(true); enableTBlueSlime = config.get("Difficulty Changes", "Enable mod blue slime tools", true).getBoolean(true); craftMetalTools = config.get("Difficulty Changes", "Craft metals with Wood Patterns", false).getBoolean(false); vanillaMetalBlocks = config.get("Difficulty Changes", "Craft vanilla metal blocks", true).getBoolean(true); lavaFortuneInteraction = config.get("Difficulty Changes", "Enable Auto-Smelt and Fortune interaction", true).getBoolean(true); removeVanillaToolRecipes = config.get("Difficulty Changes", "Remove Vanilla Tool Recipes", false).getBoolean(false); harderBronze = config.get("Difficulty Changes", "Lower bronze output to 2 ingots", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); miningLevelIncrease = config.get("Difficulty Changes", "Modifiers increase Mining Level", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); harderBronze = config.get("Difficulty Changes", "Lower bronze output to 2 ingots", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); //1467-1489 woodStation = config.getBlock("Wood Tool Station", 1471).getInt(1471); heldItemBlock = config.getBlock("Held Item Block", 1472).getInt(1472); lavaTank = config.getBlock("Lava Tank", 1473).getInt(1473); smeltery = config.getBlock("Smeltery", 1474).getInt(1474); oreSlag = config.getBlock("Ores Slag", 1475).getInt(1475); craftedSoil = config.getBlock("Special Soil", 1476).getInt(1476); searedTable = config.getBlock("Seared Table", 1477).getInt(1477); metalBlock = config.getBlock("Metal Storage", 1478).getInt(1478); /*metalFlowing = config.getBlock("Liquid Metal Flowing", 1479).getInt(1479); metalStill = config.getBlock("Liquid Metal Still", 1480).getInt(1480);*/ multiBrick = config.getBlock("Multi Brick", 1481).getInt(1481); stoneTorch = config.getBlock("Stone Torch", 1484).getInt(1484); stoneLadder = config.getBlock("Stone Ladder", 1479).getInt(1479); oreBerry = config.getBlock("Ore Berry One", 1485).getInt(1485); oreBerrySecond = config.getBlock("Ore Berry Two", 1486).getInt(1486); oreGravel = config.getBlock("Ores Gravel", 1488).getInt(1488); speedBlock = config.getBlock("Speed Block", 1489).getInt(1489); landmine = config.getBlock("Landmine", 1470).getInt(1470); toolForge = config.getBlock("Tool Forge", 1468).getInt(1468); multiBrickFancy = config.getBlock("Multi Brick Fancy", 1467).getInt(1467); barricadeOak = config.getBlock("Oak Barricade", 1469).getInt(1469); barricadeSpruce = config.getBlock("Spruce Barricade", 1482).getInt(1482); barricadeBirch = config.getBlock("Birch Barricade", 1483).getInt(1483); barricadeJungle = config.getBlock("Jungle Barricade", 1487).getInt(1487); slimeChannel = config.getBlock("Slime Channel", 3190).getInt(3190); slimePad = config.getBlock("Slime Pad", 3191).getInt(3191); //Thermal Expansion moltenSilver = config.getBlock("Molten Silver", 3195).getInt(3195); moltenLead = config.getBlock("Molten Lead", 3196).getInt(3196); moltenNickel = config.getBlock("Molten Nickel", 3197).getInt(3197); moltenShiny = config.getBlock("Molten Platinum", 3198).getInt(3198); moltenInvar = config.getBlock("Molten Invar", 3199).getInt(3199); moltenElectrum = config.getBlock("Molten Electrum", 3200).getInt(3200); moltenIron = config.getBlock("Molten Iron", 3201).getInt(3201); moltenGold = config.getBlock("Molten Gold", 3202).getInt(3202); moltenCopper = config.getBlock("Molten Copper", 3203).getInt(3203); moltenTin = config.getBlock("Molten Tin", 3204).getInt(3204); moltenAluminum = config.getBlock("Molten Aluminum", 3205).getInt(3205); moltenCobalt = config.getBlock("Molten Cobalt", 3206).getInt(3206); moltenArdite = config.getBlock("Molten Ardite", 3207).getInt(3207); moltenBronze = config.getBlock("Molten Bronze", 3208).getInt(3208); moltenAlubrass = config.getBlock("Molten Aluminum Brass", 3209).getInt(3209); moltenManyullyn = config.getBlock("Molten Manyullyn", 3210).getInt(3210); moltenAlumite = config.getBlock("Molten Alumite", 3211).getInt(3211); moltenObsidian = config.getBlock("Molten Obsidian", 3212).getInt(3212); moltenSteel = config.getBlock("Molten Steel", 3213).getInt(3213); moltenGlass = config.getBlock("Molten Glass", 3214).getInt(3214); moltenStone = config.getBlock("Molten Stone", 3215).getInt(3215); moltenEmerald = config.getBlock("Molten Emerald", 3216).getInt(3216); blood = config.getBlock("Liquid Cow", 3217).getInt(3217); moltenEnder = config.getBlock("Molten Ender", 3218).getInt(3218); //3221+ //3221 //3222 glass = config.getBlock("Clear Glass", 3223).getInt(3223); stainedGlass = config.getBlock("Stained Glass", 3224).getInt(3224); stainedGlassClear = config.getBlock("Clear Stained Glass", 3225).getInt(3225); redstoneMachine = config.getBlock("Redstone Machines", 3226).getInt(3226); dryingRack = config.getBlock("Drying Rack", 3227).getInt(3227); glassPane = config.getBlock("Glass Pane", 3228).getInt(3228); stainedGlassClearPane = config.getBlock("Clear Stained Glass Pane", 3229).getInt(3229); searedSlab = config.getBlock("Seared Slab", 3230).getInt(3230); speedSlab = config.getBlock("Speed Slab", 3231).getInt(3231); punji = config.getBlock("Punji", 3232).getInt(3232); woodCrafter = config.getBlock("Crafting Station", 3233).getInt(3233); essenceExtractor = config.getBlock("Essence Extractor", 3234).getInt(3234); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); //3246 castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); airTank = config.getBlock("Air Tank", 3246).getInt(3246); castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); manual = config.getItem("Patterns and Misc", "Tinker's Manual", 14018).getInt(14018); blankPattern = config.getItem("Patterns and Misc", "Blank Patterns", 14019).getInt(14019); materials = config.getItem("Patterns and Misc", "Materials", 14020).getInt(14020); toolRod = config.getItem("Patterns and Misc", "Tool Rod", 14021).getInt(14021); toolShard = config.getItem("Patterns and Misc", "Tool Shard", 14022).getInt(14022); woodPattern = config.getItem("Patterns and Misc", "Wood Pattern", 14023).getInt(14023); metalPattern = config.getItem("Patterns and Misc", "Metal Pattern", 14024).getInt(14024); armorPattern = config.getItem("Patterns and Misc", "Armor Pattern", 14025).getInt(14025); pickaxeHead = config.getItem("Tool Parts", "Pickaxe Head", 14026).getInt(14026); shovelHead = config.getItem("Tool Parts", "Shovel Head", 14027).getInt(14027); axeHead = config.getItem("Tool Parts", "Axe Head", 14028).getInt(14028); hoeHead = config.getItem("Tool Parts", "Hoe Head", 14029).getInt(14029); swordBlade = config.getItem("Tool Parts", "Sword Blade", 14030).getInt(14030); largeGuard = config.getItem("Tool Parts", "Large Guard", 14031).getInt(14031); medGuard = config.getItem("Tool Parts", "Medium Guard", 14032).getInt(14032); crossbar = config.getItem("Tool Parts", "Crossbar", 14033).getInt(14033); binding = config.getItem("Tool Parts", "Tool Binding", 14034).getInt(14034); frypanHead = config.getItem("Tool Parts", "Frypan Head", 14035).getInt(14035); signHead = config.getItem("Tool Parts", "Sign Head", 14036).getInt(14036); lumberHead = config.getItem("Tool Parts", "Lumber Axe Head", 14037).getInt(14037); knifeBlade = config.getItem("Tool Parts", "Knife Blade", 14038).getInt(14038); chiselHead = config.getItem("Tool Parts", "Chisel Head", 14039).getInt(14039); scytheBlade = config.getItem("Tool Parts", "Scythe Head", 14040).getInt(14040); toughBinding = config.getItem("Tool Parts", "Tough Binding", 14041).getInt(14041); toughRod = config.getItem("Tool Parts", "Tough Rod", 14042).getInt(14042); largeSwordBlade = config.getItem("Tool Parts", "Large Sword Blade", 14043).getInt(14043); largePlate = config.getItem("Tool Parts", "Large Plate", 14044).getInt(14044); excavatorHead = config.getItem("Tool Parts", "Excavator Head", 14045).getInt(14045); hammerHead = config.getItem("Tool Parts", "Hammer Head", 14046).getInt(14046); fullGuard = config.getItem("Tool Parts", "Full Guard", 14047).getInt(14047); bowstring = config.getItem("Tool Parts", "Bowstring", 14048).getInt(14048); arrowhead = config.getItem("Tool Parts", "Arrowhead", 14049).getInt(14049); fletching = config.getItem("Tool Parts", "Fletching", 14050).getInt(14050); pickaxe = config.getItem("Tools", "Pickaxe", 14051).getInt(14051); shovel = config.getItem("Tools", "Shovel", 14052).getInt(14052); axe = config.getItem("Tools", "Axe", 14053).getInt(14053); hoe = config.getItem("Tools", "Hoe", 14054).getInt(14054); broadsword = config.getItem("Tools", "Broadsword", 14055).getInt(14055); rapier = config.getItem("Tools", "Rapier", 14057).getInt(14057); longsword = config.getItem("Tools", "Longsword", 14056).getInt(14056); dagger = config.getItem("Tools", "Dagger", 14065).getInt(14065); frypan = config.getItem("Tools", "Frying Pan", 14058).getInt(14058); battlesign = config.getItem("Tools", "Battlesign", 14059).getInt(14059); mattock = config.getItem("Tools", "Mattock", 14060).getInt(14060); lumberaxe = config.getItem("Tools", "Lumber Axe", 14061).getInt(14061); longbow = config.getItem("Tools", "Longbow", 14062).getInt(14062); shortbow = config.getItem("Tools", "Shortbow", 14063).getInt(14063); potionLauncher = config.getItem("Tools", "Potion Launcher", 14064).getInt(14064); chisel = config.getItem("Tools", "Chisel", 14066).getInt(14066); scythe = config.getItem("Tools", "Scythe", 14067).getInt(14067); cleaver = config.getItem("Tools", "Cleaver", 14068).getInt(14068); excavator = config.getItem("Tools", "Excavator", 14069).getInt(14069); hammer = config.getItem("Tools", "Hammer", 14070).getInt(14070); battleaxe = config.getItem("Tools", "Battleaxe", 14071).getInt(14071); cutlass = config.getItem("Tools", "Cutlass", 14072).getInt(14072); arrow = config.getItem("Tools", "Arrow", 14073).getInt(14073); buckets = config.getItem("Patterns and Misc", "Buckets", 14101).getInt(14101); uselessItem = config.getItem("Patterns and Misc", "Title Icon", 14102).getInt(14102); slimefood = config.getItem("Patterns and Misc", "Strange Food", 14103).getInt(14103); oreChunks = config.getItem("Patterns and Misc", "Ore Chunks", 14104).getInt(14104); heartCanister = config.getItem("Equipables", "Heart Canister", 14105).getInt(14105); diamondApple = config.getItem("Patterns and Misc", "Jeweled Apple", 14107).getInt(14107); woodHelmet = config.getItem("Equipables", "Wooden Helmet", 14106).getInt(14106); woodChestplate = config.getItem("Equipables", "Wooden Chestplate", 14108).getInt(14108); woodPants = config.getItem("Equipables", "Wooden Pants", 14109).getInt(14109); woodBoots = config.getItem("Equipables", "Wooden Boots", 14110).getInt(14110); glove = config.getItem("Equipables", "Gloves", 14111).getInt(14111); knapsack = config.getItem("Equipables", "Knapsack", 14112).getInt(14112); goldHead = config.getItem("Patterns and Misc", "Golden Head", 14113).getInt(14113); essenceCrystal = config.getItem("Patterns and Misc", "Essence Crystal", 14114).getInt(14114); jerky = config.getItem("Patterns and Misc", "Jerky", 14115).getInt(14115); boolean ic2 = true; boolean xycraft = true; try { Class c = Class.forName("ic2.core.IC2"); ic2 = false; } catch (Exception e) { } try { Class c = Class.forName("soaryn.xycraft.core.XyCraft"); xycraft = false; } catch (Exception e) { } generateCopper = config.get("Worldgen Disabler", "Generate Copper", ic2).getBoolean(ic2); generateTin = config.get("Worldgen Disabler", "Generate Tin", ic2).getBoolean(ic2); generateAluminum = config.get("Worldgen Disabler", "Generate Aluminum", xycraft).getBoolean(xycraft); generateNetherOres = config.get("Worldgen Disabler", "Generate Cobalt and Ardite", true).getBoolean(true); generateIronSurface = config.get("Worldgen Disabler", "Generate Surface Iron", true).getBoolean(true); generateGoldSurface = config.get("Worldgen Disabler", "Generate Surface Gold", true).getBoolean(true); generateCopperSurface = config.get("Worldgen Disabler", "Generate Surface Copper", true).getBoolean(true); generateTinSurface = config.get("Worldgen Disabler", "Generate Surface Tin", true).getBoolean(true); generateAluminumSurface = config.get("Worldgen Disabler", "Generate Surface Aluminum", true).getBoolean(true); generateIronBush = config.get("Worldgen Disabler", "Generate Iron Bushes", true).getBoolean(true); generateGoldBush = config.get("Worldgen Disabler", "Generate Gold Bushes", true).getBoolean(true); generateCopperBush = config.get("Worldgen Disabler", "Generate Copper Bushes", true).getBoolean(true); generateTinBush = config.get("Worldgen Disabler", "Generate Tin Bushes", true).getBoolean(true); generateAluminumBush = config.get("Worldgen Disabler", "Generate Aluminum Bushes", true).getBoolean(true); generateEssenceBush = config.get("Worldgen Disabler", "Generate Essence Bushes", true).getBoolean(true); addToVillages = config.get("Worldgen Disabler", "Add Village Generation", true).getBoolean(true); copperuDensity = config.get("Worldgen", "Copper Underground Density", 2, "Density: Chances per chunk").getInt(2); tinuDensity = config.get("Worldgen", "Tin Underground Density", 2).getInt(2); aluminumuDensity = config.get("Worldgen", "Aluminum Underground Density", 3).getInt(3); netherDensity = config.get("Worldgen", "Nether Ores Density", 8).getInt(8); copperuMinY = config.get("Worldgen", "Copper Underground Min Y", 20).getInt(20); copperuMaxY = config.get("Worldgen", "Copper Underground Max Y", 60).getInt(60); tinuMinY = config.get("Worldgen", "Tin Underground Min Y", 0).getInt(0); tinuMaxY = config.get("Worldgen", "Tin Underground Max Y", 40).getInt(40); aluminumuMinY = config.get("Worldgen", "Aluminum Underground Min Y", 0).getInt(0); aluminumuMaxY = config.get("Worldgen", "Aluminum Underground Max Y", 64).getInt(64); ironsRarity = config.get("Worldgen", "Iron Surface Rarity", 400).getInt(400); goldsRarity = config.get("Worldgen", "Gold Surface Rarity", 900).getInt(900); coppersRarity = config.get("Worldgen", "Copper Surface Rarity", 100, "Rarity: 1/num to generate in chunk").getInt(100); tinsRarity = config.get("Worldgen", "Tin Surface Rarity", 100).getInt(100); aluminumsRarity = config.get("Worldgen", "Aluminum Surface Rarity", 50).getInt(50); cobaltsRarity = config.get("Worldgen", "Cobalt Surface Rarity", 2000).getInt(2000); ironBushDensity = config.get("Worldgen", "Iron Bush Density", 1).getInt(1); goldBushDensity = config.get("Worldgen", "Gold Bush Density", 1).getInt(1); copperBushDensity = config.get("Worldgen", "Copper Bush Density", 2).getInt(2); tinBushDensity = config.get("Worldgen", "Tin Bush Density", 2).getInt(2); aluminumBushDensity = config.get("Worldgen", "Aluminum Bush Density", 2).getInt(2); silverBushDensity = config.get("Worldgen", "Silver Bush Density", 1).getInt(1); ironBushRarity = config.get("Worldgen", "Iron Bush Rarity", 5).getInt(5); goldBushRarity = config.get("Worldgen", "Gold Bush Rarity", 8).getInt(8); copperBushRarity = config.get("Worldgen", "Copper Bush Rarity", 3).getInt(3); tinBushRarity = config.get("Worldgen", "Tin Bush Rarity", 3).getInt(3); aluminumBushRarity = config.get("Worldgen", "Aluminum Bush Rarity", 2).getInt(2); essenceBushRarity = config.get("Worldgen", "Essence Bush Rarity", 6).getInt(6); copperBushMinY = config.get("Worldgen", "Copper Bush Min Y", 20).getInt(20); copperBushMaxY = config.get("Worldgen", "Copper Bush Max Y", 60).getInt(60); tinBushMinY = config.get("Worldgen", "Tin Bush Min Y", 0).getInt(0); tinBushMaxY = config.get("Worldgen", "Tin Bush Max Y", 40).getInt(40); aluminumBushMinY = config.get("Worldgen", "Aluminum Bush Min Y", 0).getInt(0); aluminumBushMaxY = config.get("Worldgen", "Aluminum Bush Max Y", 60).getInt(60); seaLevel = config.get("general", "Sea level", 64).getInt(64); enableHealthRegen = config.get("Ultra Hardcore Changes", "Passive Health Regen", true).getBoolean(true); goldAppleRecipe = config.get("Ultra Hardcore Changes", "Change Crafting Recipes", false, "Makes recipes for gold apples, carrots, and melon potions more expensive").getBoolean(false); dropPlayerHeads = config.get("Ultra Hardcore Changes", "Players drop heads on death", false).getBoolean(false); uhcGhastDrops = config.get("Ultra Hardcore Changes", "Change Ghast drops to Gold Ingots", false).getBoolean(false); worldBorder = config.get("Ultra Hardcore Changes", "Add World Border", false).getBoolean(false); worldBorderSize = config.get("Ultra Hardcore Changes", "World Border Radius", 1000).getInt(1000); freePatterns = config.get("Ultra Hardcore Changes", "Add Patterns to Pattern Chests", false, "Gives all tier 1 patterns when pattern chest is placed").getBoolean(false); AbilityHelper.necroticUHS = config.get("Ultra Hardcore Changes", "Necrotic modifier only heals on hostile mob kills", false).getBoolean(false); //Slime pools islandRarity = config.get("Worldgen", "Slime Island Rarity", 1450).getInt(1450); //Looks Property conTexMode = config.get("Looks", "Connected Textures Enabled", true); conTexMode.comment = "0 = disabled, 1 = enabled, 2 = enabled + ignore stained glass meta"; connectedTexturesMode = conTexMode.getInt(2); //dimension blacklist cfgDimBlackList = config.get("DimBlackList", "SlimeIslandDimBlacklist",new int[]{}).getIntList(); slimeIslGenDim0Only = config.get("DimBlackList","GenerateSlimeIslandInDim0Only" , false).getBoolean(false); slimeIslGenDim0 = config.get("DimBlackList", "slimeIslGenDim0", true).getBoolean(true); //Experimental functionality throwableSmeltery = config.get("Experimental", "Items can be thrown into smelteries", true).getBoolean(true); //Addon stuff isCleaverTwoHanded = config.get("Battlegear", "Can Cleavers have shields", true).getBoolean(true); isHatchetWeapon = config.get("Battlegear", "Are Hatches also weapons", true).getBoolean(true); /* Save the configuration file */ config.save(); File gt = new File(location + "/GregTech"); if (gt.exists()) { File gtDyn = new File(location + "/GregTech/DynamicConfig.cfg"); Configuration gtConfig = new Configuration(gtDyn); gtConfig.load(); gregtech = gtConfig.get("smelting", "tile.anvil.slightlyDamaged", false).getBoolean(false); + TConstruct.logger.severe("Gelatinous iceberg dead ahead! Entering Greggy waters! Abandon hope all ye who enter here! (No, seriously, we don't support GT. Don't report any issues. Thanks.)"); } } //Blocks public static int woodStation; public static int toolForge; public static int heldItemBlock; public static int woodCrafter; public static int woodCrafterSlab; public static int ores; public static int lavaTank; public static int smeltery; public static int searedTable; public static int castingChannel; public static int airTank; public static int craftedSoil; public static int oreSlag; public static int oreGravel; public static int metalBlock; public static int redstoneMachine; public static int dryingRack; //Crops public static int oreBerry; public static int oreBerrySecond; public static int netherOreBerry; //Traps public static int landmine; public static int punji; public static int barricadeOak; public static int barricadeSpruce; public static int barricadeBirch; public static int barricadeJungle; //InfiBlocks public static int speedBlock; public static int glass; public static int glassPane; public static int stainedGlass; public static int stainedGlassClear; public static int stainedGlassClearPane; //Crystalline public static int essenceExtractor; public static int essenceCrystal; //Liquids public static int metalFlowing; public static int metalStill; public static int moltenIron; public static int moltenGold; public static int moltenCopper; public static int moltenTin; public static int moltenAluminum; public static int moltenCobalt; public static int moltenArdite; public static int moltenBronze; public static int moltenAlubrass; public static int moltenManyullyn; public static int moltenAlumite; public static int moltenObsidian; public static int moltenSteel; public static int moltenGlass; public static int moltenStone; public static int moltenEmerald; public static int blood; public static int moltenEnder; public static int moltenSilver; //Thermal Expansion public static int moltenLead; public static int moltenNickel; public static int moltenShiny; public static int moltenInvar; public static int moltenElectrum; //Slime public static int slimePoolBlue; public static int slimeGel; public static int slimeGrass; public static int slimeTallGrass; public static int slimeLeaves; public static int slimeSapling; public static int slimeChannel; public static int slimePad; //Decoration public static int stoneTorch; public static int stoneLadder; public static int multiBrick; public static int multiBrickFancy; public static int redstoneBallRepeater; public static int searedSlab; public static int speedSlab; public static int meatBlock; public static int woolSlab1; public static int woolSlab2; //Patterns and misc public static int blankPattern; public static int materials; public static int toolRod; public static int toolShard; public static int woodPattern; public static int metalPattern; public static int armorPattern; public static int manual; public static int buckets; public static int uselessItem; public static int oreChunks; //Food public static int diamondApple; public static int slimefood; public static int jerky; //Tools public static int pickaxe; public static int shovel; public static int axe; public static int hoe; public static int broadsword; public static int longsword; public static int rapier; public static int dagger; public static int cutlass; public static int frypan; public static int battlesign; public static int longbow; public static int shortbow; public static int potionLauncher; public static int mattock; public static int lumberaxe; public static int scythe; public static int cleaver; public static int excavator; public static int hammer; public static int battleaxe; public static int chisel; public static int arrow; //Tool parts public static int swordBlade; public static int largeGuard; public static int medGuard; public static int crossbar; public static int knifeBlade; public static int fullGuard; public static int pickaxeHead; public static int axeHead; public static int shovelHead; public static int hoeHead; public static int frypanHead; public static int signHead; public static int chiselHead; public static int scytheBlade; public static int lumberHead; public static int largeSwordBlade; public static int excavatorHead; public static int hammerHead; public static int binding; public static int toughBinding; public static int toughRod; public static int largePlate; public static int bowstring; public static int arrowhead; public static int fletching; //Wearables public static int woodHelmet; public static int woodChestplate; public static int woodPants; public static int woodBoots; public static int glove; public static int knapsack; public static int heartCanister; //Ore values public static boolean generateCopper; public static boolean generateTin; public static boolean generateAluminum; public static boolean generateNetherOres; public static boolean generateIronSurface; public static boolean generateGoldSurface; public static boolean generateCopperSurface; public static boolean generateTinSurface; public static boolean generateAluminumSurface; public static boolean generateCobaltSurface; public static boolean generateIronBush; public static boolean generateGoldBush; public static boolean generateCopperBush; public static boolean generateTinBush; public static boolean generateAluminumBush; public static boolean generateEssenceBush; public static boolean addToVillages; public static int copperuDensity; public static int tinuDensity; public static int aluminumuDensity; public static int netherDensity; public static int ironsRarity; public static int goldsRarity; public static int coppersRarity; public static int tinsRarity; public static int aluminumsRarity; public static int cobaltsRarity; public static int ironBushDensity; public static int goldBushDensity; public static int copperBushDensity; public static int tinBushDensity; public static int aluminumBushDensity; public static int silverBushDensity; public static int ironBushRarity; public static int goldBushRarity; public static int copperBushRarity; public static int tinBushRarity; public static int aluminumBushRarity; public static int essenceBushRarity; public static int copperuMinY; public static int copperuMaxY; public static int tinuMinY; public static int tinuMaxY; public static int aluminumuMinY; public static int aluminumuMaxY; public static int copperBushMinY; public static int copperBushMaxY; public static int tinBushMinY; public static int tinBushMaxY; public static int aluminumBushMinY; public static int aluminumBushMaxY; public static int seaLevel; //Mobs //Difficulty modifiers public static boolean keepHunger; public static boolean keepLevels; public static boolean alphaRegen; public static boolean alphaHunger; public static boolean disableWoodTools; public static boolean disableStoneTools; public static boolean disableIronTools; public static boolean disableDiamondTools; public static boolean disableGoldTools; public static boolean enableTWood; public static boolean enableTStone; public static boolean enableTCactus; public static boolean enableTBone; public static boolean enableTFlint; public static boolean enableTNetherrack; public static boolean enableTSlime; public static boolean enableTPaper; public static boolean enableTBlueSlime; public static boolean craftMetalTools; public static boolean vanillaMetalBlocks; public static boolean removeVanillaToolRecipes; public static boolean harderBronze; public static boolean stencilTableCrafting; public static boolean miningLevelIncrease; public static boolean denyMattock; //Ultra Hardcore modifiers public static boolean enableHealthRegen; public static boolean goldAppleRecipe; public static boolean dropPlayerHeads; public static boolean uhcGhastDrops; public static boolean worldBorder; public static int worldBorderSize; public static boolean freePatterns; public static int goldHead; //Superfun public static boolean superfunWorld; public static boolean beginnerBook; public static boolean gregtech; public static boolean lavaFortuneInteraction; public static int islandRarity; //Looks public static int connectedTexturesMode; public static File cfglocation; //dimensionblacklist public static boolean slimeIslGenDim0Only; public static int[] cfgDimBlackList; public static boolean slimeIslGenDim0; //Experimental functionality public static boolean throwableSmeltery; //Addon stuff public static boolean isCleaverTwoHanded; public static boolean isHatchetWeapon; }
true
true
public static void initProps (File location) { /* Here we will set up the config file for the mod * First: Create a folder inside the config folder * Second: Create the actual config file * Note: Configs are a pain, but absolutely necessary for every mod. */ //File file = new File(TConstruct.proxy.getLocation() + "/config"); //file.mkdir(); //File newFile = new File(TConstruct.proxy.getLocation() + "/config/TinkersWorkshop.txt"); File newFile = new File(location + "/TinkersWorkshop.txt"); /* Some basic debugging will go a long way */ try { newFile.createNewFile(); } catch (IOException e) { TConstruct.logger.severe("Could not create configuration file for TConstruct. Reason:"); TConstruct.logger.severe(e.getLocalizedMessage()); } /* [Forge] Configuration class, used as config method */ Configuration config = new Configuration(newFile); cfglocation = location; /* Load the configuration file */ config.load(); /* Define the mod's IDs. * Avoid values below 4096 for items and in the 250-450 range for blocks */ keepHunger = config.get("Difficulty Changes", "Keep hunger on death", true).getBoolean(true); keepLevels = config.get("Difficulty Changes", "Keep levels on death", true).getBoolean(true); beginnerBook = config.get("Difficulty Changes", "Spawn beginner book", true).getBoolean(true); alphaRegen = config.get("Alpha Behavior", "Regenerate HP from food", false).getBoolean(false); alphaHunger = config.get("Alpha Behavior", "Remove hunger", false).getBoolean(false); superfunWorld = config.get("Superfun", "All the world is Superfun", false).getBoolean(false); enableTWood = config.get("Difficulty Changes", "Enable mod wooden tools", true).getBoolean(true); enableTStone = config.get("Difficulty Changes", "Enable mod stone tools", true).getBoolean(true); enableTCactus = config.get("Difficulty Changes", "Enable mod cactus tools", true).getBoolean(true); enableTBone = config.get("Difficulty Changes", "Enable mod bone tools", true).getBoolean(true); enableTFlint = config.get("Difficulty Changes", "Enable mod flint tools", true).getBoolean(true); enableTNetherrack = config.get("Difficulty Changes", "Enable mod netherrack tools", true).getBoolean(true); enableTSlime = config.get("Difficulty Changes", "Enable mod slime tools", true).getBoolean(true); enableTPaper = config.get("Difficulty Changes", "Enable mod paper tools", true).getBoolean(true); enableTBlueSlime = config.get("Difficulty Changes", "Enable mod blue slime tools", true).getBoolean(true); craftMetalTools = config.get("Difficulty Changes", "Craft metals with Wood Patterns", false).getBoolean(false); vanillaMetalBlocks = config.get("Difficulty Changes", "Craft vanilla metal blocks", true).getBoolean(true); lavaFortuneInteraction = config.get("Difficulty Changes", "Enable Auto-Smelt and Fortune interaction", true).getBoolean(true); removeVanillaToolRecipes = config.get("Difficulty Changes", "Remove Vanilla Tool Recipes", false).getBoolean(false); harderBronze = config.get("Difficulty Changes", "Lower bronze output to 2 ingots", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); miningLevelIncrease = config.get("Difficulty Changes", "Modifiers increase Mining Level", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); harderBronze = config.get("Difficulty Changes", "Lower bronze output to 2 ingots", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); //1467-1489 woodStation = config.getBlock("Wood Tool Station", 1471).getInt(1471); heldItemBlock = config.getBlock("Held Item Block", 1472).getInt(1472); lavaTank = config.getBlock("Lava Tank", 1473).getInt(1473); smeltery = config.getBlock("Smeltery", 1474).getInt(1474); oreSlag = config.getBlock("Ores Slag", 1475).getInt(1475); craftedSoil = config.getBlock("Special Soil", 1476).getInt(1476); searedTable = config.getBlock("Seared Table", 1477).getInt(1477); metalBlock = config.getBlock("Metal Storage", 1478).getInt(1478); /*metalFlowing = config.getBlock("Liquid Metal Flowing", 1479).getInt(1479); metalStill = config.getBlock("Liquid Metal Still", 1480).getInt(1480);*/ multiBrick = config.getBlock("Multi Brick", 1481).getInt(1481); stoneTorch = config.getBlock("Stone Torch", 1484).getInt(1484); stoneLadder = config.getBlock("Stone Ladder", 1479).getInt(1479); oreBerry = config.getBlock("Ore Berry One", 1485).getInt(1485); oreBerrySecond = config.getBlock("Ore Berry Two", 1486).getInt(1486); oreGravel = config.getBlock("Ores Gravel", 1488).getInt(1488); speedBlock = config.getBlock("Speed Block", 1489).getInt(1489); landmine = config.getBlock("Landmine", 1470).getInt(1470); toolForge = config.getBlock("Tool Forge", 1468).getInt(1468); multiBrickFancy = config.getBlock("Multi Brick Fancy", 1467).getInt(1467); barricadeOak = config.getBlock("Oak Barricade", 1469).getInt(1469); barricadeSpruce = config.getBlock("Spruce Barricade", 1482).getInt(1482); barricadeBirch = config.getBlock("Birch Barricade", 1483).getInt(1483); barricadeJungle = config.getBlock("Jungle Barricade", 1487).getInt(1487); slimeChannel = config.getBlock("Slime Channel", 3190).getInt(3190); slimePad = config.getBlock("Slime Pad", 3191).getInt(3191); //Thermal Expansion moltenSilver = config.getBlock("Molten Silver", 3195).getInt(3195); moltenLead = config.getBlock("Molten Lead", 3196).getInt(3196); moltenNickel = config.getBlock("Molten Nickel", 3197).getInt(3197); moltenShiny = config.getBlock("Molten Platinum", 3198).getInt(3198); moltenInvar = config.getBlock("Molten Invar", 3199).getInt(3199); moltenElectrum = config.getBlock("Molten Electrum", 3200).getInt(3200); moltenIron = config.getBlock("Molten Iron", 3201).getInt(3201); moltenGold = config.getBlock("Molten Gold", 3202).getInt(3202); moltenCopper = config.getBlock("Molten Copper", 3203).getInt(3203); moltenTin = config.getBlock("Molten Tin", 3204).getInt(3204); moltenAluminum = config.getBlock("Molten Aluminum", 3205).getInt(3205); moltenCobalt = config.getBlock("Molten Cobalt", 3206).getInt(3206); moltenArdite = config.getBlock("Molten Ardite", 3207).getInt(3207); moltenBronze = config.getBlock("Molten Bronze", 3208).getInt(3208); moltenAlubrass = config.getBlock("Molten Aluminum Brass", 3209).getInt(3209); moltenManyullyn = config.getBlock("Molten Manyullyn", 3210).getInt(3210); moltenAlumite = config.getBlock("Molten Alumite", 3211).getInt(3211); moltenObsidian = config.getBlock("Molten Obsidian", 3212).getInt(3212); moltenSteel = config.getBlock("Molten Steel", 3213).getInt(3213); moltenGlass = config.getBlock("Molten Glass", 3214).getInt(3214); moltenStone = config.getBlock("Molten Stone", 3215).getInt(3215); moltenEmerald = config.getBlock("Molten Emerald", 3216).getInt(3216); blood = config.getBlock("Liquid Cow", 3217).getInt(3217); moltenEnder = config.getBlock("Molten Ender", 3218).getInt(3218); //3221+ //3221 //3222 glass = config.getBlock("Clear Glass", 3223).getInt(3223); stainedGlass = config.getBlock("Stained Glass", 3224).getInt(3224); stainedGlassClear = config.getBlock("Clear Stained Glass", 3225).getInt(3225); redstoneMachine = config.getBlock("Redstone Machines", 3226).getInt(3226); dryingRack = config.getBlock("Drying Rack", 3227).getInt(3227); glassPane = config.getBlock("Glass Pane", 3228).getInt(3228); stainedGlassClearPane = config.getBlock("Clear Stained Glass Pane", 3229).getInt(3229); searedSlab = config.getBlock("Seared Slab", 3230).getInt(3230); speedSlab = config.getBlock("Speed Slab", 3231).getInt(3231); punji = config.getBlock("Punji", 3232).getInt(3232); woodCrafter = config.getBlock("Crafting Station", 3233).getInt(3233); essenceExtractor = config.getBlock("Essence Extractor", 3234).getInt(3234); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); //3246 castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); airTank = config.getBlock("Air Tank", 3246).getInt(3246); castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); manual = config.getItem("Patterns and Misc", "Tinker's Manual", 14018).getInt(14018); blankPattern = config.getItem("Patterns and Misc", "Blank Patterns", 14019).getInt(14019); materials = config.getItem("Patterns and Misc", "Materials", 14020).getInt(14020); toolRod = config.getItem("Patterns and Misc", "Tool Rod", 14021).getInt(14021); toolShard = config.getItem("Patterns and Misc", "Tool Shard", 14022).getInt(14022); woodPattern = config.getItem("Patterns and Misc", "Wood Pattern", 14023).getInt(14023); metalPattern = config.getItem("Patterns and Misc", "Metal Pattern", 14024).getInt(14024); armorPattern = config.getItem("Patterns and Misc", "Armor Pattern", 14025).getInt(14025); pickaxeHead = config.getItem("Tool Parts", "Pickaxe Head", 14026).getInt(14026); shovelHead = config.getItem("Tool Parts", "Shovel Head", 14027).getInt(14027); axeHead = config.getItem("Tool Parts", "Axe Head", 14028).getInt(14028); hoeHead = config.getItem("Tool Parts", "Hoe Head", 14029).getInt(14029); swordBlade = config.getItem("Tool Parts", "Sword Blade", 14030).getInt(14030); largeGuard = config.getItem("Tool Parts", "Large Guard", 14031).getInt(14031); medGuard = config.getItem("Tool Parts", "Medium Guard", 14032).getInt(14032); crossbar = config.getItem("Tool Parts", "Crossbar", 14033).getInt(14033); binding = config.getItem("Tool Parts", "Tool Binding", 14034).getInt(14034); frypanHead = config.getItem("Tool Parts", "Frypan Head", 14035).getInt(14035); signHead = config.getItem("Tool Parts", "Sign Head", 14036).getInt(14036); lumberHead = config.getItem("Tool Parts", "Lumber Axe Head", 14037).getInt(14037); knifeBlade = config.getItem("Tool Parts", "Knife Blade", 14038).getInt(14038); chiselHead = config.getItem("Tool Parts", "Chisel Head", 14039).getInt(14039); scytheBlade = config.getItem("Tool Parts", "Scythe Head", 14040).getInt(14040); toughBinding = config.getItem("Tool Parts", "Tough Binding", 14041).getInt(14041); toughRod = config.getItem("Tool Parts", "Tough Rod", 14042).getInt(14042); largeSwordBlade = config.getItem("Tool Parts", "Large Sword Blade", 14043).getInt(14043); largePlate = config.getItem("Tool Parts", "Large Plate", 14044).getInt(14044); excavatorHead = config.getItem("Tool Parts", "Excavator Head", 14045).getInt(14045); hammerHead = config.getItem("Tool Parts", "Hammer Head", 14046).getInt(14046); fullGuard = config.getItem("Tool Parts", "Full Guard", 14047).getInt(14047); bowstring = config.getItem("Tool Parts", "Bowstring", 14048).getInt(14048); arrowhead = config.getItem("Tool Parts", "Arrowhead", 14049).getInt(14049); fletching = config.getItem("Tool Parts", "Fletching", 14050).getInt(14050); pickaxe = config.getItem("Tools", "Pickaxe", 14051).getInt(14051); shovel = config.getItem("Tools", "Shovel", 14052).getInt(14052); axe = config.getItem("Tools", "Axe", 14053).getInt(14053); hoe = config.getItem("Tools", "Hoe", 14054).getInt(14054); broadsword = config.getItem("Tools", "Broadsword", 14055).getInt(14055); rapier = config.getItem("Tools", "Rapier", 14057).getInt(14057); longsword = config.getItem("Tools", "Longsword", 14056).getInt(14056); dagger = config.getItem("Tools", "Dagger", 14065).getInt(14065); frypan = config.getItem("Tools", "Frying Pan", 14058).getInt(14058); battlesign = config.getItem("Tools", "Battlesign", 14059).getInt(14059); mattock = config.getItem("Tools", "Mattock", 14060).getInt(14060); lumberaxe = config.getItem("Tools", "Lumber Axe", 14061).getInt(14061); longbow = config.getItem("Tools", "Longbow", 14062).getInt(14062); shortbow = config.getItem("Tools", "Shortbow", 14063).getInt(14063); potionLauncher = config.getItem("Tools", "Potion Launcher", 14064).getInt(14064); chisel = config.getItem("Tools", "Chisel", 14066).getInt(14066); scythe = config.getItem("Tools", "Scythe", 14067).getInt(14067); cleaver = config.getItem("Tools", "Cleaver", 14068).getInt(14068); excavator = config.getItem("Tools", "Excavator", 14069).getInt(14069); hammer = config.getItem("Tools", "Hammer", 14070).getInt(14070); battleaxe = config.getItem("Tools", "Battleaxe", 14071).getInt(14071); cutlass = config.getItem("Tools", "Cutlass", 14072).getInt(14072); arrow = config.getItem("Tools", "Arrow", 14073).getInt(14073); buckets = config.getItem("Patterns and Misc", "Buckets", 14101).getInt(14101); uselessItem = config.getItem("Patterns and Misc", "Title Icon", 14102).getInt(14102); slimefood = config.getItem("Patterns and Misc", "Strange Food", 14103).getInt(14103); oreChunks = config.getItem("Patterns and Misc", "Ore Chunks", 14104).getInt(14104); heartCanister = config.getItem("Equipables", "Heart Canister", 14105).getInt(14105); diamondApple = config.getItem("Patterns and Misc", "Jeweled Apple", 14107).getInt(14107); woodHelmet = config.getItem("Equipables", "Wooden Helmet", 14106).getInt(14106); woodChestplate = config.getItem("Equipables", "Wooden Chestplate", 14108).getInt(14108); woodPants = config.getItem("Equipables", "Wooden Pants", 14109).getInt(14109); woodBoots = config.getItem("Equipables", "Wooden Boots", 14110).getInt(14110); glove = config.getItem("Equipables", "Gloves", 14111).getInt(14111); knapsack = config.getItem("Equipables", "Knapsack", 14112).getInt(14112); goldHead = config.getItem("Patterns and Misc", "Golden Head", 14113).getInt(14113); essenceCrystal = config.getItem("Patterns and Misc", "Essence Crystal", 14114).getInt(14114); jerky = config.getItem("Patterns and Misc", "Jerky", 14115).getInt(14115); boolean ic2 = true; boolean xycraft = true; try { Class c = Class.forName("ic2.core.IC2"); ic2 = false; } catch (Exception e) { } try { Class c = Class.forName("soaryn.xycraft.core.XyCraft"); xycraft = false; } catch (Exception e) { } generateCopper = config.get("Worldgen Disabler", "Generate Copper", ic2).getBoolean(ic2); generateTin = config.get("Worldgen Disabler", "Generate Tin", ic2).getBoolean(ic2); generateAluminum = config.get("Worldgen Disabler", "Generate Aluminum", xycraft).getBoolean(xycraft); generateNetherOres = config.get("Worldgen Disabler", "Generate Cobalt and Ardite", true).getBoolean(true); generateIronSurface = config.get("Worldgen Disabler", "Generate Surface Iron", true).getBoolean(true); generateGoldSurface = config.get("Worldgen Disabler", "Generate Surface Gold", true).getBoolean(true); generateCopperSurface = config.get("Worldgen Disabler", "Generate Surface Copper", true).getBoolean(true); generateTinSurface = config.get("Worldgen Disabler", "Generate Surface Tin", true).getBoolean(true); generateAluminumSurface = config.get("Worldgen Disabler", "Generate Surface Aluminum", true).getBoolean(true); generateIronBush = config.get("Worldgen Disabler", "Generate Iron Bushes", true).getBoolean(true); generateGoldBush = config.get("Worldgen Disabler", "Generate Gold Bushes", true).getBoolean(true); generateCopperBush = config.get("Worldgen Disabler", "Generate Copper Bushes", true).getBoolean(true); generateTinBush = config.get("Worldgen Disabler", "Generate Tin Bushes", true).getBoolean(true); generateAluminumBush = config.get("Worldgen Disabler", "Generate Aluminum Bushes", true).getBoolean(true); generateEssenceBush = config.get("Worldgen Disabler", "Generate Essence Bushes", true).getBoolean(true); addToVillages = config.get("Worldgen Disabler", "Add Village Generation", true).getBoolean(true); copperuDensity = config.get("Worldgen", "Copper Underground Density", 2, "Density: Chances per chunk").getInt(2); tinuDensity = config.get("Worldgen", "Tin Underground Density", 2).getInt(2); aluminumuDensity = config.get("Worldgen", "Aluminum Underground Density", 3).getInt(3); netherDensity = config.get("Worldgen", "Nether Ores Density", 8).getInt(8); copperuMinY = config.get("Worldgen", "Copper Underground Min Y", 20).getInt(20); copperuMaxY = config.get("Worldgen", "Copper Underground Max Y", 60).getInt(60); tinuMinY = config.get("Worldgen", "Tin Underground Min Y", 0).getInt(0); tinuMaxY = config.get("Worldgen", "Tin Underground Max Y", 40).getInt(40); aluminumuMinY = config.get("Worldgen", "Aluminum Underground Min Y", 0).getInt(0); aluminumuMaxY = config.get("Worldgen", "Aluminum Underground Max Y", 64).getInt(64); ironsRarity = config.get("Worldgen", "Iron Surface Rarity", 400).getInt(400); goldsRarity = config.get("Worldgen", "Gold Surface Rarity", 900).getInt(900); coppersRarity = config.get("Worldgen", "Copper Surface Rarity", 100, "Rarity: 1/num to generate in chunk").getInt(100); tinsRarity = config.get("Worldgen", "Tin Surface Rarity", 100).getInt(100); aluminumsRarity = config.get("Worldgen", "Aluminum Surface Rarity", 50).getInt(50); cobaltsRarity = config.get("Worldgen", "Cobalt Surface Rarity", 2000).getInt(2000); ironBushDensity = config.get("Worldgen", "Iron Bush Density", 1).getInt(1); goldBushDensity = config.get("Worldgen", "Gold Bush Density", 1).getInt(1); copperBushDensity = config.get("Worldgen", "Copper Bush Density", 2).getInt(2); tinBushDensity = config.get("Worldgen", "Tin Bush Density", 2).getInt(2); aluminumBushDensity = config.get("Worldgen", "Aluminum Bush Density", 2).getInt(2); silverBushDensity = config.get("Worldgen", "Silver Bush Density", 1).getInt(1); ironBushRarity = config.get("Worldgen", "Iron Bush Rarity", 5).getInt(5); goldBushRarity = config.get("Worldgen", "Gold Bush Rarity", 8).getInt(8); copperBushRarity = config.get("Worldgen", "Copper Bush Rarity", 3).getInt(3); tinBushRarity = config.get("Worldgen", "Tin Bush Rarity", 3).getInt(3); aluminumBushRarity = config.get("Worldgen", "Aluminum Bush Rarity", 2).getInt(2); essenceBushRarity = config.get("Worldgen", "Essence Bush Rarity", 6).getInt(6); copperBushMinY = config.get("Worldgen", "Copper Bush Min Y", 20).getInt(20); copperBushMaxY = config.get("Worldgen", "Copper Bush Max Y", 60).getInt(60); tinBushMinY = config.get("Worldgen", "Tin Bush Min Y", 0).getInt(0); tinBushMaxY = config.get("Worldgen", "Tin Bush Max Y", 40).getInt(40); aluminumBushMinY = config.get("Worldgen", "Aluminum Bush Min Y", 0).getInt(0); aluminumBushMaxY = config.get("Worldgen", "Aluminum Bush Max Y", 60).getInt(60); seaLevel = config.get("general", "Sea level", 64).getInt(64); enableHealthRegen = config.get("Ultra Hardcore Changes", "Passive Health Regen", true).getBoolean(true); goldAppleRecipe = config.get("Ultra Hardcore Changes", "Change Crafting Recipes", false, "Makes recipes for gold apples, carrots, and melon potions more expensive").getBoolean(false); dropPlayerHeads = config.get("Ultra Hardcore Changes", "Players drop heads on death", false).getBoolean(false); uhcGhastDrops = config.get("Ultra Hardcore Changes", "Change Ghast drops to Gold Ingots", false).getBoolean(false); worldBorder = config.get("Ultra Hardcore Changes", "Add World Border", false).getBoolean(false); worldBorderSize = config.get("Ultra Hardcore Changes", "World Border Radius", 1000).getInt(1000); freePatterns = config.get("Ultra Hardcore Changes", "Add Patterns to Pattern Chests", false, "Gives all tier 1 patterns when pattern chest is placed").getBoolean(false); AbilityHelper.necroticUHS = config.get("Ultra Hardcore Changes", "Necrotic modifier only heals on hostile mob kills", false).getBoolean(false); //Slime pools islandRarity = config.get("Worldgen", "Slime Island Rarity", 1450).getInt(1450); //Looks Property conTexMode = config.get("Looks", "Connected Textures Enabled", true); conTexMode.comment = "0 = disabled, 1 = enabled, 2 = enabled + ignore stained glass meta"; connectedTexturesMode = conTexMode.getInt(2); //dimension blacklist cfgDimBlackList = config.get("DimBlackList", "SlimeIslandDimBlacklist",new int[]{}).getIntList(); slimeIslGenDim0Only = config.get("DimBlackList","GenerateSlimeIslandInDim0Only" , false).getBoolean(false); slimeIslGenDim0 = config.get("DimBlackList", "slimeIslGenDim0", true).getBoolean(true); //Experimental functionality throwableSmeltery = config.get("Experimental", "Items can be thrown into smelteries", true).getBoolean(true); //Addon stuff isCleaverTwoHanded = config.get("Battlegear", "Can Cleavers have shields", true).getBoolean(true); isHatchetWeapon = config.get("Battlegear", "Are Hatches also weapons", true).getBoolean(true); /* Save the configuration file */ config.save(); File gt = new File(location + "/GregTech"); if (gt.exists()) { File gtDyn = new File(location + "/GregTech/DynamicConfig.cfg"); Configuration gtConfig = new Configuration(gtDyn); gtConfig.load(); gregtech = gtConfig.get("smelting", "tile.anvil.slightlyDamaged", false).getBoolean(false); } }
public static void initProps (File location) { /* Here we will set up the config file for the mod * First: Create a folder inside the config folder * Second: Create the actual config file * Note: Configs are a pain, but absolutely necessary for every mod. */ //File file = new File(TConstruct.proxy.getLocation() + "/config"); //file.mkdir(); //File newFile = new File(TConstruct.proxy.getLocation() + "/config/TinkersWorkshop.txt"); File newFile = new File(location + "/TinkersWorkshop.txt"); /* Some basic debugging will go a long way */ try { newFile.createNewFile(); } catch (IOException e) { TConstruct.logger.severe("Could not create configuration file for TConstruct. Reason:"); TConstruct.logger.severe(e.getLocalizedMessage()); } /* [Forge] Configuration class, used as config method */ Configuration config = new Configuration(newFile); cfglocation = location; /* Load the configuration file */ config.load(); /* Define the mod's IDs. * Avoid values below 4096 for items and in the 250-450 range for blocks */ keepHunger = config.get("Difficulty Changes", "Keep hunger on death", true).getBoolean(true); keepLevels = config.get("Difficulty Changes", "Keep levels on death", true).getBoolean(true); beginnerBook = config.get("Difficulty Changes", "Spawn beginner book", true).getBoolean(true); alphaRegen = config.get("Alpha Behavior", "Regenerate HP from food", false).getBoolean(false); alphaHunger = config.get("Alpha Behavior", "Remove hunger", false).getBoolean(false); superfunWorld = config.get("Superfun", "All the world is Superfun", false).getBoolean(false); enableTWood = config.get("Difficulty Changes", "Enable mod wooden tools", true).getBoolean(true); enableTStone = config.get("Difficulty Changes", "Enable mod stone tools", true).getBoolean(true); enableTCactus = config.get("Difficulty Changes", "Enable mod cactus tools", true).getBoolean(true); enableTBone = config.get("Difficulty Changes", "Enable mod bone tools", true).getBoolean(true); enableTFlint = config.get("Difficulty Changes", "Enable mod flint tools", true).getBoolean(true); enableTNetherrack = config.get("Difficulty Changes", "Enable mod netherrack tools", true).getBoolean(true); enableTSlime = config.get("Difficulty Changes", "Enable mod slime tools", true).getBoolean(true); enableTPaper = config.get("Difficulty Changes", "Enable mod paper tools", true).getBoolean(true); enableTBlueSlime = config.get("Difficulty Changes", "Enable mod blue slime tools", true).getBoolean(true); craftMetalTools = config.get("Difficulty Changes", "Craft metals with Wood Patterns", false).getBoolean(false); vanillaMetalBlocks = config.get("Difficulty Changes", "Craft vanilla metal blocks", true).getBoolean(true); lavaFortuneInteraction = config.get("Difficulty Changes", "Enable Auto-Smelt and Fortune interaction", true).getBoolean(true); removeVanillaToolRecipes = config.get("Difficulty Changes", "Remove Vanilla Tool Recipes", false).getBoolean(false); harderBronze = config.get("Difficulty Changes", "Lower bronze output to 2 ingots", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); miningLevelIncrease = config.get("Difficulty Changes", "Modifiers increase Mining Level", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); harderBronze = config.get("Difficulty Changes", "Lower bronze output to 2 ingots", false).getBoolean(false); stencilTableCrafting = config.get("Difficulty Changes", "Craft Stencil Tables", true).getBoolean(true); denyMattock = config.get("Difficulty Changes", "Deny creation of non-metal mattocks", false).getBoolean(false); //1467-1489 woodStation = config.getBlock("Wood Tool Station", 1471).getInt(1471); heldItemBlock = config.getBlock("Held Item Block", 1472).getInt(1472); lavaTank = config.getBlock("Lava Tank", 1473).getInt(1473); smeltery = config.getBlock("Smeltery", 1474).getInt(1474); oreSlag = config.getBlock("Ores Slag", 1475).getInt(1475); craftedSoil = config.getBlock("Special Soil", 1476).getInt(1476); searedTable = config.getBlock("Seared Table", 1477).getInt(1477); metalBlock = config.getBlock("Metal Storage", 1478).getInt(1478); /*metalFlowing = config.getBlock("Liquid Metal Flowing", 1479).getInt(1479); metalStill = config.getBlock("Liquid Metal Still", 1480).getInt(1480);*/ multiBrick = config.getBlock("Multi Brick", 1481).getInt(1481); stoneTorch = config.getBlock("Stone Torch", 1484).getInt(1484); stoneLadder = config.getBlock("Stone Ladder", 1479).getInt(1479); oreBerry = config.getBlock("Ore Berry One", 1485).getInt(1485); oreBerrySecond = config.getBlock("Ore Berry Two", 1486).getInt(1486); oreGravel = config.getBlock("Ores Gravel", 1488).getInt(1488); speedBlock = config.getBlock("Speed Block", 1489).getInt(1489); landmine = config.getBlock("Landmine", 1470).getInt(1470); toolForge = config.getBlock("Tool Forge", 1468).getInt(1468); multiBrickFancy = config.getBlock("Multi Brick Fancy", 1467).getInt(1467); barricadeOak = config.getBlock("Oak Barricade", 1469).getInt(1469); barricadeSpruce = config.getBlock("Spruce Barricade", 1482).getInt(1482); barricadeBirch = config.getBlock("Birch Barricade", 1483).getInt(1483); barricadeJungle = config.getBlock("Jungle Barricade", 1487).getInt(1487); slimeChannel = config.getBlock("Slime Channel", 3190).getInt(3190); slimePad = config.getBlock("Slime Pad", 3191).getInt(3191); //Thermal Expansion moltenSilver = config.getBlock("Molten Silver", 3195).getInt(3195); moltenLead = config.getBlock("Molten Lead", 3196).getInt(3196); moltenNickel = config.getBlock("Molten Nickel", 3197).getInt(3197); moltenShiny = config.getBlock("Molten Platinum", 3198).getInt(3198); moltenInvar = config.getBlock("Molten Invar", 3199).getInt(3199); moltenElectrum = config.getBlock("Molten Electrum", 3200).getInt(3200); moltenIron = config.getBlock("Molten Iron", 3201).getInt(3201); moltenGold = config.getBlock("Molten Gold", 3202).getInt(3202); moltenCopper = config.getBlock("Molten Copper", 3203).getInt(3203); moltenTin = config.getBlock("Molten Tin", 3204).getInt(3204); moltenAluminum = config.getBlock("Molten Aluminum", 3205).getInt(3205); moltenCobalt = config.getBlock("Molten Cobalt", 3206).getInt(3206); moltenArdite = config.getBlock("Molten Ardite", 3207).getInt(3207); moltenBronze = config.getBlock("Molten Bronze", 3208).getInt(3208); moltenAlubrass = config.getBlock("Molten Aluminum Brass", 3209).getInt(3209); moltenManyullyn = config.getBlock("Molten Manyullyn", 3210).getInt(3210); moltenAlumite = config.getBlock("Molten Alumite", 3211).getInt(3211); moltenObsidian = config.getBlock("Molten Obsidian", 3212).getInt(3212); moltenSteel = config.getBlock("Molten Steel", 3213).getInt(3213); moltenGlass = config.getBlock("Molten Glass", 3214).getInt(3214); moltenStone = config.getBlock("Molten Stone", 3215).getInt(3215); moltenEmerald = config.getBlock("Molten Emerald", 3216).getInt(3216); blood = config.getBlock("Liquid Cow", 3217).getInt(3217); moltenEnder = config.getBlock("Molten Ender", 3218).getInt(3218); //3221+ //3221 //3222 glass = config.getBlock("Clear Glass", 3223).getInt(3223); stainedGlass = config.getBlock("Stained Glass", 3224).getInt(3224); stainedGlassClear = config.getBlock("Clear Stained Glass", 3225).getInt(3225); redstoneMachine = config.getBlock("Redstone Machines", 3226).getInt(3226); dryingRack = config.getBlock("Drying Rack", 3227).getInt(3227); glassPane = config.getBlock("Glass Pane", 3228).getInt(3228); stainedGlassClearPane = config.getBlock("Clear Stained Glass Pane", 3229).getInt(3229); searedSlab = config.getBlock("Seared Slab", 3230).getInt(3230); speedSlab = config.getBlock("Speed Slab", 3231).getInt(3231); punji = config.getBlock("Punji", 3232).getInt(3232); woodCrafter = config.getBlock("Crafting Station", 3233).getInt(3233); essenceExtractor = config.getBlock("Essence Extractor", 3234).getInt(3234); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); //3246 castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); slimePoolBlue = config.getBlock("Liquid Blue Slime", 3235).getInt(3235); slimeGel = config.getBlock("Congealed Slime", 3237).getInt(3237); slimeGrass = config.getBlock("Slime Grass", 3238).getInt(3238); slimeTallGrass = config.getBlock("Slime Tall Grass", 3239).getInt(3239); slimeLeaves = config.getBlock("Slime Grass Leaves", 3240).getInt(3240); slimeSapling = config.getBlock("Slime Tree Sapling", 3241).getInt(3241); meatBlock = config.getBlock("Meat Block", 3242).getInt(3242); woodCrafterSlab = config.getBlock("Crafting Slab", 3243).getInt(3243); woolSlab1 = config.getBlock("Wool Slab 1", 3244).getInt(3244); woolSlab2 = config.getBlock("Wool Slab 2", 3245).getInt(3245); airTank = config.getBlock("Air Tank", 3246).getInt(3246); castingChannel = config.getBlock("Casting Channel", 3249).getInt(3249); manual = config.getItem("Patterns and Misc", "Tinker's Manual", 14018).getInt(14018); blankPattern = config.getItem("Patterns and Misc", "Blank Patterns", 14019).getInt(14019); materials = config.getItem("Patterns and Misc", "Materials", 14020).getInt(14020); toolRod = config.getItem("Patterns and Misc", "Tool Rod", 14021).getInt(14021); toolShard = config.getItem("Patterns and Misc", "Tool Shard", 14022).getInt(14022); woodPattern = config.getItem("Patterns and Misc", "Wood Pattern", 14023).getInt(14023); metalPattern = config.getItem("Patterns and Misc", "Metal Pattern", 14024).getInt(14024); armorPattern = config.getItem("Patterns and Misc", "Armor Pattern", 14025).getInt(14025); pickaxeHead = config.getItem("Tool Parts", "Pickaxe Head", 14026).getInt(14026); shovelHead = config.getItem("Tool Parts", "Shovel Head", 14027).getInt(14027); axeHead = config.getItem("Tool Parts", "Axe Head", 14028).getInt(14028); hoeHead = config.getItem("Tool Parts", "Hoe Head", 14029).getInt(14029); swordBlade = config.getItem("Tool Parts", "Sword Blade", 14030).getInt(14030); largeGuard = config.getItem("Tool Parts", "Large Guard", 14031).getInt(14031); medGuard = config.getItem("Tool Parts", "Medium Guard", 14032).getInt(14032); crossbar = config.getItem("Tool Parts", "Crossbar", 14033).getInt(14033); binding = config.getItem("Tool Parts", "Tool Binding", 14034).getInt(14034); frypanHead = config.getItem("Tool Parts", "Frypan Head", 14035).getInt(14035); signHead = config.getItem("Tool Parts", "Sign Head", 14036).getInt(14036); lumberHead = config.getItem("Tool Parts", "Lumber Axe Head", 14037).getInt(14037); knifeBlade = config.getItem("Tool Parts", "Knife Blade", 14038).getInt(14038); chiselHead = config.getItem("Tool Parts", "Chisel Head", 14039).getInt(14039); scytheBlade = config.getItem("Tool Parts", "Scythe Head", 14040).getInt(14040); toughBinding = config.getItem("Tool Parts", "Tough Binding", 14041).getInt(14041); toughRod = config.getItem("Tool Parts", "Tough Rod", 14042).getInt(14042); largeSwordBlade = config.getItem("Tool Parts", "Large Sword Blade", 14043).getInt(14043); largePlate = config.getItem("Tool Parts", "Large Plate", 14044).getInt(14044); excavatorHead = config.getItem("Tool Parts", "Excavator Head", 14045).getInt(14045); hammerHead = config.getItem("Tool Parts", "Hammer Head", 14046).getInt(14046); fullGuard = config.getItem("Tool Parts", "Full Guard", 14047).getInt(14047); bowstring = config.getItem("Tool Parts", "Bowstring", 14048).getInt(14048); arrowhead = config.getItem("Tool Parts", "Arrowhead", 14049).getInt(14049); fletching = config.getItem("Tool Parts", "Fletching", 14050).getInt(14050); pickaxe = config.getItem("Tools", "Pickaxe", 14051).getInt(14051); shovel = config.getItem("Tools", "Shovel", 14052).getInt(14052); axe = config.getItem("Tools", "Axe", 14053).getInt(14053); hoe = config.getItem("Tools", "Hoe", 14054).getInt(14054); broadsword = config.getItem("Tools", "Broadsword", 14055).getInt(14055); rapier = config.getItem("Tools", "Rapier", 14057).getInt(14057); longsword = config.getItem("Tools", "Longsword", 14056).getInt(14056); dagger = config.getItem("Tools", "Dagger", 14065).getInt(14065); frypan = config.getItem("Tools", "Frying Pan", 14058).getInt(14058); battlesign = config.getItem("Tools", "Battlesign", 14059).getInt(14059); mattock = config.getItem("Tools", "Mattock", 14060).getInt(14060); lumberaxe = config.getItem("Tools", "Lumber Axe", 14061).getInt(14061); longbow = config.getItem("Tools", "Longbow", 14062).getInt(14062); shortbow = config.getItem("Tools", "Shortbow", 14063).getInt(14063); potionLauncher = config.getItem("Tools", "Potion Launcher", 14064).getInt(14064); chisel = config.getItem("Tools", "Chisel", 14066).getInt(14066); scythe = config.getItem("Tools", "Scythe", 14067).getInt(14067); cleaver = config.getItem("Tools", "Cleaver", 14068).getInt(14068); excavator = config.getItem("Tools", "Excavator", 14069).getInt(14069); hammer = config.getItem("Tools", "Hammer", 14070).getInt(14070); battleaxe = config.getItem("Tools", "Battleaxe", 14071).getInt(14071); cutlass = config.getItem("Tools", "Cutlass", 14072).getInt(14072); arrow = config.getItem("Tools", "Arrow", 14073).getInt(14073); buckets = config.getItem("Patterns and Misc", "Buckets", 14101).getInt(14101); uselessItem = config.getItem("Patterns and Misc", "Title Icon", 14102).getInt(14102); slimefood = config.getItem("Patterns and Misc", "Strange Food", 14103).getInt(14103); oreChunks = config.getItem("Patterns and Misc", "Ore Chunks", 14104).getInt(14104); heartCanister = config.getItem("Equipables", "Heart Canister", 14105).getInt(14105); diamondApple = config.getItem("Patterns and Misc", "Jeweled Apple", 14107).getInt(14107); woodHelmet = config.getItem("Equipables", "Wooden Helmet", 14106).getInt(14106); woodChestplate = config.getItem("Equipables", "Wooden Chestplate", 14108).getInt(14108); woodPants = config.getItem("Equipables", "Wooden Pants", 14109).getInt(14109); woodBoots = config.getItem("Equipables", "Wooden Boots", 14110).getInt(14110); glove = config.getItem("Equipables", "Gloves", 14111).getInt(14111); knapsack = config.getItem("Equipables", "Knapsack", 14112).getInt(14112); goldHead = config.getItem("Patterns and Misc", "Golden Head", 14113).getInt(14113); essenceCrystal = config.getItem("Patterns and Misc", "Essence Crystal", 14114).getInt(14114); jerky = config.getItem("Patterns and Misc", "Jerky", 14115).getInt(14115); boolean ic2 = true; boolean xycraft = true; try { Class c = Class.forName("ic2.core.IC2"); ic2 = false; } catch (Exception e) { } try { Class c = Class.forName("soaryn.xycraft.core.XyCraft"); xycraft = false; } catch (Exception e) { } generateCopper = config.get("Worldgen Disabler", "Generate Copper", ic2).getBoolean(ic2); generateTin = config.get("Worldgen Disabler", "Generate Tin", ic2).getBoolean(ic2); generateAluminum = config.get("Worldgen Disabler", "Generate Aluminum", xycraft).getBoolean(xycraft); generateNetherOres = config.get("Worldgen Disabler", "Generate Cobalt and Ardite", true).getBoolean(true); generateIronSurface = config.get("Worldgen Disabler", "Generate Surface Iron", true).getBoolean(true); generateGoldSurface = config.get("Worldgen Disabler", "Generate Surface Gold", true).getBoolean(true); generateCopperSurface = config.get("Worldgen Disabler", "Generate Surface Copper", true).getBoolean(true); generateTinSurface = config.get("Worldgen Disabler", "Generate Surface Tin", true).getBoolean(true); generateAluminumSurface = config.get("Worldgen Disabler", "Generate Surface Aluminum", true).getBoolean(true); generateIronBush = config.get("Worldgen Disabler", "Generate Iron Bushes", true).getBoolean(true); generateGoldBush = config.get("Worldgen Disabler", "Generate Gold Bushes", true).getBoolean(true); generateCopperBush = config.get("Worldgen Disabler", "Generate Copper Bushes", true).getBoolean(true); generateTinBush = config.get("Worldgen Disabler", "Generate Tin Bushes", true).getBoolean(true); generateAluminumBush = config.get("Worldgen Disabler", "Generate Aluminum Bushes", true).getBoolean(true); generateEssenceBush = config.get("Worldgen Disabler", "Generate Essence Bushes", true).getBoolean(true); addToVillages = config.get("Worldgen Disabler", "Add Village Generation", true).getBoolean(true); copperuDensity = config.get("Worldgen", "Copper Underground Density", 2, "Density: Chances per chunk").getInt(2); tinuDensity = config.get("Worldgen", "Tin Underground Density", 2).getInt(2); aluminumuDensity = config.get("Worldgen", "Aluminum Underground Density", 3).getInt(3); netherDensity = config.get("Worldgen", "Nether Ores Density", 8).getInt(8); copperuMinY = config.get("Worldgen", "Copper Underground Min Y", 20).getInt(20); copperuMaxY = config.get("Worldgen", "Copper Underground Max Y", 60).getInt(60); tinuMinY = config.get("Worldgen", "Tin Underground Min Y", 0).getInt(0); tinuMaxY = config.get("Worldgen", "Tin Underground Max Y", 40).getInt(40); aluminumuMinY = config.get("Worldgen", "Aluminum Underground Min Y", 0).getInt(0); aluminumuMaxY = config.get("Worldgen", "Aluminum Underground Max Y", 64).getInt(64); ironsRarity = config.get("Worldgen", "Iron Surface Rarity", 400).getInt(400); goldsRarity = config.get("Worldgen", "Gold Surface Rarity", 900).getInt(900); coppersRarity = config.get("Worldgen", "Copper Surface Rarity", 100, "Rarity: 1/num to generate in chunk").getInt(100); tinsRarity = config.get("Worldgen", "Tin Surface Rarity", 100).getInt(100); aluminumsRarity = config.get("Worldgen", "Aluminum Surface Rarity", 50).getInt(50); cobaltsRarity = config.get("Worldgen", "Cobalt Surface Rarity", 2000).getInt(2000); ironBushDensity = config.get("Worldgen", "Iron Bush Density", 1).getInt(1); goldBushDensity = config.get("Worldgen", "Gold Bush Density", 1).getInt(1); copperBushDensity = config.get("Worldgen", "Copper Bush Density", 2).getInt(2); tinBushDensity = config.get("Worldgen", "Tin Bush Density", 2).getInt(2); aluminumBushDensity = config.get("Worldgen", "Aluminum Bush Density", 2).getInt(2); silverBushDensity = config.get("Worldgen", "Silver Bush Density", 1).getInt(1); ironBushRarity = config.get("Worldgen", "Iron Bush Rarity", 5).getInt(5); goldBushRarity = config.get("Worldgen", "Gold Bush Rarity", 8).getInt(8); copperBushRarity = config.get("Worldgen", "Copper Bush Rarity", 3).getInt(3); tinBushRarity = config.get("Worldgen", "Tin Bush Rarity", 3).getInt(3); aluminumBushRarity = config.get("Worldgen", "Aluminum Bush Rarity", 2).getInt(2); essenceBushRarity = config.get("Worldgen", "Essence Bush Rarity", 6).getInt(6); copperBushMinY = config.get("Worldgen", "Copper Bush Min Y", 20).getInt(20); copperBushMaxY = config.get("Worldgen", "Copper Bush Max Y", 60).getInt(60); tinBushMinY = config.get("Worldgen", "Tin Bush Min Y", 0).getInt(0); tinBushMaxY = config.get("Worldgen", "Tin Bush Max Y", 40).getInt(40); aluminumBushMinY = config.get("Worldgen", "Aluminum Bush Min Y", 0).getInt(0); aluminumBushMaxY = config.get("Worldgen", "Aluminum Bush Max Y", 60).getInt(60); seaLevel = config.get("general", "Sea level", 64).getInt(64); enableHealthRegen = config.get("Ultra Hardcore Changes", "Passive Health Regen", true).getBoolean(true); goldAppleRecipe = config.get("Ultra Hardcore Changes", "Change Crafting Recipes", false, "Makes recipes for gold apples, carrots, and melon potions more expensive").getBoolean(false); dropPlayerHeads = config.get("Ultra Hardcore Changes", "Players drop heads on death", false).getBoolean(false); uhcGhastDrops = config.get("Ultra Hardcore Changes", "Change Ghast drops to Gold Ingots", false).getBoolean(false); worldBorder = config.get("Ultra Hardcore Changes", "Add World Border", false).getBoolean(false); worldBorderSize = config.get("Ultra Hardcore Changes", "World Border Radius", 1000).getInt(1000); freePatterns = config.get("Ultra Hardcore Changes", "Add Patterns to Pattern Chests", false, "Gives all tier 1 patterns when pattern chest is placed").getBoolean(false); AbilityHelper.necroticUHS = config.get("Ultra Hardcore Changes", "Necrotic modifier only heals on hostile mob kills", false).getBoolean(false); //Slime pools islandRarity = config.get("Worldgen", "Slime Island Rarity", 1450).getInt(1450); //Looks Property conTexMode = config.get("Looks", "Connected Textures Enabled", true); conTexMode.comment = "0 = disabled, 1 = enabled, 2 = enabled + ignore stained glass meta"; connectedTexturesMode = conTexMode.getInt(2); //dimension blacklist cfgDimBlackList = config.get("DimBlackList", "SlimeIslandDimBlacklist",new int[]{}).getIntList(); slimeIslGenDim0Only = config.get("DimBlackList","GenerateSlimeIslandInDim0Only" , false).getBoolean(false); slimeIslGenDim0 = config.get("DimBlackList", "slimeIslGenDim0", true).getBoolean(true); //Experimental functionality throwableSmeltery = config.get("Experimental", "Items can be thrown into smelteries", true).getBoolean(true); //Addon stuff isCleaverTwoHanded = config.get("Battlegear", "Can Cleavers have shields", true).getBoolean(true); isHatchetWeapon = config.get("Battlegear", "Are Hatches also weapons", true).getBoolean(true); /* Save the configuration file */ config.save(); File gt = new File(location + "/GregTech"); if (gt.exists()) { File gtDyn = new File(location + "/GregTech/DynamicConfig.cfg"); Configuration gtConfig = new Configuration(gtDyn); gtConfig.load(); gregtech = gtConfig.get("smelting", "tile.anvil.slightlyDamaged", false).getBoolean(false); TConstruct.logger.severe("Gelatinous iceberg dead ahead! Entering Greggy waters! Abandon hope all ye who enter here! (No, seriously, we don't support GT. Don't report any issues. Thanks.)"); } }
diff --git a/src/com/kmcguire/KFactions/P.java b/src/com/kmcguire/KFactions/P.java index 58ccf39..e9f8ddc 100644 --- a/src/com/kmcguire/KFactions/P.java +++ b/src/com/kmcguire/KFactions/P.java @@ -1,3688 +1,3688 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.kmcguire.KFactions; import com.dthielke.herochat.ChannelChatEvent; import com.dthielke.herochat.MessageFormatSupplier; import com.dthielke.herochat.StandardChannel; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.craftbukkit.util.LongHash; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.EventException; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.EntityExplodeEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerRespawnEvent; import org.bukkit.plugin.EventExecutor; import org.bukkit.plugin.java.JavaPlugin; class DataDumper implements Runnable { P p; DataDumper(P p) { this.p = p; } @Override public void run() { synchronized(p) { try { //SLAPI.save(p.factions, "plugin.data.factions"); p.DumpHumanReadableData(); p.smsg("saved data to disk"); } catch (Exception e) { p.smsg("error when trying to save data to disk"); } /// SCHEDULE OURSELVES TO RUN AGAIN ONCE WE ARE DONE p.getServer().getScheduler().scheduleAsyncDelayedTask(p, this, 20 * 60 * 10); } } } public class P extends JavaPlugin implements Listener { public Map<String, Faction> factions; private boolean saveToDisk; public static final File fdata; private static HashMap<String, Long> seeChunkLast; private HashMap<String, Long> scannerWait; private HashMap<String, FactionPlayer> fpquickmap; static final int NOPVP = 0x01; static final int NOBOOM = 0x02; static final int NODECAY = 0x04; public HashMap<Long, Integer> emcMap; // configuration public double landPowerCostPerHour; public HashSet<String> worldsEnabled; boolean enabledScanner; long scannerWaitTime; double scannerChance; boolean friendlyFire; HashSet<String> noGriefPerWorld; public Location gspawn = null; public boolean upgradeCatch; public static P __ehook; static { fdata = new File("kfactions.data.yml"); } public P() { __ehook = this; } public Map<String, Faction> LoadHumanReadableData() throws InvalidConfigurationException { YamlConfiguration cfg; ConfigurationSection cfg_root; ConfigurationSection cfg_chunks; ConfigurationSection cfg_friends; ConfigurationSection cfg_invites; ConfigurationSection cfg_players; ConfigurationSection cfg_walocs; ConfigurationSection cfg_zapin; ConfigurationSection cfg_zapout; List<String> cfg_slist; Map<String, Object> m; Faction f; FactionChunk fc; LinkedList<ConfigurationSection> zaps; HashMap<String, Faction> allfactions; zaps = new LinkedList<ConfigurationSection>(); cfg = new YamlConfiguration(); allfactions = new HashMap<String, Faction>(); try { cfg.load(fdata); } catch (FileNotFoundException ex) { return null; } catch (IOException ex) { return null; } getLogger().info(" - data loaded into memory; creating structures"); m = cfg.getValues(false); for (Entry<String, Object> e : m.entrySet()) { cfg_root = (ConfigurationSection)e.getValue(); f = new Faction(); f.chunks = new HashMap<String, Map<Long, FactionChunk>>(); f.lpud = System.currentTimeMillis(); // access all of the list/array/map type stuff cfg_chunks = cfg_root.getConfigurationSection("chunks"); if (cfg_chunks != null) { //getLogger().info("CHUNKS NOT NULL"); for (String key : cfg_chunks.getKeys(false)) { ConfigurationSection ccs; ConfigurationSection _ccs; int m1, m2, m3; fc = new FactionChunk(); m1 = key.indexOf('*'); m2 = key.indexOf('*', m1 + 1); //getLogger().info(String.format("key:%s", key)); fc.worldName = key.substring(0, m1); fc.x = Integer.parseInt(key.substring(m1 + 1, m2)); fc.z = Integer.parseInt(key.substring(m2 + 1)); fc.builders = null; fc.users = null; fc.faction = f; ccs = cfg_chunks.getConfigurationSection(key); fc.mru = ccs.getInt("mru"); fc.mrb = ccs.getInt("mrb"); _ccs = ccs.getConfigurationSection("tid"); fc.tid = new HashMap<Integer, Integer>(); if (_ccs != null) { for (Entry<String, Object> en : _ccs.getValues(false).entrySet()) { fc.tid.put(Integer.parseInt(en.getKey()), (Integer)en.getValue()); } } _ccs = ccs.getConfigurationSection("tidu"); fc.tidu = new HashMap<Integer, Integer>(); if (_ccs != null) { for (Entry<String, Object> en : _ccs.getValues(false).entrySet()) { fc.tid.put(Integer.parseInt(en.getKey()), (Integer)en.getValue()); } } if (f.chunks.get(fc.worldName) == null) { f.chunks.put(fc.worldName, new HashMap<Long, FactionChunk>()); } f.chunks.get(fc.worldName).put(LongHash.toLong(fc.x, fc.z), fc); // } } cfg_friends = cfg_root.getConfigurationSection("friends"); f.friends = new HashMap<String, Integer>(); if (cfg_friends != null) { for (Entry<String, Object> en : cfg_friends.getValues(false).entrySet()) { f.friends.put(en.getKey(), (Integer)en.getValue()); } } cfg_slist = cfg_root.getStringList("allies"); f.allies = new HashSet<String>(); if (cfg_slist != null) { for (String name : cfg_slist) { f.allies.add(name); } } cfg_slist = cfg_root.getStringList("enemies"); f.enemies = new HashSet<String>(); if (cfg_slist != null) { for (String name : cfg_slist) { f.enemies.add(name); } } cfg_invites = cfg_root.getConfigurationSection("invites"); f.invites = new HashSet<String>(); cfg_players = cfg_root.getConfigurationSection("players"); f.players = new HashMap<String, FactionPlayer>(); if (cfg_players != null) { for (Entry<String, Object> en : cfg_players.getValues(false).entrySet()) { FactionPlayer fp; fp = new FactionPlayer(); fp.faction = f; fp.name = en.getKey(); fp.rank = (Integer)en.getValue(); f.players.put(en.getKey(), fp); } } cfg_walocs = cfg_root.getConfigurationSection("walocs"); f.walocs = new HashSet<WorldAnchorLocation>(); if (cfg_walocs != null) { for (String key : cfg_walocs.getKeys(false)) { ConfigurationSection _cs; WorldAnchorLocation waloc; _cs = cfg_walocs.getConfigurationSection(key); waloc = new WorldAnchorLocation(); waloc.x = _cs.getInt("x"); waloc.y = _cs.getInt("y"); waloc.z = _cs.getInt("z"); waloc.w = _cs.getString("world"); waloc.byWho = _cs.getString("byWho"); waloc.timePlaced = _cs.getLong("timePlaced"); f.walocs.add(waloc); } } cfg_zapin = cfg_root.getConfigurationSection("zappersIncoming"); if (cfg_zapin != null) { for (String key : cfg_zapin.getKeys(false)) { ConfigurationSection _cs; _cs = cfg_zapin.getConfigurationSection(key); zaps.add(_cs); } } cfg_zapout = cfg_root.getConfigurationSection("zappersOutgoing"); if (cfg_zapout != null) { for (String key : cfg_zapout.getKeys(false)) { ConfigurationSection _cs; _cs = cfg_zapout.getConfigurationSection(key); // these have to be done last once we have all the faction // objects loaded into memory so we can lookup the faction // specified by the zap entry structure zaps.add(_cs); } } // access all the primitive value fields f.desc = cfg_root.getString("desc"); f.flags = cfg_root.getInt("flags"); f.hw = cfg_root.getString("hw"); f.hx = cfg_root.getDouble("hx"); f.hy = cfg_root.getDouble("hy"); f.hz = cfg_root.getDouble("hz"); f.lpud = cfg_root.getLong("lpud"); f.mrc = cfg_root.getInt("mrc"); f.mri = cfg_root.getInt("mri"); f.mrsh = cfg_root.getInt("mrsh"); f.mrtp = cfg_root.getInt("mrtp"); f.mrz = cfg_root.getInt("mrz"); f.name = e.getKey(); f.peaceful = false; f.power = cfg_root.getDouble("power"); f.worthEMC = cfg_root.getLong("worthEMC"); allfactions.put(f.name.toLowerCase(), f); } // iterate through the zaps for (ConfigurationSection c_zap : zaps) { ZapEntry ze; Faction f_from, f_to; ze = new ZapEntry(); ze.amount = c_zap.getDouble("amount"); f_from = allfactions.get(c_zap.getString("from")); f_to = allfactions.get(c_zap.getString("to")); ze.from = f_from; ze.to = f_to; ze.isFake = c_zap.getBoolean("isFake"); ze.perTick = c_zap.getDouble("perTick"); ze.timeStart = c_zap.getLong("timeStart"); ze.timeTick = c_zap.getLong("timeTick"); f_from.zappersOutgoing.add(ze); f_to.zappersIncoming.add(ze); } //try { // _DumpHumanReadableData(allfactions, new File("test.yml")); //} catch (Exception ex) { // ex.printStackTrace(); //} return allfactions; } /** This is mainly used to make faction name safe to use in other stuff * such as the YAML data format. * */ public String sanitizeString(String in) { char[] cb; String ac; int y; int z; ac = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_"; z = 0; cb = new char[in.length()]; for (int x = 0; x < in.length(); ++x) { for (y = 0; y < ac.length(); ++y) { if (in.charAt(x) == ac.charAt(y)) { break; } } if (y < ac.length()) { cb[z++] = in.charAt(x); } } return new String(cb, 0, z); } public void DumpHumanReadableData() throws FileNotFoundException, IOException { _DumpHumanReadableData(factions, fdata); } public void DumpHumanReadableData(File file) throws FileNotFoundException, IOException { _DumpHumanReadableData(factions, file); } private void hrfWriteChunk(RandomAccessFile raf, FactionChunk chk) throws IOException { // mru (done) // mrb (done) // tid (loop) // tidu (loop) raf.writeBytes(String.format(" %s*%d*%d:\n", chk.worldName, chk.x, chk.z)); raf.writeBytes(String.format(" mru: %d\n", chk.mru)); raf.writeBytes(String.format(" mrb: %d\n", chk.mrb)); raf.writeBytes(" tid:\n"); if (chk.tid != null) { for (Entry<Integer, Integer> e : chk.tid.entrySet()) { raf.writeBytes(String.format(" %d: %d\n", e.getKey(), e.getValue())); } } raf.writeBytes(" tidu:\n"); if (chk.tidu != null) { for (Entry<Integer, Integer> e : chk.tidu.entrySet()) { raf.writeBytes(String.format(" %d: %d\n", e.getKey(), e.getValue())); } } } public void _DumpHumanReadableData(Map<String, Faction> allfactions, File file) throws FileNotFoundException, IOException { RandomAccessFile raf; Faction f; String fname; int j; raf = new RandomAccessFile(file, "rw"); raf.setLength(0); for (Entry<String, Faction> ef : allfactions.entrySet()) { // TestFaction: f = ef.getValue(); fname = sanitizeString(f.name); if (fname.length() == 0) { continue; } //getLogger().info(String.format("dumping faction %s", fname)); raf.writeBytes(String.format("%s:\n", fname)); // members/players raf.writeBytes(" players:\n"); for (Entry<String, FactionPlayer> p : f.players.entrySet()) { raf.writeBytes(String.format(" %s: %d\n", p.getKey(), p.getValue().rank)); } raf.writeBytes(" friends:\n"); if (f.friends != null) { for (Entry<String, Integer> fr : f.friends.entrySet()) { raf.writeBytes(String.format(" %s: %d\n", fr.getKey(), fr.getValue())); } } raf.writeBytes(" chunks:\n"); // if it is a String then it is the newer version if (f.chunks != null && f.chunks.size() > 0) { Map map; map = f.chunks; if (map.keySet().iterator().next().getClass().getName().equals("java.lang.String")) { // this shall be the new execution path for upgraded data thus // after an upgrade this should be the only path ever used again for (Map<Long, FactionChunk> fcg : f.chunks.values()) { for (Entry<Long, FactionChunk> fc : fcg.entrySet()) { hrfWriteChunk(raf, fc.getValue()); } } } else { // this is the old format and I had to do some casting to get it there // because the Java deserialization puts it back as the original Map // type so here it is to provide a valid upgrade path for older // versions Map<Long, FactionChunk> m; m = (Map<Long, FactionChunk>)(Object)f.chunks; for (Entry<Long, FactionChunk> fc : m.entrySet()) { FactionChunk chk; chk = fc.getValue(); hrfWriteChunk(raf, chk); } } } // desc raf.writeBytes(String.format(" desc: %s\n", f.desc)); // flags raf.writeBytes(String.format(" flags: %d\n", f.flags)); // hw, hx, hy, hz raf.writeBytes(String.format(" hw: %s\n", f.hw)); raf.writeBytes(String.format(" hx: %f\n", f.hx)); raf.writeBytes(String.format(" hy: %f\n", f.hy)); raf.writeBytes(String.format(" hz: %f\n", f.hz)); // invitations raf.writeBytes(String.format(" invites:\n")); if (f.invites != null) { for (String inv : f.invites) { inv = sanitizeString(inv); if (inv.length() == 0) { continue; } raf.writeBytes(String.format(" - %s\n", inv)); } } // lpud raf.writeBytes(String.format(" lpud: %d\n", f.lpud)); // mrc raf.writeBytes(String.format(" mrc: %d\n", f.mrc)); // mri raf.writeBytes(String.format(" mri: %d\n", f.mri)); // mrsh raf.writeBytes(String.format(" mrsh: %d\n", f.mrsh)); // mrtp raf.writeBytes(String.format(" mrtp: %d\n", (int)f.mrtp)); // mrz raf.writeBytes(String.format(" mrz: %d\n", (int)f.mrz)); // name (already used for root key name) // power raf.writeBytes(String.format(" power: %f\n", f.power)); raf.writeBytes(" walocs:\n"); j = 0; for (WorldAnchorLocation wal : f.walocs) { raf.writeBytes(String.format(" %d:\n", j++)); raf.writeBytes(String.format(" byWho: %s\n", wal.byWho)); raf.writeBytes(String.format(" timePlaced: %d\n", wal.timePlaced)); raf.writeBytes(String.format(" world: %s\n", wal.w)); raf.writeBytes(String.format(" x: %d\n", wal.x)); raf.writeBytes(String.format(" y: %d\n", wal.y)); raf.writeBytes(String.format(" z: %d\n", wal.z)); } // worthEMC raf.writeBytes(String.format(" worthEMC: %d\n", f.worthEMC)); raf.writeBytes(" allies:\n"); for (String name : f.allies) { raf.writeBytes(String.format(" - %s", name)); } raf.writeBytes(" enemies:\n"); for (String name : f.enemies) { raf.writeBytes(String.format(" - %s", name)); } HashSet<ZapEntry>[] zez; String f_from; String f_to; zez = new HashSet[2]; zez[0] = f.zappersIncoming; zez[1] = f.zappersOutgoing; for (HashSet<ZapEntry> hsze : zez) { if (hsze == zez[0]) { raf.writeBytes(" zappersIncoming:\n"); } else { raf.writeBytes(" zappersOutgoing:\n"); } j = 0; for (ZapEntry ze : f.zappersIncoming) { raf.writeBytes(String.format(" %d:\n", j++)); // amount double raf.writeBytes(String.format(" amount: %f\n", ze.amount)); // from raf.writeBytes(String.format(" from: %s\n", ze.from.name)); // isFake boolean raf.writeBytes(String.format(" isFake: %b\n", ze.isFake)); // perTick boolean raf.writeBytes(String.format(" perTick: %f\n", ze.perTick)); // timeStart long raf.writeBytes(String.format(" timeStart: %d\n", ze.timeStart)); // timeTick long raf.writeBytes(String.format(" timeTick: %d\n", ze.timeTick)); // to Faction raf.writeBytes(String.format(" to: %s\n", ze.to.name)); } } // <end of loop> } return; } public int getEMC(int tid, int did) { if (!emcMap.containsKey(LongHash.toLong(tid, did))) return 0; return emcMap.get(LongHash.toLong(tid, did)); } /** This will hook the Herochat plugin and stand between it so that it can * replace the token {faction} in any of the format strings used. This allows * you to go inside the Herochat config file and insert {faction} where you * would like for the faction name to appear at thus providing a faction tag. * * I mainly use a single reflection hack to access a private field, then I * use an super class to do the work between the original class and the calling * Herochat plugin method. */ public void setupForHeroChat() { class ProxyExecutor implements EventExecutor { public P p; @Override public void execute(Listener ll, Event __event) throws EventException { StandardChannel stdc; String format; Class clazz; Field field; ChannelChatEvent event; class Proxy implements MessageFormatSupplier { MessageFormatSupplier mfs; P p; Player player; public Proxy(MessageFormatSupplier _mfs, P _p, Player _player) { mfs = _mfs; p = _p; player = _player; } @Override public String getStandardFormat() { String fmt; FactionPlayer fp; fmt = mfs.getStandardFormat(); p.getLogger().info(fmt); fp = p.getFactionPlayer(player.getName()); if (fp != null) { fmt = fmt.replace("{faction}", fp.faction.name); } else { fmt = fmt.replace("{faction}", ""); } return fmt; } @Override public String getConversationFormat() { return mfs.getConversationFormat(); } @Override public String getAnnounceFormat() { return mfs.getAnnounceFormat(); } @Override public String getEmoteFormat() { return mfs.getEmoteFormat(); } } event = (ChannelChatEvent)__event; Proxy g; stdc = (StandardChannel)event.getChannel(); clazz = stdc.getClass(); format = stdc.getFormat(); getLogger().info(String.format("clazz:%s format:%s", stdc.getClass().getName(), format)); try { field = clazz.getDeclaredField("formatSupplier"); field.setAccessible(true); g = new Proxy((MessageFormatSupplier)field.get(stdc), p, event.getSender().getPlayer()); field.set(stdc, g); } catch (NoSuchFieldException ex) { ex.printStackTrace(); } catch (IllegalAccessException ex) { ex.printStackTrace(); } //stdc.setFormat(null); } } ProxyExecutor pe; pe = new ProxyExecutor(); pe.p = this; Bukkit.getPluginManager().registerEvent(ChannelChatEvent.class, this, EventPriority.LOW, pe, this); } @Override public void onEnable() { File file; File femcvals; RandomAccessFile raf; Iterator<Entry<Long, Integer>> i; Entry<Long, Integer> e; FileConfiguration cfg; File fcfg; List<String> we; seeChunkLast = new HashMap<String, Long>(); scannerWait = new HashMap<String, Long>(); /* * This was done for a guy who wanted to be able to include something such * as {faction} in the Herochat plugin and have it replaced with the player's * faction. To facililate this I had to do a lot of dirty trickery. The good * news is that all that ugly stuff is contained in a single method called * 'setupForHeroChat'. The code below simply detects if Herochat has been * loaded. */ try { Class.forName("com.dthielke.herochat.MessageFormatSupplier"); setupForHeroChat(); } catch (ClassNotFoundException ex) { getLogger().info("The plugin HeroChat was not detected. Report if this is an error!"); } fcfg = new File("kfactions.config.yml"); cfg = new YamlConfiguration(); try { if (fcfg.exists()) { cfg.load(fcfg); } if (cfg.contains("enabledScanner")) enabledScanner = cfg.getBoolean("enabledScanner"); else enabledScanner = true; noGriefPerWorld = new HashSet<String>(); if (cfg.contains("noGriefPerWorld")) { for (String worldName : cfg.getStringList("noGriefPerWorld")) { noGriefPerWorld.add(worldName); } } if (cfg.contains("scannerChance")) scannerChance = cfg.getDouble("scannerChance"); else scannerChance = 0.01; if (cfg.contains("scannerWaitTime")) scannerWaitTime = cfg.getLong("scannerWaitTime"); else scannerWaitTime = 60 * 60; if (cfg.contains("landPowerCostPerHour")) landPowerCostPerHour = cfg.getInt("landPowerCostPerHour"); else landPowerCostPerHour = 85.33; if (cfg.contains("worldsEnabled")) we = cfg.getStringList("worldsEnabled"); else { we = new ArrayList(); we.add("world"); we.add("world_nether"); we.add("world_the_end"); } if (cfg.contains("friendlyFire")) friendlyFire = cfg.getBoolean("friendlyFire"); else friendlyFire = false; worldsEnabled = new HashSet<String>(); for (String wes : we) { worldsEnabled.add(wes); } ArrayList<String> tmp; tmp = new ArrayList<String>(); for (String worldName : noGriefPerWorld) { tmp.add(worldName); } cfg.set("noGriefPerWorld", tmp); cfg.set("friendlyFire", friendlyFire); cfg.set("scannerChance", scannerChance); cfg.set("landPowerCostPerHour", landPowerCostPerHour); cfg.set("worldsEnabled", we); cfg.set("enabledScanner", enabledScanner); cfg.set("scannerWaitTime", scannerWaitTime); cfg.save(fcfg); } catch (InvalidConfigurationException ex) { ex.printStackTrace(); return; } catch (FileNotFoundException ex) { ex.printStackTrace(); return; } catch (IOException ex) { ex.printStackTrace(); return; } // ensure that emcvals.txt exists femcvals = new File("kfactions.emcvals.txt"); if (!femcvals.exists()) { getLogger().info("writting new kfactions.emcvals.txt"); try { raf = new RandomAccessFile(femcvals, "rw"); i = EMCMap.emcMap.entrySet().iterator(); while (i.hasNext()) { e = i.next(); raf.writeBytes(String.format("%d:%d=%d\n", LongHash.msw(e.getKey()), LongHash.lsw(e.getKey()), e.getValue())); } raf.close(); } catch (IOException ex) { ex.printStackTrace(); } } // load from emcvals.txt emcMap = new HashMap<Long, Integer>(); getLogger().info("reading kfaction.emcvals.txt"); try { String line; int epos; int cpos; int tid; int did; int emc; raf = new RandomAccessFile(femcvals, "rw"); while ((line = raf.readLine()) != null) { epos = line.indexOf("="); if (epos > -1) { cpos = line.indexOf(":"); tid = Integer.parseInt(line.substring(0, cpos)); did = Integer.parseInt(line.substring(cpos + 1, epos)); emc = Integer.parseInt(line.substring(epos + 1)); emcMap.put(LongHash.toLong(tid, did), emc); } } raf.close(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } getLogger().info("reading plugin.gspawn.factions"); file = new File("plugin.gspawn.factions"); gspawn = null; if (file.exists()) { RandomAccessFile fis; double x, y, z; String wname; try { fis = new RandomAccessFile(file, "rw"); wname = fis.readUTF(); x = fis.readDouble(); y = fis.readDouble(); z = fis.readDouble(); fis.close(); } catch (FileNotFoundException ex) { wname = "world"; x = 0.0d; y = 0.0d; z = 0.0d; } catch (IOException ex) { wname = "world"; x = 0.0d; y = 0.0d; z = 0.0d; } gspawn = new Location(getServer().getWorld(wname), x, y, z); getServer().getWorld(wname).setSpawnLocation((int)x, (int)y, (int)z); } // IF DATA ON DISK LOAD FROM THAT OTHERWISE CREATE // A NEW DATA STRUCTURE FOR STORAGE getLogger().info("reading faction data"); saveToDisk = true; file = new File("plugin.data.factions"); // load from the original file but immediantly create a new // YAML data format file which will then be loaded if (file.exists() && !fdata.exists()) { try { getLogger().info("upgrading old binary format to YAML format!"); factions = (HashMap<String, Faction>)SLAPI.load("plugin.data.factions"); DumpHumanReadableData(); getLogger().info(" - YAML format created old data will not be loaded anymore!"); } catch (Exception ex) { ex.printStackTrace(); smsg("error when trying to load data from binary file on disk (SAVE TO DISK DISABLED)"); } } // the old data format should have been upgraded and created a new // YAML file for us to load from if (fdata.exists()) { try { factions = LoadHumanReadableData(); } catch (Exception ex) { factions = new HashMap<String, Faction>(); saveToDisk = false; ex.printStackTrace(); smsg("error when trying to load data from YAML file on disk (SAVE TO DISK DISABLED)"); } } // if both data sources do not exist if (!fdata.exists() && !file.exists()) { factions = new HashMap<String, Faction>(); smsg("found no data on disk creating new faction data"); } // EVERYTHING WENT OKAY WE PREP THE DISK COMMIT THREAD WHICH WILL RUN LATER ON //getServer().getScheduler().scheduleAsyncDelayedTask(this, new DataDumper(this), 20 * 60 * 10); this.getServer().getPluginManager().registerEvents(new BlockHook(this), this); this.getServer().getPluginManager().registerEvents(new EntityHook(this), this); this.getServer().getPluginManager().registerEvents(new PlayerHook(this), this); this.getServer().getPluginManager().registerEvents(this, this); // let faction objects initialize anything <new> .. LOL like new fields Iterator<Entry<String, Faction>> fe; Faction f; getLogger().info("ensuring faction data structures are properly initialized"); fe = factions.entrySet().iterator(); while (fe.hasNext()) { f = fe.next().getValue(); //getServer().getLogger().info(String.format("§7[f] initFromStorage(%s)", f.name)); f.initFromStorage(); // remove world anchors (temp) //getServer().getLogger().info("removing world anchors"); //for (WorldAnchorLocation wal : f.walocs) { // getServer().getWorld(wal.w).getBlockAt(wal.x, wal.y, wal.z).setTypeId(0); // getServer().getWorld(wal.w).getBlockAt(wal.x, wal.y, wal.z).setData((byte)0); //} } final P ___p; getLogger().info("creating synchronous task"); ___p = this; getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { public P p; public boolean isAsyncDone = true; @Override public void run() { // copy factions array then schedule async task to work them final Entry<String, Faction>[] flist; if (!isAsyncDone) return; isAsyncDone = false; p = ___p; synchronized (p.factions) { flist = new Entry[factions.size()]; factions.entrySet().toArray(flist); } getServer().getScheduler().scheduleAsyncDelayedTask(p, new Runnable() { @Override public void run() { for (Entry<String, Faction> e : flist) { calcZappers(e.getValue()); } isAsyncDone = true; } }); } } , 20 * 10 * 60, 20 * 10 * 60); // every 10 minutes seems decent // make job to go through and calculate zappers for factions } public void calcZappers(Faction f) { long ct, tdelta; double toTake; ct = System.currentTimeMillis(); // stops modification of power field and of zappers synchronized (f) { Iterator<ZapEntry> i; ZapEntry z; i = f.zappersIncoming.iterator(); while (i.hasNext()) { z = i.next(); tdelta = ct - z.timeTick; z.timeTick = ct; toTake = z.perTick * (double)tdelta; z.amount -= toTake; if (!z.isFake) f.power -= toTake; // do not make them go negative that is rather // too harsh and could essentially lock out a // faction from ever playing again cause they // would be unable to ever claim any land with // a large negative power if (f.power < 0) f.power = 0; // if zapper is zero-ed then remove it if (z.amount < 1) { i.remove(); synchronized (z.from) { z.from.zappersOutgoing.remove(z); } } } } } @Override public void onDisable() { try { if (saveToDisk) { //SLAPI.save(factions, "plugin.data.factions"); getLogger().info("[debug] start data dump to disk"); DumpHumanReadableData(); getLogger().info("[debug] end data dump to disk"); getServer().getLogger().info("§7[f] saved data on disable"); } else { getServer().getLogger().info("§7[f] save to disk was disabled.."); } } catch (Exception e) { getServer().getLogger().info("§7[f] exception saving data on disable"); e.printStackTrace(); return; } } public Faction getFactionByName(String factionName) { for (Faction f : factions.values()) { if (f.name.toLowerCase().equals(factionName.toLowerCase())) { return f; } } return null; } public void sendFactionMessage(Faction f, String m) { Iterator<Entry<String, FactionPlayer>> i; Player p; i = f.players.entrySet().iterator(); while (i.hasNext()) { p = getServer().getPlayer(i.next().getValue().name); if (p != null) { p.sendMessage(m); } } } public void handlePlayerLogin(PlayerLoginEvent event) { FactionPlayer fp; Faction f; Player p; p = event.getPlayer(); fp = getFactionPlayer(p.getName()); if (fp == null) return; f = fp.faction; p.sendMessage(String.format("Faction [%s] Hours Until Depletion Is %d/hours.", f.name, (int)(getFactionPower(f) / ((8192.0 / 24.0) * f.chunks.size())) )); } public void handlePlayerLogout(Player p) { FactionPlayer fp; //fp = getFactionPlayer(p.getName()); } public void handlePlayerInteract(PlayerInteractEvent event) { int x, z; World w; FactionChunk fchunk; FactionPlayer fplayer; Player player; int rank; player = event.getPlayer(); //x = player.getLocation().getBlockX() >> 4; //z = player.getLocation().getBlockZ() >> 4; w = player.getWorld(); //getServer().getLogger().info(String.format("x:%d z:%d", x, z)); // they are for sure not interacting with anything if (event.getClickedBlock() == null) return; x = event.getClickedBlock().getX() >> 4; z = event.getClickedBlock().getZ() >> 4; //getServer().getLogger().info(String.format("x:%d z:%d", x, z)); fchunk = getFactionChunk(w, x, z); if (fchunk == null) return; fplayer = getFactionPlayer(player.getName()); rank = getPlayerRankOnLand(player, fchunk, fplayer); if (fchunk.tidu != null) { Block block; if (!fchunk.tidudefreject) event.setCancelled(false); else event.setCancelled(true); block = event.getClickedBlock(); if (fchunk.tidu.containsKey(block.getTypeId())) { if (rank < fchunk.tidu.get(block.getTypeId())) { player.sendMessage(String.format("§7[f] Your rank[%d] needs to be %d or higher for %s!", rank, fchunk.tid.get(block.getTypeId()), TypeIdToNameMap.getNameFromTypeId(block.getTypeId()))); if (!fchunk.tidudefreject) event.setCancelled(true); else event.setCancelled(false); return; } return; } // } if (rank < fchunk.mru) { event.setCancelled(true); player.sendMessage(String.format("§7[f] Your rank is too low in faction %s.", fchunk.faction.name)); return; } return; } public boolean isWorldAnchor(int typeId) { if ((typeId == 214) || (typeId == 179) || (typeId == 4095)) return true; return false; } public int getPlayerRankOnLand(Player player, FactionChunk fchunk, FactionPlayer fplayer) { int rank; rank = -1; if (fchunk == null) return -1; if (fchunk.faction.friends != null) { if (fchunk.faction.friends.containsKey(player.getName())) { rank = fchunk.faction.friends.get(player.getName()); } if (fplayer != null) { if (fchunk.faction.friends.containsKey(fplayer.faction.name)) { rank = fchunk.faction.friends.get(fplayer.faction.name); } } } if (rank == -1) { if (fplayer != null) if (fplayer.faction == fchunk.faction) rank = fplayer.rank; } return rank; } public void handleBlockPlace(BlockPlaceEvent event) { int x, z; World w; FactionChunk fchunk; FactionPlayer fplayer; Player player; int rank; Block block; if (event.isCancelled()) return; block = event.getBlockPlaced(); player = event.getPlayer(); x = event.getBlock().getX() >> 4; z = event.getBlock().getZ() >> 4; w = player.getWorld(); fchunk = getFactionChunk(w, x, z); if (fchunk == null) { if (isWorldAnchor(block.getTypeId())) { player.sendMessage("§7[f] You can only place world anchors if you are on faction land."); event.setCancelled(true); return; } return; } fplayer = getFactionPlayer(player.getName()); rank = getPlayerRankOnLand(player, fchunk, fplayer); if (fchunk.tid != null) { if (!fchunk.tiddefreject) event.setCancelled(false); else event.setCancelled(true); if (fchunk.tid.containsKey(block.getTypeId())) { if (rank < fchunk.tid.get(block.getTypeId())) { player.sendMessage(String.format("§7[f] Your rank[%d] needs to be %d or higher for %s!", rank, fchunk.tid.get(block.getTypeId()), TypeIdToNameMap.getNameFromTypeId(block.getTypeId()))); if (!fchunk.tiddefreject) event.setCancelled(true); else event.setCancelled(false); return; } return; } } if (rank < fchunk.mrb) { player.sendMessage(String.format("§7[f] Your rank is too low in faction %s.", fchunk.faction.name)); event.setCancelled(true); return; } if (isWorldAnchor(block.getTypeId())) { if (fchunk.faction.walocs.size() > 1) { player.sendMessage(String.format("§7[f] You already have %d/2 world anchors placed. Remove one and replace it.", fchunk.faction.walocs.size())); event.setCancelled(true); return; } fchunk.faction.walocs.add(new WorldAnchorLocation( block.getX(), block.getY(), block.getZ(), block.getWorld().getName(), player.getName() )); } return; } @EventHandler public void handleBlockBreak(BlockBreakEvent event) { int x, z; World w; FactionChunk fchunk; FactionPlayer fplayer; Player player; int rank; Block block; if (event.isCancelled()) return; block = event.getBlock(); player = event.getPlayer(); x = event.getBlock().getX() >> 4; z = event.getBlock().getZ() >> 4; w = player.getWorld(); fchunk = getFactionChunk(w, x, z); if (fchunk == null) return; fplayer = getFactionPlayer(player.getName()); rank = getPlayerRankOnLand(player, fchunk, fplayer); if (fchunk.tid != null) { if (!fchunk.tiddefreject) event.setCancelled(false); else event.setCancelled(true); if (fchunk.tid.containsKey(block.getTypeId())) { if (rank < fchunk.tid.get(block.getTypeId())) { player.sendMessage(String.format("§7[f] Your rank[%d] needs to be %d or higher for %s!", rank, fchunk.tid.get(block.getTypeId()), TypeIdToNameMap.getNameFromTypeId(block.getTypeId()))); if (!fchunk.tiddefreject) event.setCancelled(true); else event.setCancelled(false); return; } return; } } // FINAL RANK CHECK DO OR DIE TIME if (rank < fchunk.mrb) { player.sendMessage(String.format("§7[f] Your rank is too low in faction %s.", fchunk.faction.name)); event.setCancelled(true); return; } // WORLD ANCHOR CONTROL if (isWorldAnchor(block.getTypeId())) { Iterator<WorldAnchorLocation> i; WorldAnchorLocation wal; i = fchunk.faction.walocs.iterator(); while (i.hasNext()) { wal = i.next(); if ((wal.x == block.getX()) && (wal.y == block.getY()) && (wal.z == block.getZ()) && (wal.w.equals(block.getWorld().getName()))) { player.sendMessage("§7[f] World anchor removed from faction control. You may now place one more."); i.remove(); } } } return; } @EventHandler public void handleEntityExplodeEvent(EntityExplodeEvent event) { List<Block> blocks; Iterator<Block> iter; Block b; int x, z; World w; FactionChunk fchunk; double pcost; w = event.getLocation().getWorld(); blocks = event.blockList(); iter = blocks.iterator(); while (iter.hasNext()) { b = iter.next(); x = b.getX() >> 4; z = b.getZ() >> 4; fchunk = getFactionChunk(w, x, z); if (fchunk != null) { synchronized (fchunk.faction) { if (noGriefPerWorld.contains(w.getName())) { iter.remove(); continue; } if ((fchunk.faction.flags & NOBOOM) == NOBOOM) { // remove explosion effecting // this block since it is protected // by the NOBOOM flag iter.remove(); continue; } // check if faction can pay for protection // 8192 / 24 is cost per block (equal one hour faction power) pcost = Math.random() * (8192.0 / 24.0 / 2.0 / 5.7 / 4.0); if (getFactionPower(fchunk.faction) >= pcost) { fchunk.faction.power -= pcost; iter.remove(); continue; } } } } } public boolean canPlayerBeDamaged(Player p) { Location pl; FactionChunk fc; int cx, cz; pl = p.getLocation(); cx = pl.getChunk().getX(); cz = pl.getChunk().getZ(); fc = getFactionChunk(p.getWorld(), cx, cz); if (fc == null) return true; if ((fc.faction.flags & NOPVP) == NOPVP) { return false; } return true; } @EventHandler public void handleEntityDamageEntity(EntityDamageByEntityEvent event) { Entity e, ed; Player p, pd; Location pl; int cx, cz; FactionChunk fc; FactionPlayer fp, fpd; e = event.getEntity(); if (!(e instanceof Player)) return; p = (Player)e; ed = event.getDamager(); // check for same team combat if (!friendlyFire && (ed instanceof Player)) { pd = (Player)ed; fp = getFactionPlayer(p.getName()); fpd = getFactionPlayer(pd.getName()); if (fp != null && fpd != null) { // check if same faction if (fp.faction == fpd.faction) { event.setCancelled(true); return; } // check if allied faction // TODO } } pl = p.getLocation(); cx = pl.getChunk().getX(); cz = pl.getChunk().getZ(); fc = getFactionChunk(p.getWorld(), cx, cz); if (fc == null) return; if ((fc.faction.flags & NOPVP) == NOPVP) { e = event.getDamager(); if (e instanceof Player) { p = (Player)e; p.sendMessage("§7[f] You can not attack someone who is standing on a NOPVP faction zone!"); } event.setCancelled(true); return; } return; } @EventHandler public void handlePlayerRespawnEvent(PlayerRespawnEvent event) { if (gspawn == null) return; event.setRespawnLocation(gspawn); } @EventHandler public void handlePlayerMove(PlayerMoveEvent event) { int fx, fz; int tx, tz; Faction fc, tc; FactionChunk _fc, _tc; World world; Player player; fx = event.getFrom().getBlockX() >> 4; fz = event.getFrom().getBlockZ() >> 4; tx = event.getTo().getBlockX() >> 4; tz = event.getTo().getBlockZ() >> 4; // KEEPS US FROM EATING TONS OF CPU CYCLES WHEN ALL WE NEED TO DO // IS CHECK ON CHUNK TRANSITIONS if ((fx != tx) || (fz != tz)) { player = event.getPlayer(); fc = null; tc = null; world = player.getWorld(); _fc = getFactionChunk(world, fx, fz); if (_fc != null) fc = _fc.faction; _tc = getFactionChunk(world, tx, tz); if (_tc != null) tc = _tc.faction; // IF WALKING FROM SAME TO SAME SAY NOTHING if (fc == tc) { return; } // HANDLES walking from one faction chunk to another or walking from wilderness (fc can be null or not) if (tc != null) { player.sendMessage(String.format("§7[f] You entered faction %s.", tc.name)); return; } // HANDLES walking into wilderness if (fc != null) { player.sendMessage("§7[f] You entered wilderness."); return; } } } public double getFactionPower(Faction f) { FactionPlayer fp; Iterator<Entry<String, FactionPlayer>> i; float pow; long ctime; double delta; double powcon; int landcnt; ctime = System.currentTimeMillis(); delta = (double)(ctime - f.lpud) / 1000.0d / 60.0d / 60.0d; landcnt = 0; for (Map m : f.chunks.values()) { landcnt += m.size(); } powcon = delta * (double)landcnt * landPowerCostPerHour; synchronized (f) { f.power = f.power - powcon; if (f.power < 0.0) f.power = 0.0; f.lpud = ctime; if ((f.flags & NODECAY) == NODECAY) { return (double)(landcnt + 1) * 8192.0; } } return f.power; } public FactionChunk getFactionChunk(World world, int x, int z) { Iterator<Entry<String, Faction>> i; Entry<String, Faction> e; Faction f; FactionChunk fc; i = factions.entrySet().iterator(); while (i.hasNext()) { e = i.next(); f = e.getValue(); if (f.chunks.containsKey(world.getName())) { fc = f.chunks.get(world.getName()).get(LongHash.toLong(x, z)); if (fc != null) { return fc; } } } return null; } public FactionPlayer getFactionPlayer(String playerName) { Iterator<Entry<String, Faction>> i; Entry<String, Faction> e; Faction f; playerName = playerName.toLowerCase(); i = factions.entrySet().iterator(); while (i.hasNext()) { e = i.next(); f = e.getValue(); for (Entry<String, FactionPlayer> e2 : f.players.entrySet()) { if (e2.getKey().toLowerCase().equals(playerName)) { return e2.getValue(); } } } return null; } // this is not used anymore and I guess I leave it just // for history; i used to use this but it can create // collisions and the X and Z are limited to 16-bit public Long getChunkLong(World world, int x, int z) { return new Long((world.getUID().getMostSignificantBits() << 32) | (z & 0xffff) | ((x & 0xffff) << 16)); } public static void sendPlayerBlockChange(Player p, int x, int y, int z, int typeId, byte data) { Location loc; loc = new Location(p.getWorld(), (double)x, (double)y, (double)z); p.sendBlockChange(loc, typeId, data); } public void displayHelp(Player player, String[] args) { if ((args.length > 1) && args[0].equals("help")) { // help rank if (args[1].equalsIgnoreCase("ranks")) { player.sendMessage("§7------------RANKS--------------------"); player.sendMessage("§7These commands will change a player's rank. They also set"); player.sendMessage("§7the required rank needed to perform certain commands. The"); player.sendMessage("§7rank is a number. To see your rank type §a/f who§r and"); player.sendMessage("§7find your name and in brackets is your rank. You also can"); player.sendMessage("§7not set someone equal to or above your own rank. Whoever"); player.sendMessage("§7creates the faction gets the rank of 1000 which no one else"); player.sendMessage("§7can be higher than, unless an OP performs the setrank command"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§dsetrank§r <player> <rank> - set new rank"); player.sendMessage("§dcbrank§r <rank> - set chunk build rank"); player.sendMessage("§dcurank§r <rank> - set chunk use rank"); player.sendMessage("§asetmri§r <rank> - set minimum rank to invite"); player.sendMessage("§asetmrc§r <rank> - set minimum rank to claim"); player.sendMessage("§asetmrtp§r <rank> - minimum rank to do teleport cmds and set home"); player.sendMessage("§7-------------------------------------"); return; } // help friends if (args[1].equalsIgnoreCase("friends")) { player.sendMessage("§7--------------FRIENDS----------------"); player.sendMessage("§7Friends are given a rank specified which makes them able"); player.sendMessage("§7to interact with or break/place blocks even though they"); player.sendMessage("§7are not in your faction."); player.sendMessage("§7-------------------------------------"); player.sendMessage("§aaddfriend§r <name> <rank> - add friend to faction"); player.sendMessage("§aremfriend§r <name> - remove faction friend"); player.sendMessage("§alistfriends§r - inspect chunk you are standing on"); player.sendMessage("§7-------------------------------------"); return; } // help blockrank if (args[1].equalsIgnoreCase("blockrank")) { player.sendMessage("§7-------------BLOCKRANK---------------"); player.sendMessage("§7This sets the specific rank needed to either"); player.sendMessage("§7interact with or place/break blocks. Used in"); player.sendMessage("§7conjunction with friends you can allow them"); player.sendMessage("§7access to certain blocks."); player.sendMessage("§7-------------------------------------"); player.sendMessage("§7cbr, lbr, and br are for block place/break ---"); player.sendMessage("§7cbru, lbru, and bru are for block interact ---"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§acbr or cbrus§r - clear block ranks for current claim"); player.sendMessage("§albr or lbru§r - list block ranks for current claim"); player.sendMessage("§abr or bru§r <rank> <typeID> - or hold item in hand and just give <rank>"); player.sendMessage("§7-------------------------------------"); return; } // help zap if (args[1].equalsIgnoreCase("zap")) { player.sendMessage("§7----------------ZAP------------------"); player.sendMessage("§7This is used to assault another faction. This is a"); player.sendMessage("§7alternative to using nukes/tnt/explosives. You can"); player.sendMessage("§7not zap a faction that is lower in power than your"); player.sendMessage("§7own faction!"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§asetzaprank§r - set rank needed to issue /zap commands"); player.sendMessage("§dshowzaps§r - shows incoming and outgoing zaps"); player.sendMessage("§dzap§r <faction> <amount> - zap faction's power using your own power"); player.sendMessage("§asetmrz§r <rank> - set minimum rank to zap"); player.sendMessage("§7-------------------------------------"); return; } // help home if (args[1].equalsIgnoreCase("home")) { player.sendMessage("§7---------------HOME------------------"); player.sendMessage("§7These are important commands which allow you to set"); player.sendMessage("§7a faction home so that other players can use the"); player.sendMessage("§7command /f home to teleport home. This commands"); player.sendMessage("§7consume 10% of your faction power. On some servers"); player.sendMessage("§7you may be able to use a bed to save faction power!"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§asetmrsh§r - sets minimum rank to use /f sethome"); player.sendMessage("§asethome§r - set home for faction for teleport cmds"); player.sendMessage("§ahome§r - short for tptp <yourname> home"); player.sendMessage("§7-------------------------------------"); return; } // help teleport if (args[1].equalsIgnoreCase("teleport")) { player.sendMessage("§7-------------TELEPORT----------------"); player.sendMessage("§7These are the teleport commands. You can teleport to"); player.sendMessage("§7your faction home, to spawn, or to another player."); player.sendMessage("§7These commands consume 10% of your faction power."); player.sendMessage("§7You also can not teleport to a player in your faction"); player.sendMessage("§7who is a higher rank than you. They must teleport you"); player.sendMessage("§7to them. You can teleport to someone of equal or lower"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§7rank than your self."); player.sendMessage("§atptp§r <player> <player|home> - teleport player to player "); player.sendMessage("§ahome§r - short for tptp <yourname> home"); player.sendMessage("§aspawn§r - short for tptp <yourname> spawn"); player.sendMessage("§7-------------------------------------"); return; } if (args[1].equalsIgnoreCase("basic")) { player.sendMessage("§7--------------BASIC------------------"); player.sendMessage("§dcharge§r - charge faction power from item"); player.sendMessage("§achkcharge§r - check how much charge from item"); player.sendMessage("§aunclaimall§r - unclaim all land"); player.sendMessage("§aunclaim§r - unclaim land claimed"); player.sendMessage("§dclaim§r - claim land standing on"); player.sendMessage("§adisband§r - disband faction"); player.sendMessage("§aleave§r - leave current faction"); player.sendMessage("§djoin§r <faction> - join faction after invite"); player.sendMessage("§akick§r <player> - kick out of faction"); player.sendMessage("§dinvite§r <player> - invite to faction"); player.sendMessage("§dcreate§r <name> - make new faction"); player.sendMessage("§dseechunk§r <name> - walls the chunk in glass"); player.sendMessage("§arename§r <name> - rename faction"); player.sendMessage("§7-------------------------------------"); return; } // help anchors if (args[1].equalsIgnoreCase("anchors")) { player.sendMessage("§7-------------------------------------"); player.sendMessage("§7Each faction can only place so many world anchors"); player.sendMessage("§7The current limit is 2 per faction. To see where"); player.sendMessage("§7anchors are that have been placed by players in your"); player.sendMessage("§7faction use the following command. To remove anchors"); player.sendMessage("§7that do not exist contact an administrator and tell"); player.sendMessage("§7them to use the special /resetwa command in the console."); player.sendMessage("§ashowanchors§r - shows world anchors your faction has placed"); player.sendMessage("§7-------------------------------------"); return; } if (args[1].equalsIgnoreCase("whycharge")) { player.sendMessage("§7-------------WHY CHARGE?-------------"); player.sendMessage("§7The charge (or power) your faction has is what"); player.sendMessage("§7protects it from harm by other players. To charge"); player.sendMessage("§7your faction hold an item, block, or stack in"); player.sendMessage("§7your hand and type §a/f charge§r. You can also see"); player.sendMessage("§7how much is will charge by holding it and typing"); player.sendMessage("§7the command §a/f chkcharge§r. When an explosion happens"); player.sendMessage("§7and it *would* damage your land for each block that"); player.sendMessage("§7would be destroyed an amount of faction power is"); player.sendMessage("§7deducted from your faction power. If you have no power"); player.sendMessage("§7left them the explosion will destroy the block. This"); player.sendMessage("§7is how you can be raided and how you can raid other"); player.sendMessage("§7factions. You must shoot or detonate TNT or nukes"); player.sendMessage("§7next to their land or shoot it into their land."); player.sendMessage("§7Also, power can be used to zap other factions which"); player.sendMessage("§7is a second way to siege someone's faction!"); player.sendMessage("§7-------------------------------------"); return; } if (args[1].equalsIgnoreCase("tut")) { player.sendMessage("§7---------------TUTORIAL--------------"); player.sendMessage("§7The first thing you need to do is create a faction"); player.sendMessage("§7with §a/f create MyName§r. Now, once you have created"); player.sendMessage("§7a faction you need to claim some land where you want"); player.sendMessage("§7to build your house. Find a spot and type §a/f seechunk§r."); player.sendMessage("§7The area enclosed in glass is the chunk that you would"); player.sendMessage("§7claim if you typed §a/f claim§r. You might have to claim"); player.sendMessage("§7multiple chunks to get the specific area you want."); player.sendMessage("§7Now, that you have claimed land you need to charge"); player.sendMessage("§7your faction power. To understand charging type the"); player.sendMessage("§7command §a/f help whycharge§r."); player.sendMessage("§7-------------------------------------"); return; } player.sendMessage(String.format("§7You specified help but the argument %s is not understood!", args[1])); return; } // no arguments / unknown command / help player.sendMessage("§7-------------------------------------"); player.sendMessage("§7Faction Help Main Menu"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§dhelp tut§r - short tutorial"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§dhelp chat§r - chat commands"); player.sendMessage("§dhelp basic§r - basic commands"); player.sendMessage("§ahelp ranks§r - ranking commands"); player.sendMessage("§ahelp blockrank§r - block rank commands"); player.sendMessage("§ahelp friends§r - friend commands"); player.sendMessage("§ahelp zap§r - zap commands"); player.sendMessage("§ahelp anchors§r - anchor commands"); player.sendMessage("§dhelp home§r - home commands"); player.sendMessage("§dhelp teleport§r - teleport commands"); player.sendMessage("§e/f c <message>§r - faction chat message"); player.sendMessage("§7-------------------------------------"); player.sendMessage("§7For example: §a/f help basic§r"); player.sendMessage("§7For example: §a/f help friends§r"); player.sendMessage("§7-------------------------------------"); } public void showPlayerChunk(Player player, boolean undo) { final int cx, cz; int tid; byte did; World world; int ly, hy; cx = player.getLocation().getBlockX() >> 4; cz = player.getLocation().getBlockZ() >> 4; ly = player.getLocation().getBlockY(); ly = ly - 5; hy = ly + 10; ly = ly < 0 ? 0 : ly; hy = hy > 255 ? 255 : hy; if (!undo) { // replace air with glass tid = 20; did = 0; } else { // replace glass back with air tid = 0; did = 0; } world = player.getWorld(); for (int i = -1; i < 17; ++i) { for (int y = ly; y < hy; ++y) { if (world.getBlockAt(cx * 16 + i, y, cz * 16 + 16).getTypeId() == 0) sendPlayerBlockChange(player, cx * 16 + i, y, cz * 16 + 16, tid, (byte)did); if (world.getBlockAt(cx * 16 + i, y, cz * 16 + -1).getTypeId() == 0) sendPlayerBlockChange(player, cx * 16 + i, y, cz * 16 + -1, tid, (byte)did); } } for (int i = -1; i < 17; ++i) { for (int y = ly; y < hy; ++y) { if (world.getBlockAt(cx * 16 + 16, y, cz * 16 + i).getTypeId() == 0) sendPlayerBlockChange(player, cx * 16 + 16, y, cz * 16 + i, tid, (byte)did); if (world.getBlockAt(cx * 16 + -1, y, cz * 16 + i).getTypeId() == 0) sendPlayerBlockChange(player, cx * 16 + -1, y, cz * 16 + i, tid, (byte)did); } } } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String cmd; final Player player; // MUST BE TYPED INTO THE CONSOLE if (!(sender instanceof Player)) { if (args.length < 1) { return true; } cmd = args[0]; if (cmd.equals("glitch1")) { Faction f; f = getFactionByName(args[1]); f.mrc = 700; f.mri = 600; return true; } if (command.getName().equals("resetwa")) { int x, y, z; Iterator<WorldAnchorLocation> i; WorldAnchorLocation wal; Faction f; String fn; String w; fn = args[0]; w = args[1]; x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); f = getFactionByName(fn); if (f == null) { getServer().getLogger().info("[f] Could not find faction"); return true; } i = f.walocs.iterator(); while (i.hasNext()) { wal = i.next(); if ((wal.x == x) && (wal.y == y) && (wal.z == z) && (wal.w.equals(w))) { getServer().getLogger().info("§7[f] World anchor removed from faction control. You may now place one more."); i.remove(); return true; } } getServer().getLogger().info("[f] Could not find world anchor."); return true; } if (cmd.equals("setgspawn")) { if (args.length < 1) { getServer().getLogger().info("§7[f] setgspawn needs one argument /f setgspawn <playername>"); return true; } Location l; File file; RandomAccessFile raf; if (getServer().getPlayer(args[1]) == null) { getServer().getLogger().info("§7[f] player does not exist"); return true; } l = getServer().getPlayer(args[1]).getLocation(); gspawn = l; getServer().getLogger().info("§7[f] set global respawn to location of player"); // ALSO WRITE OUT TO DISK FILE file = new File("plugin.gspawn.factions"); try { raf = new RandomAccessFile(file, "rw"); raf.writeUTF(l.getWorld().getName()); raf.writeDouble(l.getX()); raf.writeDouble(l.getY()); raf.writeDouble(l.getZ()); raf.close(); } catch (FileNotFoundException e) { return true; } catch (IOException e) { getServer().getLogger().info("§7[f] could not write gspawn to disk!"); return true; } return true; } if (cmd.equals("noboom")) { // f noboom <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] noboom needs one argument /f noboom <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NOBOOM) == NOBOOM) { f.flags = f.flags & ~NOBOOM; getServer().getLogger().info(String.format("§7[f] NOBOOM toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NOBOOM; getServer().getLogger().info(String.format("§7[f] NOBOOM toggled ON on %s", args[1])); return true; } if (cmd.equals("nopvp")) { // f nopvp <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] nopvp needs one argument /f nopvp <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NOPVP) == NOPVP) { f.flags = f.flags & ~NOPVP; getServer().getLogger().info(String.format("§7[f] NOPVP toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NOPVP; getServer().getLogger().info(String.format("§7[f] NOPVP toggled ON on %s", args[1])); return true; } if (cmd.equals("nodecay")) { // f nopvp <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] nodecay needs one argument /f nodecay <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NODECAY) == NODECAY) { f.flags = f.flags & ~NODECAY; getServer().getLogger().info(String.format("§7[f] NODECAY toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NODECAY; getServer().getLogger().info(String.format("§7[f] NODECAY toggled ON on %s", args[1])); return true; } if (cmd.equals("yank")) { // f yank <faction> <player> Faction f; if (args.length < 2) { getServer().getLogger().info("§7[f] yank needs two arguments /f yank <faction> <player>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if (!f.players.containsKey(args[2])) { getServer().getLogger().info(String.format("§7[f] faction %s has no player %s", args[1], args[2])); return true; } f.players.remove(args[2]); getServer().getLogger().info(String.format("§7[f] player %s was yanked from faction %s", args[2], args[1])); return true; } if (cmd.equals("stick")) { // f stick <faction> <player> FactionPlayer fp; Faction f; if (args.length < 2) { getServer().getLogger().info("§7[f] stick needs two arguments /stick <faction> <player>"); return true; } fp = getFactionPlayer(args[2]); if (fp != null) { fp.faction.players.remove(fp.name); } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } fp = new FactionPlayer(); fp.rank = 1000; fp.name = args[2]; fp.faction = f; f.players.put(args[2], fp); getServer().getLogger().info(String.format("§7[f] player %s was stick-ed in faction %s", args[2], args[1])); return true; } } if (!(sender instanceof Player)) return false; player = (Player)sender; // enforce world restrictions if (!worldsEnabled.contains(player.getWorld().getName())) { player.sendMessage("§7[f] This world has not been enabled for KFactions!"); return true; } if (command.getName().equals("home")) { player.sendMessage("§7[f] Use /f home (requires a faction)"); return true; } if (command.getName().equals("spawn")) { player.sendMessage("§7[f] Use /f spawn (requires a faction)"); return true; } if (args.length < 1) { if (sender instanceof Player) displayHelp((Player)sender, args); return false; } cmd = args[0]; //this.getServer().getPluginManager().getPlugins()[0]. //setmri, setmrc, setmrsp, setmrtp, //sethome, tptp if (cmd.equals("c")) { StringBuffer sb; FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } sb = new StringBuffer(); for (int x = 1; x < args.length; ++x) { sb.append(args[x]); sb.append(" "); } sendFactionMessage(fp.faction, String.format("§d[Faction]§r§e %s: %s", player.getDisplayName(), sb.toString())); return true; } if (cmd.equals("showanchors")) { Iterator<WorldAnchorLocation> i; WorldAnchorLocation wal; FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } player.sendMessage("§7[f] Showing Placed World Anchors"); i = fp.faction.walocs.iterator(); while (i.hasNext()) { wal = i.next(); player.sendMessage(String.format( " x:%d y:%d z:%d w:%s by:%s age:%d/days", wal.x, wal.y, wal.z, wal.w, wal.byWho, (System.currentTimeMillis() - wal.timePlaced) / 1000 / 60 / 60 / 24 )); } return true; } if (cmd.equals("scan")) { double chance; double Xmax, Xmin, Zmax, Zmin; int wndx, cndx, fndx; int realX, realZ; FactionPlayer fp; long ct; long sr; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } if (!enabledScanner) { player.sendMessage("§7[f] The scanner feature is not enabled on this server!"); return true; } ct = System.currentTimeMillis(); if (scannerWait.containsKey(fp.faction.name)) { sr = ct - scannerWait.get(fp.faction.name); if (sr < (1000 * scannerWaitTime)) { player.sendMessage(String.format( "§7[f] You need to wait %d more seconds!", ((1000 * scannerWaitTime) - sr) / 1000 )); return true; } } // scan all factions and all land claims to build minimum and maximum bounds fndx = (int)(Math.random() * factions.size()); realX = 0; realZ = 0; Xmax = 0; Zmax = 0; Xmin = 0; Zmin = 0; for (Faction f : factions.values()) { // pick random claim if any claim exists wndx = (int)(Math.random() * f.chunks.size()); for (String wn : f.chunks.keySet()) { cndx = (int)(Math.random() * f.chunks.get(wn).size()); for (FactionChunk fc : f.chunks.get(wn).values()) { if (cndx == 0 && wndx == 0 && fndx == 0) { realX = fc.x * 16; realZ = fc.z * 16; } Xmax = Xmax == 0 || fc.x > Xmax ? fc.x : Xmax; Zmax = Zmax == 0 || fc.z > Zmax ? fc.z : Zmax; Xmin = Xmin == 0 || fc.x < Xmin ? fc.x : Xmin; Zmin = Zmin == 0 || fc.z < Zmin ? fc.z : Zmin; --cndx; } --wndx; } --fndx; } if (Math.random() > scannerChance) { Xmax = Xmax * 16; Xmin = Xmin * 16; Zmax = Zmax * 16; Zmin = Zmin * 16; realX = (int)(Math.random() * (double)(Xmax - Xmin) + (double)Xmin); realZ = (int)(Math.random() * (double)(Zmax - Zmin) + (double)Zmin); realX = (realX >> 4) << 4; realZ = (realZ >> 4) << 4; } scannerWait.put(fp.faction.name, ct); sendFactionMessage(fp.faction, String.format( "§7 The world anomally scanner result is §a%d:%d§r.", realX, realZ )); return true; } if (cmd.equals("curank") || cmd.equals("cbrank")) { FactionPlayer fp; FactionChunk fc; Location loc; int bx, bz; int irank; loc = player.getLocation(); fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } bx = loc.getBlockX() >> 4; bz = loc.getBlockZ() >> 4; fc = getFactionChunk(player.getWorld(), bx, bz); if (fc == null) { player.sendMessage("§7[f] §7Land not claimed by anyone."); return true; } if ((fc.faction != fp.faction) && (!player.isOp())) { player.sendMessage("§7[f] §7Land not claimed by your faction."); return true; } if ((fc.mrb >= fp.rank) && (!player.isOp())) { player.sendMessage("§7[f] §7Land rank is equal or greater than yours."); return true; } if (args.length < 2) { player.sendMessage("§7[f] §7The syntax is /f curank <value> OR /f cbrank <value>"); return true; } irank = Integer.valueOf(args[1]); if ((irank >= fp.rank) && (!player.isOp())) { player.sendMessage("§7[f] §7Your rank is too low."); return true; } if (cmd.equals("curank")) { fc.mru = irank; } else { fc.mrb = irank; } player.sendMessage("§7[f] §7The rank was set. Use /f inspect to check."); return true; } if (cmd.equals("sethome")) { FactionPlayer fp; FactionChunk fc; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } fc = getFactionChunk(player.getWorld(), player.getLocation().getBlockX() >> 4, player.getLocation().getBlockZ() >> 4); if (fc == null) { player.sendMessage("§7[f] Must be on faction land."); return true; } if (fc.faction != fp.faction) { player.sendMessage("§7[f] Must be on your faction land."); return true; } if (fp.rank < fp.faction.mrsh) { player.sendMessage("§7[f] Your rank is too low."); return true; } fp.faction.hx = player.getLocation().getX(); fp.faction.hy = player.getLocation().getY(); fp.faction.hz = player.getLocation().getZ(); fp.faction.hw = player.getLocation().getWorld().getName(); player.sendMessage("§7[f] Faction home set."); return true; } if (cmd.equals("tptp") || cmd.equals("home") || cmd.equals("spawn")) { FactionPlayer fp; if (cmd.equals("spawn")) { args = new String[3]; args[1] = player.getName(); args[2] = "spawn"; } if (cmd.equals("home")) { args = new String[3]; args[1] = player.getName(); args[2] = "home"; } fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrtp) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 3) { player.sendMessage("§7[f] Use syntax /f tptp <player> <player/home>"); return true; } FactionPlayer src; FactionPlayer dst; src = getFactionPlayer(args[1]); dst = getFactionPlayer(args[2]); if (src == null) { player.sendMessage("§7[f] Source player does not exist."); return true; } if (src.rank > fp.rank) { player.sendMessage(String.format("§7[f] The player %s is higher in rank than you. Ask him.", args[2])); return true; } if (dst == null) { if (!args[2].equals("home") && !args[2].equals("spawn")) { player.sendMessage("§7[f] Source player does not exist, or use word $home."); return true; } } else { if (dst.rank > fp.rank) { player.sendMessage(String.format("§7[f] The player %s is higher in rank than you. Ask him.", args[3])); return true; } } Location loc; if (dst != null) { if ((src.faction != dst.faction) || (src.faction != fp.faction)) { player.sendMessage("§7[f] Everyone has to be in the same faction."); return true; } loc = getServer().getPlayer(args[2]).getLocation(); if (getServer().getPlayer(args[1]) != null) { getServer().getPlayer(args[1]).teleport(loc); synchronized (fp.faction) { fp.faction.power = fp.faction.power - (fp.faction.power * 0.1); } } else { player.sendMessage(String.format("§7[f] The player %s was not found.", args[1])); } return true; } if ((src.faction != fp.faction)) { player.sendMessage("§7[f] Everyone has to be in the same faction."); return true; } // are we going home or to spawn? if (args[2].equals("spawn")) { loc = gspawn; if (gspawn == null) { player.sendMessage("§7[f] The spawn has not been set for factions!"); return true; } } else { // teleport them to home if (fp.faction.hw == null) { player.sendMessage("§7[f] The faction home is not set! Use /f sethome"); return true; } loc = new Location(getServer().getWorld(fp.faction.hw), fp.faction.hx, fp.faction.hy + 0.3, fp.faction.hz); } getServer().getPlayer(args[1]).teleport(loc); synchronized (fp.faction) { fp.faction.power = fp.faction.power - (fp.faction.power * 0.1); } return true; } if (cmd.equals("setmrsh")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrsh) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrsh <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrsh = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrtp")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrtp) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrtp <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrtp = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrz")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrz <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrz = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrc")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrc) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrc <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrc = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmri")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mri) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmri <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mri = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setzaprank")) { FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] Too few arguments. Use /f setzaprank <rank>"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] You are lower than the MRZ rank, so you can not change it."); return true; } fp.faction.mrz = Integer.parseInt(args[1]); return true; } if (cmd.equals("showzaps")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } f = fp.faction; synchronized (f) { double grandTotal; player.sendMessage("[§6f§r] [§6DIR§r ] [§6AMOUNT§r ] [§6FACTION§r]"); for (ZapEntry e : f.zappersOutgoing) { player.sendMessage(String.format(" §6OUT§r (%11f) §6%s", e.amount, e.to.name)); } grandTotal = 0; for (ZapEntry e : f.zappersIncoming) { player.sendMessage(String.format(" §6IN§r (%11f) §6%s", e.amount, e.from.name)); if (!e.isFake) grandTotal += e.amount; } player.sendMessage(String.format("TOTAL ZAP INCOMING: %f", grandTotal)); } return true; } if (cmd.equals("zap")) { FactionPlayer fp; Faction tf; Faction f; int amount; String target; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] You do not have enough rank to ZAP."); return true; } // <faction> <amount> if (args.length < 3) { player.sendMessage("§7[f] The syntax is /f zap <faction> <amount>"); return true; } target = args[1]; amount = Integer.parseInt(args[2]); if (amount <= 0) { player.sendMessage("The amount of zap must be greater then zero."); return true; } if (amount > fp.faction.power) { player.sendMessage(String.format("§7[f] You do not have %d in power to ZAP with.", amount)); return true; } tf = getFactionByName(target); if (tf == null) { player.sendMessage(String.format("§7[f] Faction could not be found by the name '%s'", target)); return true; } f = fp.faction; // make sure not more than 20 zaps are going this // is to prevent a DOS memory attack by flooding us with // thousands of entries Iterator<ZapEntry> i; int zapCnt; i = tf.zappersIncoming.iterator(); zapCnt = 0; while (i.hasNext()) { if (i.next().from == f) zapCnt++; } if (zapCnt > 20) { player.sendMessage("§7[f] You reached maximum number of active zaps [20]"); return true; } ZapEntry ze; ze = new ZapEntry(); // no longer will it create fake zaps // instead it will warn the player of // the problem and not allow them to // zap the target faction if (tf.power < f.power) { player.sendMessage("§7[f] That faction has less power than you! You can zap only if they have more than you."); return true; } ze.amount = (double)amount; ze.timeStart = System.currentTimeMillis(); ze.timeTick = ze.timeStart; ze.perTick = (double)amount / (1000.0d * 60.0d * 60.0d * 48.0d); if (ze.perTick <= 0.0d) { // ensure it will at least drain amount which // will result in the ZapEntry's removal ze.perTick = 1.0d; } ze.from = f; ze.to = tf; synchronized (f) { f.zappersOutgoing.add(ze); tf.zappersIncoming.add(ze); // go ahead and subtract what they spent f.power -= amount; } player.sendMessage("§7[f] Zap has commenced."); return true; } if (cmd.equals("create")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); args[1] = sanitizeString(args[1]); if (fp != null) { player.sendMessage("§7[f] You must leave your current faction to create a new faction."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the new faction name. /f create <faction-name>"); return true; } if (factions.containsKey(args[1].toLowerCase())) { player.sendMessage(String.format("§7[f] The faction name %s is already taken.", args[1])); return true; } f = new Faction(); f.name = args[1]; f.desc = "default description"; f.mrc = 700; f.mri = 600; fp = new FactionPlayer(); fp.faction = f; fp.name = player.getName(); fp.rank = 1000; f.players.put(player.getName(), fp); getServer().broadcastMessage(String.format("§7[f] %s created new faction %s!", player.getName(), args[1])); synchronized (factions) { factions.put(args[1].toLowerCase(), f); } return true; } if (cmd.startsWith("cbr")) { FactionPlayer fp; FactionChunk fc; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("§7[f] This land is not owned"); return true; } if (fc.faction != fp.faction) { player.sendMessage(String.format("§7[f] This land is owned by §c%s§7!", fp.faction.name)); return true; } if (cmd.equals("cbru")) { m = fc.tidu; } else { m = fc.tid; } player.sendMessage("§7[f] Clearing Block Ranks"); if (m != null) { Iterator<Entry<Integer, Integer>> i; Entry<Integer, Integer> e; i = m.entrySet().iterator(); while (i.hasNext()) { e = i.next(); if (e.getValue() >= fp.rank) { player.sendMessage(String.format("§7 Rank too low for to clear %s[%d] at rank %d!", TypeIdToNameMap.getNameFromTypeId(e.getKey()), e.getKey(), e.getValue())); } else { i.remove(); } } } return true; } if (cmd.startsWith("lbr")) { FactionPlayer fp; FactionChunk fc; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("§7[f] This land is not owned"); return true; } if (cmd.equals("lbru")) { player.sendMessage("§7[f] List §cInteraction§7 Block Rank For Claim"); m = fc.tidu; } else { player.sendMessage("§7[f] List §cPlace/Break§7 Block Rank For Claim"); m = fc.tid; } if (m != null) { Iterator<Entry<Integer, Integer>> i; Entry<Integer, Integer> e; i = m.entrySet().iterator(); while (i.hasNext()) { e = i.next(); player.sendMessage(String.format("§7For §c%s§7(§d%d§7) you need rank §c%d§7 or better.", TypeIdToNameMap.getNameFromTypeId(e.getKey()), e.getKey(), e.getValue())); } if (cmd.equals("lbru")) { player.sendMessage("§7Use §d/f cbru§7 (to clear) and §d/f bru§7 to add to the list."); } else { player.sendMessage("§7Use §d/f cbr§7 (to clear) and §d/f br§7 to add to the list."); } } return true; } if (cmd.equals("seechunk")) { long ct, dt; ct = System.currentTimeMillis(); if (seeChunkLast.get(player.getName()) != null) { dt = ct - seeChunkLast.get(player.getName()); if (dt < 10000) { player.sendMessage(String.format("§7You need to wait %d more seconds before you can use this command again!", 10 - (dt / 1000))); return true; } } seeChunkLast.put(player.getName(), ct); showPlayerChunk(player, false); getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { showPlayerChunk(player, true); } }, 20 * 10); player.sendMessage("§7[f] The current chunk now surrounded with glass where there was air!"); return true; } if (cmd.startsWith("br")) { FactionPlayer fp; FactionChunk fc; int typeId; byte typeData; int rank; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("This land is not claimed."); return true; } if (fc.faction != fp.faction) { player.sendMessage(String.format("§7[f] This land is owned by %s.", fc.faction.name)); return true; } if (args.length == 1) { player.sendMessage("§7[f] Either hold item in hand, or use /f blockrank <rank> <typeId> <dataId(optinal)>"); return true; } rank = Integer.parseInt(args[1]); if (rank >= fp.rank) { player.sendMessage("§7[f] You can not set a block rank equal or greater than your rank."); return true; } if (args.length > 2) { typeId = Integer.parseInt(args[2]); if (args.length < 4) { typeData = (byte)0; } else { typeData = (byte)Integer.parseInt(args[3]); } } else { if (player.getItemInHand().getTypeId() == 0) { if (cmd.equals("bru")) { player.sendMessage("§7[f] Either hold item in hand and use §c/f bru <rank>§7, or use §c/f br <rank> <typeId>§7"); } else { player.sendMessage("§7[f] Either hold item in hand and use §c/f br <rank>§7, or use §c/f br <rank> <typeId>§7"); } return true; } typeId = player.getItemInHand().getTypeId(); typeData = player.getItemInHand().getData().getData(); } if (cmd.equals("bru")) { if (fc.tidu == null) fc.tidu = new HashMap<Integer, Integer>(); m = fc.tidu; } else { if (fc.tid == null) fc.tid = new HashMap<Integer, Integer>(); m = fc.tid; } /// UPGRADE CODE BLOCK if (m.containsKey(typeId)) { if (m.get(typeId) >= fp.rank) { player.sendMessage(String.format("§7[f] Block rank exists for §a%s[%d]§r and is equal or higher than your rank §b%d§r.", TypeIdToNameMap.getNameFromTypeId(typeId), fc.tid.get(typeId), fp.rank)); return true; } } m.put(typeId, rank); player.sendMessage(String.format("§7[f] Block §a%s§r[%d] at rank §a%d§r added to current claim.", TypeIdToNameMap.getNameFromTypeId(typeId), typeId, rank)); return true; } if (cmd.equals("invite")) { FactionPlayer fp; Player p; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the name of whom to invite! /f invite <player-name>"); return true; } if (fp.rank < fp.faction.mri) { player.sendMessage(String.format("§7[f] Your rank is %d but needs to be %d.", fp.rank, fp.faction.mri)); return true; } p = getServer().getPlayer(args[1]); if (p == null) { player.sendMessage("§7[f] The player must be online to invite them."); return true; } fp.faction.invites.add(args[1].toLowerCase()); sendFactionMessage(fp.faction, String.format("§7[f] %s has been invited to your faction", args[1])); if (p != null) { p.sendMessage(String.format("§7[f] You have been invited to %s by %s. Use /f join %s to join!", fp.faction.name, fp.name, fp.faction.name)); } return true; } if (cmd.equals("kick")) { FactionPlayer fp; FactionPlayer _fp; fp = getFactionPlayer(player.getName()); if (fp.rank < fp.faction.mri) { player.sendMessage("§7[f] Your rank is too low to invite or kick."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the player name. /f kick <player-name>"); return true; } _fp = getFactionPlayer(args[1]); if (_fp == null) { player.sendMessage("§7[f] Player specified is not in a faction or does not exist."); return true; } if (_fp.faction != fp.faction) { player.sendMessage(String.format("§7[f] Player is in faction %s and you are in faction %s.", _fp.faction.name, fp.faction.name)); return true; } if (_fp.rank >= fp.rank) { player.sendMessage(String.format("§7[f] Player %s at rank %d is equal or higher than your rank of %d", _fp.name, _fp.rank, fp.rank)); return true; } fp.faction.players.remove(_fp.name); getServer().broadcastMessage(String.format("§7[f] %s was kicked from faction %s by %s", _fp.name, fp.faction.name, fp.name)); return true; } if (cmd.equals("join")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); if (fp != null) { player.sendMessage("§7[f] You must leave you current faction to join another one."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the faction to join. /f join <faction-name>"); return true; } f = getFactionByName(args[1]); if (f == null) { player.sendMessage("§7[f] No faction found by that name."); return true; } // FIX FOR OLDER VER CLASS if (f.invites == null) f.invites = new HashSet<String>(); Iterator<String> i; i = f.invites.iterator(); while (i.hasNext()) { if (i.next().toLowerCase().equals(player.getName().toLowerCase())) { f.invites.remove(player.getName()); fp = new FactionPlayer(); fp.faction = f; fp.name = player.getName(); fp.rank = 0; f.players.put(player.getName(), fp); getServer().broadcastMessage(String.format("§7[f] %s just joined the faction [%s].", fp.name, f.name)); return true; } } player.sendMessage("You have no invintation to join that faction!"); return true; } if (cmd.equals("leave")) { FactionPlayer fp; FactionChunk fchunk; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } /// MAKE SURE WE ARE NOT STANDING ON FACTION CLAIMED LAND fchunk = getFactionChunk(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockZ()); if (fchunk != null) { if (fchunk.faction == fp.faction) { player.sendMessage("§7[f] You must not be on your faction land when leaving the faction."); return true; } } /// MAKE SURE NOT EMPTY IF SO NEED TO USE DISBAND /// IF WE ARE OWNER WE NEED TO TRANSFER OWNERSHIP BEFORE WE LEAVE if (fp.faction.players.size() == 1) { // ENSURE THEY ARE HIGH ENOUGH FOR OWNER (CATCH BUGS KINDA) fp.rank = 1000; player.sendMessage("§7[f] You are the last player in faction use /f disband."); return true; } // IF THEY ARE THE OWNER HAND OWNERSHIP TO SOMEBODY ELSE KINDA AT RANDOM if (fp.rank == 1000) { Iterator<Entry<String, FactionPlayer>> i; FactionPlayer _fp; i = fp.faction.players.entrySet().iterator(); _fp = null; while (i.hasNext()) { _fp = i.next().getValue(); if (!fp.name.equals(_fp.name)) break; } _fp.rank = 1000; getServer().broadcastMessage(String.format("§7[f] Ownership of %s was handed to %s at random.", fp.faction.name, fp.name)); } getServer().broadcastMessage(String.format("§7[f] §a%s§r has left the faction §a%s§r!", fp.name, fp.faction.name)); fp.faction.players.remove(fp.name); return true; } if (cmd.equals("disband")) { FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // MUST BE OWNER OF FACTION if (fp.rank < 1000) { player.sendMessage("§7[f] You are not owner of faction."); return true; } // why the hell am i doing this? --kmcguire fp.faction.chunks = new HashMap<String, Map<Long, FactionChunk>>(); getServer().broadcastMessage(String.format("§7[f] §a%s§r has disbanded the faction §a%s§r!", fp.name, fp.faction.name)); factions.remove(fp.faction.name.toLowerCase()); return true; } if (cmd.equals("listfriends")) { String friendName; Faction f; FactionPlayer fp; int frank; Iterator<Entry<String, Integer>> i; Entry<String, Integer> e; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.faction.friends == null) { player.sendMessage("§7[f] Faction has no friends."); return true; } i = fp.faction.friends.entrySet().iterator(); while (i.hasNext()) { e = i.next(); player.sendMessage(String.format("§7[f] %s => %d", e.getKey(), e.getValue())); } player.sendMessage("§7[f] Done"); return true; } if (cmd.equals("addfriend")) { String friendName; Faction f; FactionPlayer fp; int frank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (args.length < 3) { player.sendMessage("Syntax is /f addfriend <name> <rank>. Use again to change rank. Use /f remfriend to remove."); return true; } friendName = args[1]; frank = Integer.parseInt(args[2]); if (frank >= fp.rank) { player.sendMessage(String.format("§7[f] You can not set friend rank of %d because it is higher than your rank of %d.", frank, fp.rank)); return true; } if (fp.faction.friends == null) fp.faction.friends = new HashMap<String, Integer>(); fp.faction.friends.put(friendName, frank); sendFactionMessage(fp.faction, String.format("§7[f] Added friend %s at rank %d\n", friendName, frank)); return true; } if (cmd.equals("remfriend")) { String friendName; Faction f; FactionPlayer fp; int frank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (args.length < 2) { player.sendMessage("Syntax is /f remfriend <name>."); return true; } friendName = args[1]; if (fp.faction.friends == null) fp.faction.friends = new HashMap<String, Integer>(); if (fp.faction.friends.containsKey(friendName)) { frank = fp.faction.friends.get(friendName); if (frank >= fp.rank) { player.sendMessage(String.format("§7[f] You can not remove friend with rank of %d because it is higher than your rank of %d.", frank, fp.rank)); return true; } } fp.faction.friends.remove(friendName); sendFactionMessage(fp.faction, String.format("§7[f] Removed friend %s\n", friendName)); return true; } if (cmd.equals("rename")) { FactionPlayer fp; String newName; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.rank < 1000) { player.sendMessage("§7[f] You need to be owner of this faction to change the rank!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] The syntax is /f rename <newname>."); return true; } newName = args[1]; newName = sanitizeString(newName); if (newName.length() < 1) { player.sendMessage("§7[f] The name length is zero!"); return true; } getServer().broadcastMessage(String.format("§7[f] The faction §a%s§7 was renamed to §a%s§7.", fp.faction.name, newName)); synchronized (factions) { factions.remove(fp.faction.name.toLowerCase()); fp.faction.name = newName; factions.put(fp.faction.name.toLowerCase(), fp.faction); } return true; } if (cmd.equals("claim")) { FactionPlayer fp; int x, z; FactionChunk fchunk; double pow; if (player == null) { player.sendMessage("§7[f] uhoh plyer is null"); return true; } fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } // DO WE HAVE ENOUGH POWER? // NEED ENOUGH TO HOLD FOR 24 HOURS //pow = getFactionPower(fp.faction); //if (pow < ((fp.faction.chunks.size() + 1) * 24.0)) { // player.sendMessage("§7[f] The faction lacks needed power to claim land"); // return true; //} //smsg(String.format("blockx:%d", player.getLocation().getBlockX())); x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fchunk = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fchunk != null) { if (fchunk.faction == fp.faction) { player.sendMessage(String.format("§7[f] chunk already owned by your faction %s", fchunk.faction.name)); return true; } if (noGriefPerWorld.contains(player.getWorld().getName())) { player.sendMessage("§7[f] This world does not allow claiming of another faction's land!"); return true; } if (fchunk.faction != fp.faction) { if (getFactionPower(fchunk.faction) >= fchunk.faction.chunks.size()) { player.sendMessage(String.format("§7[f] faction %s has enough power to hold this claim", fchunk.faction.name)); return true; } getServer().broadcastMessage(String.format("§7[f] %s lost land claim to %s by %s", fchunk.faction.name, fp.faction.name, fp.name)); fchunk.faction.chunks.remove(getChunkLong(player.getWorld(), x >> 4, z >> 4)); } } fchunk = new FactionChunk(); fchunk.x = x >> 4; fchunk.z = z >> 4; fchunk.worldName = player.getWorld().getName(); fchunk.faction = fp.faction; fchunk.mrb = 500; // DEFAULT VALUES fchunk.mru = 250; fchunk.faction = fp.faction; if (fp.faction.chunks.get(player.getWorld().getName()) == null) { fp.faction.chunks.put(player.getWorld().getName(), new HashMap<Long, FactionChunk>()); } fp.faction.chunks.get(player.getWorld().getName()).put(LongHash.toLong(x >> 4, z >> 4), fchunk); //fp.faction.chunks.put(getChunkLong(player.getWorld(), x >> 4, z >> 4), fchunk); getServer().broadcastMessage(String.format("§7[f] %s of faction %s claimed land", fp.name, fp.faction.name)); return true; } if (cmd.equals("setrank")) { FactionPlayer fp; FactionPlayer mp; int nrank; if (args.length < 2) { player.sendMessage("§7[f] Not enough arguments /f rank <player> <rank>"); return true; } fp = getFactionPlayer(args[1]); mp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] Player is not in a faction."); return true; } if (mp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.faction != mp.faction) { player.sendMessage("§7[f] You and player are not in the same faction."); } if ((fp.rank >= mp.rank) && (!player.isOp())) { player.sendMessage("§7[f] Player is already at equal or greater rank than you."); return true; } nrank = Integer.valueOf(args[2]); if ((nrank >= mp.rank) && (!player.isOp())) { player.sendMessage("§7[f] Rank you wish to set is equal or greater than you rank. [rejected]"); return true; } fp.rank = nrank; player.sendMessage(String.format("§7[f] rank for %s is now %d", args[1], nrank)); return true; } if (cmd.equals("unclaim")) { FactionPlayer fp; FactionChunk fchunk; int x, z; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } x = player.getLocation().getBlockX() >> 4; z = player.getLocation().getBlockZ() >> 4; fchunk = getFactionChunk(player.getWorld(), x, z); if (fchunk == null) { player.sendMessage("§7[f] This land chunk is owned by no one."); return true; } if (fchunk.faction != fp.faction) { player.sendMessage(String.format("§7[f] Your faction is %s, but this land belongs to %s.", fp.faction.name, fchunk.faction.name)); return true; } - fp.faction.chunks.remove(getChunkLong(player.getWorld(), x, z)); + fp.faction.chunks.get(player.getWorld().getName()).remove(LongHash.toLong(x, z)); // UPDATE FACTION POWER getFactionPower(fp.faction); getServer().broadcastMessage(String.format("§7[f] %s of faction %s unclaimed land", fp.name, fp.faction.name)); return true; } if (cmd.equals("unclaimall")) { FactionPlayer fp; Iterator<Entry<Long, FactionChunk>> i; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } fp.faction.chunks = new HashMap<String, Map<Long, FactionChunk>>(); getServer().broadcastMessage(String.format("§7[f] %s of faction %s declaimed all land", fp.name, fp.faction.name)); return true; } if (cmd.equals("chkcharge")) { int icnt; int mid; byte dat; double pts; icnt = player.getItemInHand().getAmount(); mid = player.getItemInHand().getTypeId(); dat = player.getItemInHand().getData().getData(); pts = (double)getEMC(mid, dat); player.sendMessage(String.format("§7[f] %f/item total:%f", pts, pts * icnt)); return true; } if (cmd.equals("charge")) { FactionPlayer fp; int icnt; double pts; int mid; byte dat; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } icnt = player.getItemInHand().getAmount(); mid = player.getItemInHand().getTypeId(); dat = player.getItemInHand().getData().getData(); //pts = (double)EEMaps.getEMC(mid, dat); pts = (double)getEMC(mid, dat); player.sendMessage(String.format("§7[f] Item value is %f", pts)); pts = pts * icnt; if (pts == 0.0d) { player.sendMessage("§7[f] Item(s) in hand yield no charge value."); return true; } player.setItemInHand(null); synchronized (fp.faction) { fp.faction.power += pts; } //getServer().broadcastMessage(String.format("§7[f] %s in %s charged faction power!", player.getDisplayName(), fp.faction.name)); sendFactionMessage(fp.faction, String.format("§7[f] %s charged the faction power by %f to %f.", player.getDisplayName(), pts, getFactionPower(fp.faction))); return true; } // SHOW FACTION INFORMATION ABOUT OUR FACTION // OR ANOTHER FACTION SPECIFIED if (cmd.equalsIgnoreCase("who")) { FactionPlayer fp; Faction f; Iterator<Entry<String, FactionPlayer>> iter; Entry<String, FactionPlayer> e; String o; fp = getFactionPlayer(player.getName()); if (args.length < 2 && fp == null) { player.sendMessage("§7[f] You must either specify a faction or be in a faction!"); return true; } if (args.length == 2) { f = getFactionByName(args[1]); if (f == null) { fp = getFactionPlayer(args[1]); if (fp == null) { player.sendMessage(String.format("§7[f] Could not find a faction or player named '%s'!", args[1])); return true; } f = fp.faction; } } else { f = fp.faction; } if (f == null) { player.sendMessage(String.format("§7[f] The faction %s could not be found.", args[1])); return true; } // display name and description player.sendMessage(String.format("§6Faction: §7%s", f.name)); //player.sendMessage(String.format("Description: %s", f.desc)); // display land/power/maxpower if (fp != null) { player.sendMessage(String.format("§6Land: §7%d §6Power/Hour: §7%d §6Power: §7%d", f.chunks.size(), (int)(landPowerCostPerHour * f.chunks.size()), (int)getFactionPower(f) )); player.sendMessage(String.format("§6TimeLeft: §7%d hours", (int)(getFactionPower(f) / (landPowerCostPerHour * f.chunks.size())) )); } else { player.sendMessage(String.format("§6Land: §7%d", f.chunks.size() )); } // mri, mrc, flags, mrz, mrtp, mrsh player.sendMessage(String.format( "§6MRI:§7%d §6MRC:§7%d §6FLAGS:§7%d §6MRZ:§7%d §6MRTP:§7%d §6MRSH:§7%d", f.mri, f.mrc, f.flags, (int)f.mrz, (int)f.mrtp, f.mrsh )); iter = f.players.entrySet().iterator(); o = "§6Members:§r"; while (iter.hasNext()) { e = iter.next(); if (getServer().getPlayer(e.getKey()) != null) { o = String.format("%s, §6%s§7[%d]", o, e.getKey(), e.getValue().rank); } else { o = String.format("%s, §7%s§7[%d]", o, e.getKey(), e.getValue().rank); } } player.sendMessage(o); return true; } if (cmd.equals("inspect")) { Location loc; FactionChunk fc; int bx, bz; loc = player.getLocation(); bx = loc.getBlockX() >> 4; bz = loc.getBlockZ() >> 4; fc = getFactionChunk(player.getWorld(), bx, bz); if (fc == null) { player.sendMessage("§7[f] §7Land not claimed by anyone."); return true; } player.sendMessage(String.format("§6Faction:§r%s §6MinimumBuildRank:§r%d §6MinimumUseRank:§r%d", fc.faction.name, fc.mrb, fc.mru)); return true; } displayHelp(player, args); return false; } protected void smsg(String msg) { this.getLogger().info(msg); } }
true
true
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String cmd; final Player player; // MUST BE TYPED INTO THE CONSOLE if (!(sender instanceof Player)) { if (args.length < 1) { return true; } cmd = args[0]; if (cmd.equals("glitch1")) { Faction f; f = getFactionByName(args[1]); f.mrc = 700; f.mri = 600; return true; } if (command.getName().equals("resetwa")) { int x, y, z; Iterator<WorldAnchorLocation> i; WorldAnchorLocation wal; Faction f; String fn; String w; fn = args[0]; w = args[1]; x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); f = getFactionByName(fn); if (f == null) { getServer().getLogger().info("[f] Could not find faction"); return true; } i = f.walocs.iterator(); while (i.hasNext()) { wal = i.next(); if ((wal.x == x) && (wal.y == y) && (wal.z == z) && (wal.w.equals(w))) { getServer().getLogger().info("§7[f] World anchor removed from faction control. You may now place one more."); i.remove(); return true; } } getServer().getLogger().info("[f] Could not find world anchor."); return true; } if (cmd.equals("setgspawn")) { if (args.length < 1) { getServer().getLogger().info("§7[f] setgspawn needs one argument /f setgspawn <playername>"); return true; } Location l; File file; RandomAccessFile raf; if (getServer().getPlayer(args[1]) == null) { getServer().getLogger().info("§7[f] player does not exist"); return true; } l = getServer().getPlayer(args[1]).getLocation(); gspawn = l; getServer().getLogger().info("§7[f] set global respawn to location of player"); // ALSO WRITE OUT TO DISK FILE file = new File("plugin.gspawn.factions"); try { raf = new RandomAccessFile(file, "rw"); raf.writeUTF(l.getWorld().getName()); raf.writeDouble(l.getX()); raf.writeDouble(l.getY()); raf.writeDouble(l.getZ()); raf.close(); } catch (FileNotFoundException e) { return true; } catch (IOException e) { getServer().getLogger().info("§7[f] could not write gspawn to disk!"); return true; } return true; } if (cmd.equals("noboom")) { // f noboom <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] noboom needs one argument /f noboom <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NOBOOM) == NOBOOM) { f.flags = f.flags & ~NOBOOM; getServer().getLogger().info(String.format("§7[f] NOBOOM toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NOBOOM; getServer().getLogger().info(String.format("§7[f] NOBOOM toggled ON on %s", args[1])); return true; } if (cmd.equals("nopvp")) { // f nopvp <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] nopvp needs one argument /f nopvp <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NOPVP) == NOPVP) { f.flags = f.flags & ~NOPVP; getServer().getLogger().info(String.format("§7[f] NOPVP toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NOPVP; getServer().getLogger().info(String.format("§7[f] NOPVP toggled ON on %s", args[1])); return true; } if (cmd.equals("nodecay")) { // f nopvp <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] nodecay needs one argument /f nodecay <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NODECAY) == NODECAY) { f.flags = f.flags & ~NODECAY; getServer().getLogger().info(String.format("§7[f] NODECAY toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NODECAY; getServer().getLogger().info(String.format("§7[f] NODECAY toggled ON on %s", args[1])); return true; } if (cmd.equals("yank")) { // f yank <faction> <player> Faction f; if (args.length < 2) { getServer().getLogger().info("§7[f] yank needs two arguments /f yank <faction> <player>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if (!f.players.containsKey(args[2])) { getServer().getLogger().info(String.format("§7[f] faction %s has no player %s", args[1], args[2])); return true; } f.players.remove(args[2]); getServer().getLogger().info(String.format("§7[f] player %s was yanked from faction %s", args[2], args[1])); return true; } if (cmd.equals("stick")) { // f stick <faction> <player> FactionPlayer fp; Faction f; if (args.length < 2) { getServer().getLogger().info("§7[f] stick needs two arguments /stick <faction> <player>"); return true; } fp = getFactionPlayer(args[2]); if (fp != null) { fp.faction.players.remove(fp.name); } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } fp = new FactionPlayer(); fp.rank = 1000; fp.name = args[2]; fp.faction = f; f.players.put(args[2], fp); getServer().getLogger().info(String.format("§7[f] player %s was stick-ed in faction %s", args[2], args[1])); return true; } } if (!(sender instanceof Player)) return false; player = (Player)sender; // enforce world restrictions if (!worldsEnabled.contains(player.getWorld().getName())) { player.sendMessage("§7[f] This world has not been enabled for KFactions!"); return true; } if (command.getName().equals("home")) { player.sendMessage("§7[f] Use /f home (requires a faction)"); return true; } if (command.getName().equals("spawn")) { player.sendMessage("§7[f] Use /f spawn (requires a faction)"); return true; } if (args.length < 1) { if (sender instanceof Player) displayHelp((Player)sender, args); return false; } cmd = args[0]; //this.getServer().getPluginManager().getPlugins()[0]. //setmri, setmrc, setmrsp, setmrtp, //sethome, tptp if (cmd.equals("c")) { StringBuffer sb; FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } sb = new StringBuffer(); for (int x = 1; x < args.length; ++x) { sb.append(args[x]); sb.append(" "); } sendFactionMessage(fp.faction, String.format("§d[Faction]§r§e %s: %s", player.getDisplayName(), sb.toString())); return true; } if (cmd.equals("showanchors")) { Iterator<WorldAnchorLocation> i; WorldAnchorLocation wal; FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } player.sendMessage("§7[f] Showing Placed World Anchors"); i = fp.faction.walocs.iterator(); while (i.hasNext()) { wal = i.next(); player.sendMessage(String.format( " x:%d y:%d z:%d w:%s by:%s age:%d/days", wal.x, wal.y, wal.z, wal.w, wal.byWho, (System.currentTimeMillis() - wal.timePlaced) / 1000 / 60 / 60 / 24 )); } return true; } if (cmd.equals("scan")) { double chance; double Xmax, Xmin, Zmax, Zmin; int wndx, cndx, fndx; int realX, realZ; FactionPlayer fp; long ct; long sr; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } if (!enabledScanner) { player.sendMessage("§7[f] The scanner feature is not enabled on this server!"); return true; } ct = System.currentTimeMillis(); if (scannerWait.containsKey(fp.faction.name)) { sr = ct - scannerWait.get(fp.faction.name); if (sr < (1000 * scannerWaitTime)) { player.sendMessage(String.format( "§7[f] You need to wait %d more seconds!", ((1000 * scannerWaitTime) - sr) / 1000 )); return true; } } // scan all factions and all land claims to build minimum and maximum bounds fndx = (int)(Math.random() * factions.size()); realX = 0; realZ = 0; Xmax = 0; Zmax = 0; Xmin = 0; Zmin = 0; for (Faction f : factions.values()) { // pick random claim if any claim exists wndx = (int)(Math.random() * f.chunks.size()); for (String wn : f.chunks.keySet()) { cndx = (int)(Math.random() * f.chunks.get(wn).size()); for (FactionChunk fc : f.chunks.get(wn).values()) { if (cndx == 0 && wndx == 0 && fndx == 0) { realX = fc.x * 16; realZ = fc.z * 16; } Xmax = Xmax == 0 || fc.x > Xmax ? fc.x : Xmax; Zmax = Zmax == 0 || fc.z > Zmax ? fc.z : Zmax; Xmin = Xmin == 0 || fc.x < Xmin ? fc.x : Xmin; Zmin = Zmin == 0 || fc.z < Zmin ? fc.z : Zmin; --cndx; } --wndx; } --fndx; } if (Math.random() > scannerChance) { Xmax = Xmax * 16; Xmin = Xmin * 16; Zmax = Zmax * 16; Zmin = Zmin * 16; realX = (int)(Math.random() * (double)(Xmax - Xmin) + (double)Xmin); realZ = (int)(Math.random() * (double)(Zmax - Zmin) + (double)Zmin); realX = (realX >> 4) << 4; realZ = (realZ >> 4) << 4; } scannerWait.put(fp.faction.name, ct); sendFactionMessage(fp.faction, String.format( "§7 The world anomally scanner result is §a%d:%d§r.", realX, realZ )); return true; } if (cmd.equals("curank") || cmd.equals("cbrank")) { FactionPlayer fp; FactionChunk fc; Location loc; int bx, bz; int irank; loc = player.getLocation(); fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } bx = loc.getBlockX() >> 4; bz = loc.getBlockZ() >> 4; fc = getFactionChunk(player.getWorld(), bx, bz); if (fc == null) { player.sendMessage("§7[f] §7Land not claimed by anyone."); return true; } if ((fc.faction != fp.faction) && (!player.isOp())) { player.sendMessage("§7[f] §7Land not claimed by your faction."); return true; } if ((fc.mrb >= fp.rank) && (!player.isOp())) { player.sendMessage("§7[f] §7Land rank is equal or greater than yours."); return true; } if (args.length < 2) { player.sendMessage("§7[f] §7The syntax is /f curank <value> OR /f cbrank <value>"); return true; } irank = Integer.valueOf(args[1]); if ((irank >= fp.rank) && (!player.isOp())) { player.sendMessage("§7[f] §7Your rank is too low."); return true; } if (cmd.equals("curank")) { fc.mru = irank; } else { fc.mrb = irank; } player.sendMessage("§7[f] §7The rank was set. Use /f inspect to check."); return true; } if (cmd.equals("sethome")) { FactionPlayer fp; FactionChunk fc; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } fc = getFactionChunk(player.getWorld(), player.getLocation().getBlockX() >> 4, player.getLocation().getBlockZ() >> 4); if (fc == null) { player.sendMessage("§7[f] Must be on faction land."); return true; } if (fc.faction != fp.faction) { player.sendMessage("§7[f] Must be on your faction land."); return true; } if (fp.rank < fp.faction.mrsh) { player.sendMessage("§7[f] Your rank is too low."); return true; } fp.faction.hx = player.getLocation().getX(); fp.faction.hy = player.getLocation().getY(); fp.faction.hz = player.getLocation().getZ(); fp.faction.hw = player.getLocation().getWorld().getName(); player.sendMessage("§7[f] Faction home set."); return true; } if (cmd.equals("tptp") || cmd.equals("home") || cmd.equals("spawn")) { FactionPlayer fp; if (cmd.equals("spawn")) { args = new String[3]; args[1] = player.getName(); args[2] = "spawn"; } if (cmd.equals("home")) { args = new String[3]; args[1] = player.getName(); args[2] = "home"; } fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrtp) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 3) { player.sendMessage("§7[f] Use syntax /f tptp <player> <player/home>"); return true; } FactionPlayer src; FactionPlayer dst; src = getFactionPlayer(args[1]); dst = getFactionPlayer(args[2]); if (src == null) { player.sendMessage("§7[f] Source player does not exist."); return true; } if (src.rank > fp.rank) { player.sendMessage(String.format("§7[f] The player %s is higher in rank than you. Ask him.", args[2])); return true; } if (dst == null) { if (!args[2].equals("home") && !args[2].equals("spawn")) { player.sendMessage("§7[f] Source player does not exist, or use word $home."); return true; } } else { if (dst.rank > fp.rank) { player.sendMessage(String.format("§7[f] The player %s is higher in rank than you. Ask him.", args[3])); return true; } } Location loc; if (dst != null) { if ((src.faction != dst.faction) || (src.faction != fp.faction)) { player.sendMessage("§7[f] Everyone has to be in the same faction."); return true; } loc = getServer().getPlayer(args[2]).getLocation(); if (getServer().getPlayer(args[1]) != null) { getServer().getPlayer(args[1]).teleport(loc); synchronized (fp.faction) { fp.faction.power = fp.faction.power - (fp.faction.power * 0.1); } } else { player.sendMessage(String.format("§7[f] The player %s was not found.", args[1])); } return true; } if ((src.faction != fp.faction)) { player.sendMessage("§7[f] Everyone has to be in the same faction."); return true; } // are we going home or to spawn? if (args[2].equals("spawn")) { loc = gspawn; if (gspawn == null) { player.sendMessage("§7[f] The spawn has not been set for factions!"); return true; } } else { // teleport them to home if (fp.faction.hw == null) { player.sendMessage("§7[f] The faction home is not set! Use /f sethome"); return true; } loc = new Location(getServer().getWorld(fp.faction.hw), fp.faction.hx, fp.faction.hy + 0.3, fp.faction.hz); } getServer().getPlayer(args[1]).teleport(loc); synchronized (fp.faction) { fp.faction.power = fp.faction.power - (fp.faction.power * 0.1); } return true; } if (cmd.equals("setmrsh")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrsh) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrsh <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrsh = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrtp")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrtp) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrtp <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrtp = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrz")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrz <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrz = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrc")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrc) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrc <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrc = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmri")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mri) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmri <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mri = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setzaprank")) { FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] Too few arguments. Use /f setzaprank <rank>"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] You are lower than the MRZ rank, so you can not change it."); return true; } fp.faction.mrz = Integer.parseInt(args[1]); return true; } if (cmd.equals("showzaps")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } f = fp.faction; synchronized (f) { double grandTotal; player.sendMessage("[§6f§r] [§6DIR§r ] [§6AMOUNT§r ] [§6FACTION§r]"); for (ZapEntry e : f.zappersOutgoing) { player.sendMessage(String.format(" §6OUT§r (%11f) §6%s", e.amount, e.to.name)); } grandTotal = 0; for (ZapEntry e : f.zappersIncoming) { player.sendMessage(String.format(" §6IN§r (%11f) §6%s", e.amount, e.from.name)); if (!e.isFake) grandTotal += e.amount; } player.sendMessage(String.format("TOTAL ZAP INCOMING: %f", grandTotal)); } return true; } if (cmd.equals("zap")) { FactionPlayer fp; Faction tf; Faction f; int amount; String target; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] You do not have enough rank to ZAP."); return true; } // <faction> <amount> if (args.length < 3) { player.sendMessage("§7[f] The syntax is /f zap <faction> <amount>"); return true; } target = args[1]; amount = Integer.parseInt(args[2]); if (amount <= 0) { player.sendMessage("The amount of zap must be greater then zero."); return true; } if (amount > fp.faction.power) { player.sendMessage(String.format("§7[f] You do not have %d in power to ZAP with.", amount)); return true; } tf = getFactionByName(target); if (tf == null) { player.sendMessage(String.format("§7[f] Faction could not be found by the name '%s'", target)); return true; } f = fp.faction; // make sure not more than 20 zaps are going this // is to prevent a DOS memory attack by flooding us with // thousands of entries Iterator<ZapEntry> i; int zapCnt; i = tf.zappersIncoming.iterator(); zapCnt = 0; while (i.hasNext()) { if (i.next().from == f) zapCnt++; } if (zapCnt > 20) { player.sendMessage("§7[f] You reached maximum number of active zaps [20]"); return true; } ZapEntry ze; ze = new ZapEntry(); // no longer will it create fake zaps // instead it will warn the player of // the problem and not allow them to // zap the target faction if (tf.power < f.power) { player.sendMessage("§7[f] That faction has less power than you! You can zap only if they have more than you."); return true; } ze.amount = (double)amount; ze.timeStart = System.currentTimeMillis(); ze.timeTick = ze.timeStart; ze.perTick = (double)amount / (1000.0d * 60.0d * 60.0d * 48.0d); if (ze.perTick <= 0.0d) { // ensure it will at least drain amount which // will result in the ZapEntry's removal ze.perTick = 1.0d; } ze.from = f; ze.to = tf; synchronized (f) { f.zappersOutgoing.add(ze); tf.zappersIncoming.add(ze); // go ahead and subtract what they spent f.power -= amount; } player.sendMessage("§7[f] Zap has commenced."); return true; } if (cmd.equals("create")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); args[1] = sanitizeString(args[1]); if (fp != null) { player.sendMessage("§7[f] You must leave your current faction to create a new faction."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the new faction name. /f create <faction-name>"); return true; } if (factions.containsKey(args[1].toLowerCase())) { player.sendMessage(String.format("§7[f] The faction name %s is already taken.", args[1])); return true; } f = new Faction(); f.name = args[1]; f.desc = "default description"; f.mrc = 700; f.mri = 600; fp = new FactionPlayer(); fp.faction = f; fp.name = player.getName(); fp.rank = 1000; f.players.put(player.getName(), fp); getServer().broadcastMessage(String.format("§7[f] %s created new faction %s!", player.getName(), args[1])); synchronized (factions) { factions.put(args[1].toLowerCase(), f); } return true; } if (cmd.startsWith("cbr")) { FactionPlayer fp; FactionChunk fc; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("§7[f] This land is not owned"); return true; } if (fc.faction != fp.faction) { player.sendMessage(String.format("§7[f] This land is owned by §c%s§7!", fp.faction.name)); return true; } if (cmd.equals("cbru")) { m = fc.tidu; } else { m = fc.tid; } player.sendMessage("§7[f] Clearing Block Ranks"); if (m != null) { Iterator<Entry<Integer, Integer>> i; Entry<Integer, Integer> e; i = m.entrySet().iterator(); while (i.hasNext()) { e = i.next(); if (e.getValue() >= fp.rank) { player.sendMessage(String.format("§7 Rank too low for to clear %s[%d] at rank %d!", TypeIdToNameMap.getNameFromTypeId(e.getKey()), e.getKey(), e.getValue())); } else { i.remove(); } } } return true; } if (cmd.startsWith("lbr")) { FactionPlayer fp; FactionChunk fc; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("§7[f] This land is not owned"); return true; } if (cmd.equals("lbru")) { player.sendMessage("§7[f] List §cInteraction§7 Block Rank For Claim"); m = fc.tidu; } else { player.sendMessage("§7[f] List §cPlace/Break§7 Block Rank For Claim"); m = fc.tid; } if (m != null) { Iterator<Entry<Integer, Integer>> i; Entry<Integer, Integer> e; i = m.entrySet().iterator(); while (i.hasNext()) { e = i.next(); player.sendMessage(String.format("§7For §c%s§7(§d%d§7) you need rank §c%d§7 or better.", TypeIdToNameMap.getNameFromTypeId(e.getKey()), e.getKey(), e.getValue())); } if (cmd.equals("lbru")) { player.sendMessage("§7Use §d/f cbru§7 (to clear) and §d/f bru§7 to add to the list."); } else { player.sendMessage("§7Use §d/f cbr§7 (to clear) and §d/f br§7 to add to the list."); } } return true; } if (cmd.equals("seechunk")) { long ct, dt; ct = System.currentTimeMillis(); if (seeChunkLast.get(player.getName()) != null) { dt = ct - seeChunkLast.get(player.getName()); if (dt < 10000) { player.sendMessage(String.format("§7You need to wait %d more seconds before you can use this command again!", 10 - (dt / 1000))); return true; } } seeChunkLast.put(player.getName(), ct); showPlayerChunk(player, false); getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { showPlayerChunk(player, true); } }, 20 * 10); player.sendMessage("§7[f] The current chunk now surrounded with glass where there was air!"); return true; } if (cmd.startsWith("br")) { FactionPlayer fp; FactionChunk fc; int typeId; byte typeData; int rank; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("This land is not claimed."); return true; } if (fc.faction != fp.faction) { player.sendMessage(String.format("§7[f] This land is owned by %s.", fc.faction.name)); return true; } if (args.length == 1) { player.sendMessage("§7[f] Either hold item in hand, or use /f blockrank <rank> <typeId> <dataId(optinal)>"); return true; } rank = Integer.parseInt(args[1]); if (rank >= fp.rank) { player.sendMessage("§7[f] You can not set a block rank equal or greater than your rank."); return true; } if (args.length > 2) { typeId = Integer.parseInt(args[2]); if (args.length < 4) { typeData = (byte)0; } else { typeData = (byte)Integer.parseInt(args[3]); } } else { if (player.getItemInHand().getTypeId() == 0) { if (cmd.equals("bru")) { player.sendMessage("§7[f] Either hold item in hand and use §c/f bru <rank>§7, or use §c/f br <rank> <typeId>§7"); } else { player.sendMessage("§7[f] Either hold item in hand and use §c/f br <rank>§7, or use §c/f br <rank> <typeId>§7"); } return true; } typeId = player.getItemInHand().getTypeId(); typeData = player.getItemInHand().getData().getData(); } if (cmd.equals("bru")) { if (fc.tidu == null) fc.tidu = new HashMap<Integer, Integer>(); m = fc.tidu; } else { if (fc.tid == null) fc.tid = new HashMap<Integer, Integer>(); m = fc.tid; } /// UPGRADE CODE BLOCK if (m.containsKey(typeId)) { if (m.get(typeId) >= fp.rank) { player.sendMessage(String.format("§7[f] Block rank exists for §a%s[%d]§r and is equal or higher than your rank §b%d§r.", TypeIdToNameMap.getNameFromTypeId(typeId), fc.tid.get(typeId), fp.rank)); return true; } } m.put(typeId, rank); player.sendMessage(String.format("§7[f] Block §a%s§r[%d] at rank §a%d§r added to current claim.", TypeIdToNameMap.getNameFromTypeId(typeId), typeId, rank)); return true; } if (cmd.equals("invite")) { FactionPlayer fp; Player p; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the name of whom to invite! /f invite <player-name>"); return true; } if (fp.rank < fp.faction.mri) { player.sendMessage(String.format("§7[f] Your rank is %d but needs to be %d.", fp.rank, fp.faction.mri)); return true; } p = getServer().getPlayer(args[1]); if (p == null) { player.sendMessage("§7[f] The player must be online to invite them."); return true; } fp.faction.invites.add(args[1].toLowerCase()); sendFactionMessage(fp.faction, String.format("§7[f] %s has been invited to your faction", args[1])); if (p != null) { p.sendMessage(String.format("§7[f] You have been invited to %s by %s. Use /f join %s to join!", fp.faction.name, fp.name, fp.faction.name)); } return true; } if (cmd.equals("kick")) { FactionPlayer fp; FactionPlayer _fp; fp = getFactionPlayer(player.getName()); if (fp.rank < fp.faction.mri) { player.sendMessage("§7[f] Your rank is too low to invite or kick."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the player name. /f kick <player-name>"); return true; } _fp = getFactionPlayer(args[1]); if (_fp == null) { player.sendMessage("§7[f] Player specified is not in a faction or does not exist."); return true; } if (_fp.faction != fp.faction) { player.sendMessage(String.format("§7[f] Player is in faction %s and you are in faction %s.", _fp.faction.name, fp.faction.name)); return true; } if (_fp.rank >= fp.rank) { player.sendMessage(String.format("§7[f] Player %s at rank %d is equal or higher than your rank of %d", _fp.name, _fp.rank, fp.rank)); return true; } fp.faction.players.remove(_fp.name); getServer().broadcastMessage(String.format("§7[f] %s was kicked from faction %s by %s", _fp.name, fp.faction.name, fp.name)); return true; } if (cmd.equals("join")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); if (fp != null) { player.sendMessage("§7[f] You must leave you current faction to join another one."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the faction to join. /f join <faction-name>"); return true; } f = getFactionByName(args[1]); if (f == null) { player.sendMessage("§7[f] No faction found by that name."); return true; } // FIX FOR OLDER VER CLASS if (f.invites == null) f.invites = new HashSet<String>(); Iterator<String> i; i = f.invites.iterator(); while (i.hasNext()) { if (i.next().toLowerCase().equals(player.getName().toLowerCase())) { f.invites.remove(player.getName()); fp = new FactionPlayer(); fp.faction = f; fp.name = player.getName(); fp.rank = 0; f.players.put(player.getName(), fp); getServer().broadcastMessage(String.format("§7[f] %s just joined the faction [%s].", fp.name, f.name)); return true; } } player.sendMessage("You have no invintation to join that faction!"); return true; } if (cmd.equals("leave")) { FactionPlayer fp; FactionChunk fchunk; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } /// MAKE SURE WE ARE NOT STANDING ON FACTION CLAIMED LAND fchunk = getFactionChunk(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockZ()); if (fchunk != null) { if (fchunk.faction == fp.faction) { player.sendMessage("§7[f] You must not be on your faction land when leaving the faction."); return true; } } /// MAKE SURE NOT EMPTY IF SO NEED TO USE DISBAND /// IF WE ARE OWNER WE NEED TO TRANSFER OWNERSHIP BEFORE WE LEAVE if (fp.faction.players.size() == 1) { // ENSURE THEY ARE HIGH ENOUGH FOR OWNER (CATCH BUGS KINDA) fp.rank = 1000; player.sendMessage("§7[f] You are the last player in faction use /f disband."); return true; } // IF THEY ARE THE OWNER HAND OWNERSHIP TO SOMEBODY ELSE KINDA AT RANDOM if (fp.rank == 1000) { Iterator<Entry<String, FactionPlayer>> i; FactionPlayer _fp; i = fp.faction.players.entrySet().iterator(); _fp = null; while (i.hasNext()) { _fp = i.next().getValue(); if (!fp.name.equals(_fp.name)) break; } _fp.rank = 1000; getServer().broadcastMessage(String.format("§7[f] Ownership of %s was handed to %s at random.", fp.faction.name, fp.name)); } getServer().broadcastMessage(String.format("§7[f] §a%s§r has left the faction §a%s§r!", fp.name, fp.faction.name)); fp.faction.players.remove(fp.name); return true; } if (cmd.equals("disband")) { FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // MUST BE OWNER OF FACTION if (fp.rank < 1000) { player.sendMessage("§7[f] You are not owner of faction."); return true; } // why the hell am i doing this? --kmcguire fp.faction.chunks = new HashMap<String, Map<Long, FactionChunk>>(); getServer().broadcastMessage(String.format("§7[f] §a%s§r has disbanded the faction §a%s§r!", fp.name, fp.faction.name)); factions.remove(fp.faction.name.toLowerCase()); return true; } if (cmd.equals("listfriends")) { String friendName; Faction f; FactionPlayer fp; int frank; Iterator<Entry<String, Integer>> i; Entry<String, Integer> e; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.faction.friends == null) { player.sendMessage("§7[f] Faction has no friends."); return true; } i = fp.faction.friends.entrySet().iterator(); while (i.hasNext()) { e = i.next(); player.sendMessage(String.format("§7[f] %s => %d", e.getKey(), e.getValue())); } player.sendMessage("§7[f] Done"); return true; } if (cmd.equals("addfriend")) { String friendName; Faction f; FactionPlayer fp; int frank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (args.length < 3) { player.sendMessage("Syntax is /f addfriend <name> <rank>. Use again to change rank. Use /f remfriend to remove."); return true; } friendName = args[1]; frank = Integer.parseInt(args[2]); if (frank >= fp.rank) { player.sendMessage(String.format("§7[f] You can not set friend rank of %d because it is higher than your rank of %d.", frank, fp.rank)); return true; } if (fp.faction.friends == null) fp.faction.friends = new HashMap<String, Integer>(); fp.faction.friends.put(friendName, frank); sendFactionMessage(fp.faction, String.format("§7[f] Added friend %s at rank %d\n", friendName, frank)); return true; } if (cmd.equals("remfriend")) { String friendName; Faction f; FactionPlayer fp; int frank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (args.length < 2) { player.sendMessage("Syntax is /f remfriend <name>."); return true; } friendName = args[1]; if (fp.faction.friends == null) fp.faction.friends = new HashMap<String, Integer>(); if (fp.faction.friends.containsKey(friendName)) { frank = fp.faction.friends.get(friendName); if (frank >= fp.rank) { player.sendMessage(String.format("§7[f] You can not remove friend with rank of %d because it is higher than your rank of %d.", frank, fp.rank)); return true; } } fp.faction.friends.remove(friendName); sendFactionMessage(fp.faction, String.format("§7[f] Removed friend %s\n", friendName)); return true; } if (cmd.equals("rename")) { FactionPlayer fp; String newName; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.rank < 1000) { player.sendMessage("§7[f] You need to be owner of this faction to change the rank!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] The syntax is /f rename <newname>."); return true; } newName = args[1]; newName = sanitizeString(newName); if (newName.length() < 1) { player.sendMessage("§7[f] The name length is zero!"); return true; } getServer().broadcastMessage(String.format("§7[f] The faction §a%s§7 was renamed to §a%s§7.", fp.faction.name, newName)); synchronized (factions) { factions.remove(fp.faction.name.toLowerCase()); fp.faction.name = newName; factions.put(fp.faction.name.toLowerCase(), fp.faction); } return true; } if (cmd.equals("claim")) { FactionPlayer fp; int x, z; FactionChunk fchunk; double pow; if (player == null) { player.sendMessage("§7[f] uhoh plyer is null"); return true; } fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } // DO WE HAVE ENOUGH POWER? // NEED ENOUGH TO HOLD FOR 24 HOURS //pow = getFactionPower(fp.faction); //if (pow < ((fp.faction.chunks.size() + 1) * 24.0)) { // player.sendMessage("§7[f] The faction lacks needed power to claim land"); // return true; //} //smsg(String.format("blockx:%d", player.getLocation().getBlockX())); x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fchunk = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fchunk != null) { if (fchunk.faction == fp.faction) { player.sendMessage(String.format("§7[f] chunk already owned by your faction %s", fchunk.faction.name)); return true; } if (noGriefPerWorld.contains(player.getWorld().getName())) { player.sendMessage("§7[f] This world does not allow claiming of another faction's land!"); return true; } if (fchunk.faction != fp.faction) { if (getFactionPower(fchunk.faction) >= fchunk.faction.chunks.size()) { player.sendMessage(String.format("§7[f] faction %s has enough power to hold this claim", fchunk.faction.name)); return true; } getServer().broadcastMessage(String.format("§7[f] %s lost land claim to %s by %s", fchunk.faction.name, fp.faction.name, fp.name)); fchunk.faction.chunks.remove(getChunkLong(player.getWorld(), x >> 4, z >> 4)); } } fchunk = new FactionChunk(); fchunk.x = x >> 4; fchunk.z = z >> 4; fchunk.worldName = player.getWorld().getName(); fchunk.faction = fp.faction; fchunk.mrb = 500; // DEFAULT VALUES fchunk.mru = 250; fchunk.faction = fp.faction; if (fp.faction.chunks.get(player.getWorld().getName()) == null) { fp.faction.chunks.put(player.getWorld().getName(), new HashMap<Long, FactionChunk>()); } fp.faction.chunks.get(player.getWorld().getName()).put(LongHash.toLong(x >> 4, z >> 4), fchunk); //fp.faction.chunks.put(getChunkLong(player.getWorld(), x >> 4, z >> 4), fchunk); getServer().broadcastMessage(String.format("§7[f] %s of faction %s claimed land", fp.name, fp.faction.name)); return true; } if (cmd.equals("setrank")) { FactionPlayer fp; FactionPlayer mp; int nrank; if (args.length < 2) { player.sendMessage("§7[f] Not enough arguments /f rank <player> <rank>"); return true; } fp = getFactionPlayer(args[1]); mp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] Player is not in a faction."); return true; } if (mp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.faction != mp.faction) { player.sendMessage("§7[f] You and player are not in the same faction."); } if ((fp.rank >= mp.rank) && (!player.isOp())) { player.sendMessage("§7[f] Player is already at equal or greater rank than you."); return true; } nrank = Integer.valueOf(args[2]); if ((nrank >= mp.rank) && (!player.isOp())) { player.sendMessage("§7[f] Rank you wish to set is equal or greater than you rank. [rejected]"); return true; } fp.rank = nrank; player.sendMessage(String.format("§7[f] rank for %s is now %d", args[1], nrank)); return true; } if (cmd.equals("unclaim")) { FactionPlayer fp; FactionChunk fchunk; int x, z; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } x = player.getLocation().getBlockX() >> 4; z = player.getLocation().getBlockZ() >> 4; fchunk = getFactionChunk(player.getWorld(), x, z); if (fchunk == null) { player.sendMessage("§7[f] This land chunk is owned by no one."); return true; } if (fchunk.faction != fp.faction) { player.sendMessage(String.format("§7[f] Your faction is %s, but this land belongs to %s.", fp.faction.name, fchunk.faction.name)); return true; } fp.faction.chunks.remove(getChunkLong(player.getWorld(), x, z)); // UPDATE FACTION POWER getFactionPower(fp.faction); getServer().broadcastMessage(String.format("§7[f] %s of faction %s unclaimed land", fp.name, fp.faction.name)); return true; } if (cmd.equals("unclaimall")) { FactionPlayer fp; Iterator<Entry<Long, FactionChunk>> i; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } fp.faction.chunks = new HashMap<String, Map<Long, FactionChunk>>(); getServer().broadcastMessage(String.format("§7[f] %s of faction %s declaimed all land", fp.name, fp.faction.name)); return true; } if (cmd.equals("chkcharge")) { int icnt; int mid; byte dat; double pts; icnt = player.getItemInHand().getAmount(); mid = player.getItemInHand().getTypeId(); dat = player.getItemInHand().getData().getData(); pts = (double)getEMC(mid, dat); player.sendMessage(String.format("§7[f] %f/item total:%f", pts, pts * icnt)); return true; } if (cmd.equals("charge")) { FactionPlayer fp; int icnt; double pts; int mid; byte dat; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } icnt = player.getItemInHand().getAmount(); mid = player.getItemInHand().getTypeId(); dat = player.getItemInHand().getData().getData(); //pts = (double)EEMaps.getEMC(mid, dat); pts = (double)getEMC(mid, dat); player.sendMessage(String.format("§7[f] Item value is %f", pts)); pts = pts * icnt; if (pts == 0.0d) { player.sendMessage("§7[f] Item(s) in hand yield no charge value."); return true; } player.setItemInHand(null); synchronized (fp.faction) { fp.faction.power += pts; } //getServer().broadcastMessage(String.format("§7[f] %s in %s charged faction power!", player.getDisplayName(), fp.faction.name)); sendFactionMessage(fp.faction, String.format("§7[f] %s charged the faction power by %f to %f.", player.getDisplayName(), pts, getFactionPower(fp.faction))); return true; } // SHOW FACTION INFORMATION ABOUT OUR FACTION // OR ANOTHER FACTION SPECIFIED if (cmd.equalsIgnoreCase("who")) { FactionPlayer fp; Faction f; Iterator<Entry<String, FactionPlayer>> iter; Entry<String, FactionPlayer> e; String o; fp = getFactionPlayer(player.getName()); if (args.length < 2 && fp == null) { player.sendMessage("§7[f] You must either specify a faction or be in a faction!"); return true; } if (args.length == 2) { f = getFactionByName(args[1]); if (f == null) { fp = getFactionPlayer(args[1]); if (fp == null) { player.sendMessage(String.format("§7[f] Could not find a faction or player named '%s'!", args[1])); return true; } f = fp.faction; } } else { f = fp.faction; } if (f == null) { player.sendMessage(String.format("§7[f] The faction %s could not be found.", args[1])); return true; } // display name and description player.sendMessage(String.format("§6Faction: §7%s", f.name)); //player.sendMessage(String.format("Description: %s", f.desc)); // display land/power/maxpower if (fp != null) { player.sendMessage(String.format("§6Land: §7%d §6Power/Hour: §7%d §6Power: §7%d", f.chunks.size(), (int)(landPowerCostPerHour * f.chunks.size()), (int)getFactionPower(f) )); player.sendMessage(String.format("§6TimeLeft: §7%d hours", (int)(getFactionPower(f) / (landPowerCostPerHour * f.chunks.size())) )); } else { player.sendMessage(String.format("§6Land: §7%d", f.chunks.size() )); } // mri, mrc, flags, mrz, mrtp, mrsh player.sendMessage(String.format( "§6MRI:§7%d §6MRC:§7%d §6FLAGS:§7%d §6MRZ:§7%d §6MRTP:§7%d §6MRSH:§7%d", f.mri, f.mrc, f.flags, (int)f.mrz, (int)f.mrtp, f.mrsh )); iter = f.players.entrySet().iterator(); o = "§6Members:§r"; while (iter.hasNext()) { e = iter.next(); if (getServer().getPlayer(e.getKey()) != null) { o = String.format("%s, §6%s§7[%d]", o, e.getKey(), e.getValue().rank); } else { o = String.format("%s, §7%s§7[%d]", o, e.getKey(), e.getValue().rank); } } player.sendMessage(o); return true; } if (cmd.equals("inspect")) { Location loc; FactionChunk fc; int bx, bz; loc = player.getLocation(); bx = loc.getBlockX() >> 4; bz = loc.getBlockZ() >> 4; fc = getFactionChunk(player.getWorld(), bx, bz); if (fc == null) { player.sendMessage("§7[f] §7Land not claimed by anyone."); return true; } player.sendMessage(String.format("§6Faction:§r%s §6MinimumBuildRank:§r%d §6MinimumUseRank:§r%d", fc.faction.name, fc.mrb, fc.mru)); return true; } displayHelp(player, args); return false; }
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { String cmd; final Player player; // MUST BE TYPED INTO THE CONSOLE if (!(sender instanceof Player)) { if (args.length < 1) { return true; } cmd = args[0]; if (cmd.equals("glitch1")) { Faction f; f = getFactionByName(args[1]); f.mrc = 700; f.mri = 600; return true; } if (command.getName().equals("resetwa")) { int x, y, z; Iterator<WorldAnchorLocation> i; WorldAnchorLocation wal; Faction f; String fn; String w; fn = args[0]; w = args[1]; x = Integer.parseInt(args[2]); y = Integer.parseInt(args[3]); z = Integer.parseInt(args[4]); f = getFactionByName(fn); if (f == null) { getServer().getLogger().info("[f] Could not find faction"); return true; } i = f.walocs.iterator(); while (i.hasNext()) { wal = i.next(); if ((wal.x == x) && (wal.y == y) && (wal.z == z) && (wal.w.equals(w))) { getServer().getLogger().info("§7[f] World anchor removed from faction control. You may now place one more."); i.remove(); return true; } } getServer().getLogger().info("[f] Could not find world anchor."); return true; } if (cmd.equals("setgspawn")) { if (args.length < 1) { getServer().getLogger().info("§7[f] setgspawn needs one argument /f setgspawn <playername>"); return true; } Location l; File file; RandomAccessFile raf; if (getServer().getPlayer(args[1]) == null) { getServer().getLogger().info("§7[f] player does not exist"); return true; } l = getServer().getPlayer(args[1]).getLocation(); gspawn = l; getServer().getLogger().info("§7[f] set global respawn to location of player"); // ALSO WRITE OUT TO DISK FILE file = new File("plugin.gspawn.factions"); try { raf = new RandomAccessFile(file, "rw"); raf.writeUTF(l.getWorld().getName()); raf.writeDouble(l.getX()); raf.writeDouble(l.getY()); raf.writeDouble(l.getZ()); raf.close(); } catch (FileNotFoundException e) { return true; } catch (IOException e) { getServer().getLogger().info("§7[f] could not write gspawn to disk!"); return true; } return true; } if (cmd.equals("noboom")) { // f noboom <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] noboom needs one argument /f noboom <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NOBOOM) == NOBOOM) { f.flags = f.flags & ~NOBOOM; getServer().getLogger().info(String.format("§7[f] NOBOOM toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NOBOOM; getServer().getLogger().info(String.format("§7[f] NOBOOM toggled ON on %s", args[1])); return true; } if (cmd.equals("nopvp")) { // f nopvp <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] nopvp needs one argument /f nopvp <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NOPVP) == NOPVP) { f.flags = f.flags & ~NOPVP; getServer().getLogger().info(String.format("§7[f] NOPVP toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NOPVP; getServer().getLogger().info(String.format("§7[f] NOPVP toggled ON on %s", args[1])); return true; } if (cmd.equals("nodecay")) { // f nopvp <faction-name> Faction f; if (args.length < 1) { getServer().getLogger().info("§7[f] nodecay needs one argument /f nodecay <faction>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if ((f.flags & NODECAY) == NODECAY) { f.flags = f.flags & ~NODECAY; getServer().getLogger().info(String.format("§7[f] NODECAY toggled OFF on %s", args[1])); return true; } f.flags = f.flags | NODECAY; getServer().getLogger().info(String.format("§7[f] NODECAY toggled ON on %s", args[1])); return true; } if (cmd.equals("yank")) { // f yank <faction> <player> Faction f; if (args.length < 2) { getServer().getLogger().info("§7[f] yank needs two arguments /f yank <faction> <player>"); return true; } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } if (!f.players.containsKey(args[2])) { getServer().getLogger().info(String.format("§7[f] faction %s has no player %s", args[1], args[2])); return true; } f.players.remove(args[2]); getServer().getLogger().info(String.format("§7[f] player %s was yanked from faction %s", args[2], args[1])); return true; } if (cmd.equals("stick")) { // f stick <faction> <player> FactionPlayer fp; Faction f; if (args.length < 2) { getServer().getLogger().info("§7[f] stick needs two arguments /stick <faction> <player>"); return true; } fp = getFactionPlayer(args[2]); if (fp != null) { fp.faction.players.remove(fp.name); } f = getFactionByName(args[1]); if (f == null) { getServer().getLogger().info(String.format("§7[f] faction %s can not be found", args[1])); return true; } fp = new FactionPlayer(); fp.rank = 1000; fp.name = args[2]; fp.faction = f; f.players.put(args[2], fp); getServer().getLogger().info(String.format("§7[f] player %s was stick-ed in faction %s", args[2], args[1])); return true; } } if (!(sender instanceof Player)) return false; player = (Player)sender; // enforce world restrictions if (!worldsEnabled.contains(player.getWorld().getName())) { player.sendMessage("§7[f] This world has not been enabled for KFactions!"); return true; } if (command.getName().equals("home")) { player.sendMessage("§7[f] Use /f home (requires a faction)"); return true; } if (command.getName().equals("spawn")) { player.sendMessage("§7[f] Use /f spawn (requires a faction)"); return true; } if (args.length < 1) { if (sender instanceof Player) displayHelp((Player)sender, args); return false; } cmd = args[0]; //this.getServer().getPluginManager().getPlugins()[0]. //setmri, setmrc, setmrsp, setmrtp, //sethome, tptp if (cmd.equals("c")) { StringBuffer sb; FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } sb = new StringBuffer(); for (int x = 1; x < args.length; ++x) { sb.append(args[x]); sb.append(" "); } sendFactionMessage(fp.faction, String.format("§d[Faction]§r§e %s: %s", player.getDisplayName(), sb.toString())); return true; } if (cmd.equals("showanchors")) { Iterator<WorldAnchorLocation> i; WorldAnchorLocation wal; FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } player.sendMessage("§7[f] Showing Placed World Anchors"); i = fp.faction.walocs.iterator(); while (i.hasNext()) { wal = i.next(); player.sendMessage(String.format( " x:%d y:%d z:%d w:%s by:%s age:%d/days", wal.x, wal.y, wal.z, wal.w, wal.byWho, (System.currentTimeMillis() - wal.timePlaced) / 1000 / 60 / 60 / 24 )); } return true; } if (cmd.equals("scan")) { double chance; double Xmax, Xmin, Zmax, Zmin; int wndx, cndx, fndx; int realX, realZ; FactionPlayer fp; long ct; long sr; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } if (!enabledScanner) { player.sendMessage("§7[f] The scanner feature is not enabled on this server!"); return true; } ct = System.currentTimeMillis(); if (scannerWait.containsKey(fp.faction.name)) { sr = ct - scannerWait.get(fp.faction.name); if (sr < (1000 * scannerWaitTime)) { player.sendMessage(String.format( "§7[f] You need to wait %d more seconds!", ((1000 * scannerWaitTime) - sr) / 1000 )); return true; } } // scan all factions and all land claims to build minimum and maximum bounds fndx = (int)(Math.random() * factions.size()); realX = 0; realZ = 0; Xmax = 0; Zmax = 0; Xmin = 0; Zmin = 0; for (Faction f : factions.values()) { // pick random claim if any claim exists wndx = (int)(Math.random() * f.chunks.size()); for (String wn : f.chunks.keySet()) { cndx = (int)(Math.random() * f.chunks.get(wn).size()); for (FactionChunk fc : f.chunks.get(wn).values()) { if (cndx == 0 && wndx == 0 && fndx == 0) { realX = fc.x * 16; realZ = fc.z * 16; } Xmax = Xmax == 0 || fc.x > Xmax ? fc.x : Xmax; Zmax = Zmax == 0 || fc.z > Zmax ? fc.z : Zmax; Xmin = Xmin == 0 || fc.x < Xmin ? fc.x : Xmin; Zmin = Zmin == 0 || fc.z < Zmin ? fc.z : Zmin; --cndx; } --wndx; } --fndx; } if (Math.random() > scannerChance) { Xmax = Xmax * 16; Xmin = Xmin * 16; Zmax = Zmax * 16; Zmin = Zmin * 16; realX = (int)(Math.random() * (double)(Xmax - Xmin) + (double)Xmin); realZ = (int)(Math.random() * (double)(Zmax - Zmin) + (double)Zmin); realX = (realX >> 4) << 4; realZ = (realZ >> 4) << 4; } scannerWait.put(fp.faction.name, ct); sendFactionMessage(fp.faction, String.format( "§7 The world anomally scanner result is §a%d:%d§r.", realX, realZ )); return true; } if (cmd.equals("curank") || cmd.equals("cbrank")) { FactionPlayer fp; FactionChunk fc; Location loc; int bx, bz; int irank; loc = player.getLocation(); fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] §7You are not in a faction."); return true; } bx = loc.getBlockX() >> 4; bz = loc.getBlockZ() >> 4; fc = getFactionChunk(player.getWorld(), bx, bz); if (fc == null) { player.sendMessage("§7[f] §7Land not claimed by anyone."); return true; } if ((fc.faction != fp.faction) && (!player.isOp())) { player.sendMessage("§7[f] §7Land not claimed by your faction."); return true; } if ((fc.mrb >= fp.rank) && (!player.isOp())) { player.sendMessage("§7[f] §7Land rank is equal or greater than yours."); return true; } if (args.length < 2) { player.sendMessage("§7[f] §7The syntax is /f curank <value> OR /f cbrank <value>"); return true; } irank = Integer.valueOf(args[1]); if ((irank >= fp.rank) && (!player.isOp())) { player.sendMessage("§7[f] §7Your rank is too low."); return true; } if (cmd.equals("curank")) { fc.mru = irank; } else { fc.mrb = irank; } player.sendMessage("§7[f] §7The rank was set. Use /f inspect to check."); return true; } if (cmd.equals("sethome")) { FactionPlayer fp; FactionChunk fc; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } fc = getFactionChunk(player.getWorld(), player.getLocation().getBlockX() >> 4, player.getLocation().getBlockZ() >> 4); if (fc == null) { player.sendMessage("§7[f] Must be on faction land."); return true; } if (fc.faction != fp.faction) { player.sendMessage("§7[f] Must be on your faction land."); return true; } if (fp.rank < fp.faction.mrsh) { player.sendMessage("§7[f] Your rank is too low."); return true; } fp.faction.hx = player.getLocation().getX(); fp.faction.hy = player.getLocation().getY(); fp.faction.hz = player.getLocation().getZ(); fp.faction.hw = player.getLocation().getWorld().getName(); player.sendMessage("§7[f] Faction home set."); return true; } if (cmd.equals("tptp") || cmd.equals("home") || cmd.equals("spawn")) { FactionPlayer fp; if (cmd.equals("spawn")) { args = new String[3]; args[1] = player.getName(); args[2] = "spawn"; } if (cmd.equals("home")) { args = new String[3]; args[1] = player.getName(); args[2] = "home"; } fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrtp) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 3) { player.sendMessage("§7[f] Use syntax /f tptp <player> <player/home>"); return true; } FactionPlayer src; FactionPlayer dst; src = getFactionPlayer(args[1]); dst = getFactionPlayer(args[2]); if (src == null) { player.sendMessage("§7[f] Source player does not exist."); return true; } if (src.rank > fp.rank) { player.sendMessage(String.format("§7[f] The player %s is higher in rank than you. Ask him.", args[2])); return true; } if (dst == null) { if (!args[2].equals("home") && !args[2].equals("spawn")) { player.sendMessage("§7[f] Source player does not exist, or use word $home."); return true; } } else { if (dst.rank > fp.rank) { player.sendMessage(String.format("§7[f] The player %s is higher in rank than you. Ask him.", args[3])); return true; } } Location loc; if (dst != null) { if ((src.faction != dst.faction) || (src.faction != fp.faction)) { player.sendMessage("§7[f] Everyone has to be in the same faction."); return true; } loc = getServer().getPlayer(args[2]).getLocation(); if (getServer().getPlayer(args[1]) != null) { getServer().getPlayer(args[1]).teleport(loc); synchronized (fp.faction) { fp.faction.power = fp.faction.power - (fp.faction.power * 0.1); } } else { player.sendMessage(String.format("§7[f] The player %s was not found.", args[1])); } return true; } if ((src.faction != fp.faction)) { player.sendMessage("§7[f] Everyone has to be in the same faction."); return true; } // are we going home or to spawn? if (args[2].equals("spawn")) { loc = gspawn; if (gspawn == null) { player.sendMessage("§7[f] The spawn has not been set for factions!"); return true; } } else { // teleport them to home if (fp.faction.hw == null) { player.sendMessage("§7[f] The faction home is not set! Use /f sethome"); return true; } loc = new Location(getServer().getWorld(fp.faction.hw), fp.faction.hx, fp.faction.hy + 0.3, fp.faction.hz); } getServer().getPlayer(args[1]).teleport(loc); synchronized (fp.faction) { fp.faction.power = fp.faction.power - (fp.faction.power * 0.1); } return true; } if (cmd.equals("setmrsh")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrsh) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrsh <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrsh = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrtp")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrtp) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrtp <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrtp = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrz")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrz <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrz = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmrc")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrc) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmrc <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mrc = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setmri")) { FactionPlayer fp; int rank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mri) { player.sendMessage("§7[f] Your rank is too low."); return true; } if (args.length < 2) { player.sendMessage("§7[f] Use /f setmri <rank>"); return true; } rank = Integer.parseInt(args[1]); if (rank > fp.rank) { player.sendMessage("§7[f] You can not set the rank higher than your own."); return true; } fp.faction.mri = rank; player.sendMessage("§7[f] The rank was changed."); return true; } if (cmd.equals("setzaprank")) { FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] Too few arguments. Use /f setzaprank <rank>"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] You are lower than the MRZ rank, so you can not change it."); return true; } fp.faction.mrz = Integer.parseInt(args[1]); return true; } if (cmd.equals("showzaps")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } f = fp.faction; synchronized (f) { double grandTotal; player.sendMessage("[§6f§r] [§6DIR§r ] [§6AMOUNT§r ] [§6FACTION§r]"); for (ZapEntry e : f.zappersOutgoing) { player.sendMessage(String.format(" §6OUT§r (%11f) §6%s", e.amount, e.to.name)); } grandTotal = 0; for (ZapEntry e : f.zappersIncoming) { player.sendMessage(String.format(" §6IN§r (%11f) §6%s", e.amount, e.from.name)); if (!e.isFake) grandTotal += e.amount; } player.sendMessage(String.format("TOTAL ZAP INCOMING: %f", grandTotal)); } return true; } if (cmd.equals("zap")) { FactionPlayer fp; Faction tf; Faction f; int amount; String target; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (fp.rank < fp.faction.mrz) { player.sendMessage("§7[f] You do not have enough rank to ZAP."); return true; } // <faction> <amount> if (args.length < 3) { player.sendMessage("§7[f] The syntax is /f zap <faction> <amount>"); return true; } target = args[1]; amount = Integer.parseInt(args[2]); if (amount <= 0) { player.sendMessage("The amount of zap must be greater then zero."); return true; } if (amount > fp.faction.power) { player.sendMessage(String.format("§7[f] You do not have %d in power to ZAP with.", amount)); return true; } tf = getFactionByName(target); if (tf == null) { player.sendMessage(String.format("§7[f] Faction could not be found by the name '%s'", target)); return true; } f = fp.faction; // make sure not more than 20 zaps are going this // is to prevent a DOS memory attack by flooding us with // thousands of entries Iterator<ZapEntry> i; int zapCnt; i = tf.zappersIncoming.iterator(); zapCnt = 0; while (i.hasNext()) { if (i.next().from == f) zapCnt++; } if (zapCnt > 20) { player.sendMessage("§7[f] You reached maximum number of active zaps [20]"); return true; } ZapEntry ze; ze = new ZapEntry(); // no longer will it create fake zaps // instead it will warn the player of // the problem and not allow them to // zap the target faction if (tf.power < f.power) { player.sendMessage("§7[f] That faction has less power than you! You can zap only if they have more than you."); return true; } ze.amount = (double)amount; ze.timeStart = System.currentTimeMillis(); ze.timeTick = ze.timeStart; ze.perTick = (double)amount / (1000.0d * 60.0d * 60.0d * 48.0d); if (ze.perTick <= 0.0d) { // ensure it will at least drain amount which // will result in the ZapEntry's removal ze.perTick = 1.0d; } ze.from = f; ze.to = tf; synchronized (f) { f.zappersOutgoing.add(ze); tf.zappersIncoming.add(ze); // go ahead and subtract what they spent f.power -= amount; } player.sendMessage("§7[f] Zap has commenced."); return true; } if (cmd.equals("create")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); args[1] = sanitizeString(args[1]); if (fp != null) { player.sendMessage("§7[f] You must leave your current faction to create a new faction."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the new faction name. /f create <faction-name>"); return true; } if (factions.containsKey(args[1].toLowerCase())) { player.sendMessage(String.format("§7[f] The faction name %s is already taken.", args[1])); return true; } f = new Faction(); f.name = args[1]; f.desc = "default description"; f.mrc = 700; f.mri = 600; fp = new FactionPlayer(); fp.faction = f; fp.name = player.getName(); fp.rank = 1000; f.players.put(player.getName(), fp); getServer().broadcastMessage(String.format("§7[f] %s created new faction %s!", player.getName(), args[1])); synchronized (factions) { factions.put(args[1].toLowerCase(), f); } return true; } if (cmd.startsWith("cbr")) { FactionPlayer fp; FactionChunk fc; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("§7[f] This land is not owned"); return true; } if (fc.faction != fp.faction) { player.sendMessage(String.format("§7[f] This land is owned by §c%s§7!", fp.faction.name)); return true; } if (cmd.equals("cbru")) { m = fc.tidu; } else { m = fc.tid; } player.sendMessage("§7[f] Clearing Block Ranks"); if (m != null) { Iterator<Entry<Integer, Integer>> i; Entry<Integer, Integer> e; i = m.entrySet().iterator(); while (i.hasNext()) { e = i.next(); if (e.getValue() >= fp.rank) { player.sendMessage(String.format("§7 Rank too low for to clear %s[%d] at rank %d!", TypeIdToNameMap.getNameFromTypeId(e.getKey()), e.getKey(), e.getValue())); } else { i.remove(); } } } return true; } if (cmd.startsWith("lbr")) { FactionPlayer fp; FactionChunk fc; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("§7[f] This land is not owned"); return true; } if (cmd.equals("lbru")) { player.sendMessage("§7[f] List §cInteraction§7 Block Rank For Claim"); m = fc.tidu; } else { player.sendMessage("§7[f] List §cPlace/Break§7 Block Rank For Claim"); m = fc.tid; } if (m != null) { Iterator<Entry<Integer, Integer>> i; Entry<Integer, Integer> e; i = m.entrySet().iterator(); while (i.hasNext()) { e = i.next(); player.sendMessage(String.format("§7For §c%s§7(§d%d§7) you need rank §c%d§7 or better.", TypeIdToNameMap.getNameFromTypeId(e.getKey()), e.getKey(), e.getValue())); } if (cmd.equals("lbru")) { player.sendMessage("§7Use §d/f cbru§7 (to clear) and §d/f bru§7 to add to the list."); } else { player.sendMessage("§7Use §d/f cbr§7 (to clear) and §d/f br§7 to add to the list."); } } return true; } if (cmd.equals("seechunk")) { long ct, dt; ct = System.currentTimeMillis(); if (seeChunkLast.get(player.getName()) != null) { dt = ct - seeChunkLast.get(player.getName()); if (dt < 10000) { player.sendMessage(String.format("§7You need to wait %d more seconds before you can use this command again!", 10 - (dt / 1000))); return true; } } seeChunkLast.put(player.getName(), ct); showPlayerChunk(player, false); getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { showPlayerChunk(player, true); } }, 20 * 10); player.sendMessage("§7[f] The current chunk now surrounded with glass where there was air!"); return true; } if (cmd.startsWith("br")) { FactionPlayer fp; FactionChunk fc; int typeId; byte typeData; int rank; int x, z; Map<Integer, Integer> m; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fc = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fc == null) { player.sendMessage("This land is not claimed."); return true; } if (fc.faction != fp.faction) { player.sendMessage(String.format("§7[f] This land is owned by %s.", fc.faction.name)); return true; } if (args.length == 1) { player.sendMessage("§7[f] Either hold item in hand, or use /f blockrank <rank> <typeId> <dataId(optinal)>"); return true; } rank = Integer.parseInt(args[1]); if (rank >= fp.rank) { player.sendMessage("§7[f] You can not set a block rank equal or greater than your rank."); return true; } if (args.length > 2) { typeId = Integer.parseInt(args[2]); if (args.length < 4) { typeData = (byte)0; } else { typeData = (byte)Integer.parseInt(args[3]); } } else { if (player.getItemInHand().getTypeId() == 0) { if (cmd.equals("bru")) { player.sendMessage("§7[f] Either hold item in hand and use §c/f bru <rank>§7, or use §c/f br <rank> <typeId>§7"); } else { player.sendMessage("§7[f] Either hold item in hand and use §c/f br <rank>§7, or use §c/f br <rank> <typeId>§7"); } return true; } typeId = player.getItemInHand().getTypeId(); typeData = player.getItemInHand().getData().getData(); } if (cmd.equals("bru")) { if (fc.tidu == null) fc.tidu = new HashMap<Integer, Integer>(); m = fc.tidu; } else { if (fc.tid == null) fc.tid = new HashMap<Integer, Integer>(); m = fc.tid; } /// UPGRADE CODE BLOCK if (m.containsKey(typeId)) { if (m.get(typeId) >= fp.rank) { player.sendMessage(String.format("§7[f] Block rank exists for §a%s[%d]§r and is equal or higher than your rank §b%d§r.", TypeIdToNameMap.getNameFromTypeId(typeId), fc.tid.get(typeId), fp.rank)); return true; } } m.put(typeId, rank); player.sendMessage(String.format("§7[f] Block §a%s§r[%d] at rank §a%d§r added to current claim.", TypeIdToNameMap.getNameFromTypeId(typeId), typeId, rank)); return true; } if (cmd.equals("invite")) { FactionPlayer fp; Player p; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You must be in a faction!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the name of whom to invite! /f invite <player-name>"); return true; } if (fp.rank < fp.faction.mri) { player.sendMessage(String.format("§7[f] Your rank is %d but needs to be %d.", fp.rank, fp.faction.mri)); return true; } p = getServer().getPlayer(args[1]); if (p == null) { player.sendMessage("§7[f] The player must be online to invite them."); return true; } fp.faction.invites.add(args[1].toLowerCase()); sendFactionMessage(fp.faction, String.format("§7[f] %s has been invited to your faction", args[1])); if (p != null) { p.sendMessage(String.format("§7[f] You have been invited to %s by %s. Use /f join %s to join!", fp.faction.name, fp.name, fp.faction.name)); } return true; } if (cmd.equals("kick")) { FactionPlayer fp; FactionPlayer _fp; fp = getFactionPlayer(player.getName()); if (fp.rank < fp.faction.mri) { player.sendMessage("§7[f] Your rank is too low to invite or kick."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the player name. /f kick <player-name>"); return true; } _fp = getFactionPlayer(args[1]); if (_fp == null) { player.sendMessage("§7[f] Player specified is not in a faction or does not exist."); return true; } if (_fp.faction != fp.faction) { player.sendMessage(String.format("§7[f] Player is in faction %s and you are in faction %s.", _fp.faction.name, fp.faction.name)); return true; } if (_fp.rank >= fp.rank) { player.sendMessage(String.format("§7[f] Player %s at rank %d is equal or higher than your rank of %d", _fp.name, _fp.rank, fp.rank)); return true; } fp.faction.players.remove(_fp.name); getServer().broadcastMessage(String.format("§7[f] %s was kicked from faction %s by %s", _fp.name, fp.faction.name, fp.name)); return true; } if (cmd.equals("join")) { FactionPlayer fp; Faction f; fp = getFactionPlayer(player.getName()); if (fp != null) { player.sendMessage("§7[f] You must leave you current faction to join another one."); return true; } if (args.length < 2) { player.sendMessage("§7[f] You must specify the faction to join. /f join <faction-name>"); return true; } f = getFactionByName(args[1]); if (f == null) { player.sendMessage("§7[f] No faction found by that name."); return true; } // FIX FOR OLDER VER CLASS if (f.invites == null) f.invites = new HashSet<String>(); Iterator<String> i; i = f.invites.iterator(); while (i.hasNext()) { if (i.next().toLowerCase().equals(player.getName().toLowerCase())) { f.invites.remove(player.getName()); fp = new FactionPlayer(); fp.faction = f; fp.name = player.getName(); fp.rank = 0; f.players.put(player.getName(), fp); getServer().broadcastMessage(String.format("§7[f] %s just joined the faction [%s].", fp.name, f.name)); return true; } } player.sendMessage("You have no invintation to join that faction!"); return true; } if (cmd.equals("leave")) { FactionPlayer fp; FactionChunk fchunk; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } /// MAKE SURE WE ARE NOT STANDING ON FACTION CLAIMED LAND fchunk = getFactionChunk(player.getWorld(), player.getLocation().getBlockX(), player.getLocation().getBlockZ()); if (fchunk != null) { if (fchunk.faction == fp.faction) { player.sendMessage("§7[f] You must not be on your faction land when leaving the faction."); return true; } } /// MAKE SURE NOT EMPTY IF SO NEED TO USE DISBAND /// IF WE ARE OWNER WE NEED TO TRANSFER OWNERSHIP BEFORE WE LEAVE if (fp.faction.players.size() == 1) { // ENSURE THEY ARE HIGH ENOUGH FOR OWNER (CATCH BUGS KINDA) fp.rank = 1000; player.sendMessage("§7[f] You are the last player in faction use /f disband."); return true; } // IF THEY ARE THE OWNER HAND OWNERSHIP TO SOMEBODY ELSE KINDA AT RANDOM if (fp.rank == 1000) { Iterator<Entry<String, FactionPlayer>> i; FactionPlayer _fp; i = fp.faction.players.entrySet().iterator(); _fp = null; while (i.hasNext()) { _fp = i.next().getValue(); if (!fp.name.equals(_fp.name)) break; } _fp.rank = 1000; getServer().broadcastMessage(String.format("§7[f] Ownership of %s was handed to %s at random.", fp.faction.name, fp.name)); } getServer().broadcastMessage(String.format("§7[f] §a%s§r has left the faction §a%s§r!", fp.name, fp.faction.name)); fp.faction.players.remove(fp.name); return true; } if (cmd.equals("disband")) { FactionPlayer fp; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // MUST BE OWNER OF FACTION if (fp.rank < 1000) { player.sendMessage("§7[f] You are not owner of faction."); return true; } // why the hell am i doing this? --kmcguire fp.faction.chunks = new HashMap<String, Map<Long, FactionChunk>>(); getServer().broadcastMessage(String.format("§7[f] §a%s§r has disbanded the faction §a%s§r!", fp.name, fp.faction.name)); factions.remove(fp.faction.name.toLowerCase()); return true; } if (cmd.equals("listfriends")) { String friendName; Faction f; FactionPlayer fp; int frank; Iterator<Entry<String, Integer>> i; Entry<String, Integer> e; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.faction.friends == null) { player.sendMessage("§7[f] Faction has no friends."); return true; } i = fp.faction.friends.entrySet().iterator(); while (i.hasNext()) { e = i.next(); player.sendMessage(String.format("§7[f] %s => %d", e.getKey(), e.getValue())); } player.sendMessage("§7[f] Done"); return true; } if (cmd.equals("addfriend")) { String friendName; Faction f; FactionPlayer fp; int frank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (args.length < 3) { player.sendMessage("Syntax is /f addfriend <name> <rank>. Use again to change rank. Use /f remfriend to remove."); return true; } friendName = args[1]; frank = Integer.parseInt(args[2]); if (frank >= fp.rank) { player.sendMessage(String.format("§7[f] You can not set friend rank of %d because it is higher than your rank of %d.", frank, fp.rank)); return true; } if (fp.faction.friends == null) fp.faction.friends = new HashMap<String, Integer>(); fp.faction.friends.put(friendName, frank); sendFactionMessage(fp.faction, String.format("§7[f] Added friend %s at rank %d\n", friendName, frank)); return true; } if (cmd.equals("remfriend")) { String friendName; Faction f; FactionPlayer fp; int frank; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (args.length < 2) { player.sendMessage("Syntax is /f remfriend <name>."); return true; } friendName = args[1]; if (fp.faction.friends == null) fp.faction.friends = new HashMap<String, Integer>(); if (fp.faction.friends.containsKey(friendName)) { frank = fp.faction.friends.get(friendName); if (frank >= fp.rank) { player.sendMessage(String.format("§7[f] You can not remove friend with rank of %d because it is higher than your rank of %d.", frank, fp.rank)); return true; } } fp.faction.friends.remove(friendName); sendFactionMessage(fp.faction, String.format("§7[f] Removed friend %s\n", friendName)); return true; } if (cmd.equals("rename")) { FactionPlayer fp; String newName; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.rank < 1000) { player.sendMessage("§7[f] You need to be owner of this faction to change the rank!"); return true; } if (args.length < 2) { player.sendMessage("§7[f] The syntax is /f rename <newname>."); return true; } newName = args[1]; newName = sanitizeString(newName); if (newName.length() < 1) { player.sendMessage("§7[f] The name length is zero!"); return true; } getServer().broadcastMessage(String.format("§7[f] The faction §a%s§7 was renamed to §a%s§7.", fp.faction.name, newName)); synchronized (factions) { factions.remove(fp.faction.name.toLowerCase()); fp.faction.name = newName; factions.put(fp.faction.name.toLowerCase(), fp.faction); } return true; } if (cmd.equals("claim")) { FactionPlayer fp; int x, z; FactionChunk fchunk; double pow; if (player == null) { player.sendMessage("§7[f] uhoh plyer is null"); return true; } fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } // DO WE HAVE ENOUGH POWER? // NEED ENOUGH TO HOLD FOR 24 HOURS //pow = getFactionPower(fp.faction); //if (pow < ((fp.faction.chunks.size() + 1) * 24.0)) { // player.sendMessage("§7[f] The faction lacks needed power to claim land"); // return true; //} //smsg(String.format("blockx:%d", player.getLocation().getBlockX())); x = player.getLocation().getBlockX(); z = player.getLocation().getBlockZ(); fchunk = getFactionChunk(player.getWorld(), x >> 4, z >> 4); if (fchunk != null) { if (fchunk.faction == fp.faction) { player.sendMessage(String.format("§7[f] chunk already owned by your faction %s", fchunk.faction.name)); return true; } if (noGriefPerWorld.contains(player.getWorld().getName())) { player.sendMessage("§7[f] This world does not allow claiming of another faction's land!"); return true; } if (fchunk.faction != fp.faction) { if (getFactionPower(fchunk.faction) >= fchunk.faction.chunks.size()) { player.sendMessage(String.format("§7[f] faction %s has enough power to hold this claim", fchunk.faction.name)); return true; } getServer().broadcastMessage(String.format("§7[f] %s lost land claim to %s by %s", fchunk.faction.name, fp.faction.name, fp.name)); fchunk.faction.chunks.remove(getChunkLong(player.getWorld(), x >> 4, z >> 4)); } } fchunk = new FactionChunk(); fchunk.x = x >> 4; fchunk.z = z >> 4; fchunk.worldName = player.getWorld().getName(); fchunk.faction = fp.faction; fchunk.mrb = 500; // DEFAULT VALUES fchunk.mru = 250; fchunk.faction = fp.faction; if (fp.faction.chunks.get(player.getWorld().getName()) == null) { fp.faction.chunks.put(player.getWorld().getName(), new HashMap<Long, FactionChunk>()); } fp.faction.chunks.get(player.getWorld().getName()).put(LongHash.toLong(x >> 4, z >> 4), fchunk); //fp.faction.chunks.put(getChunkLong(player.getWorld(), x >> 4, z >> 4), fchunk); getServer().broadcastMessage(String.format("§7[f] %s of faction %s claimed land", fp.name, fp.faction.name)); return true; } if (cmd.equals("setrank")) { FactionPlayer fp; FactionPlayer mp; int nrank; if (args.length < 2) { player.sendMessage("§7[f] Not enough arguments /f rank <player> <rank>"); return true; } fp = getFactionPlayer(args[1]); mp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] Player is not in a faction."); return true; } if (mp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } if (fp.faction != mp.faction) { player.sendMessage("§7[f] You and player are not in the same faction."); } if ((fp.rank >= mp.rank) && (!player.isOp())) { player.sendMessage("§7[f] Player is already at equal or greater rank than you."); return true; } nrank = Integer.valueOf(args[2]); if ((nrank >= mp.rank) && (!player.isOp())) { player.sendMessage("§7[f] Rank you wish to set is equal or greater than you rank. [rejected]"); return true; } fp.rank = nrank; player.sendMessage(String.format("§7[f] rank for %s is now %d", args[1], nrank)); return true; } if (cmd.equals("unclaim")) { FactionPlayer fp; FactionChunk fchunk; int x, z; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } x = player.getLocation().getBlockX() >> 4; z = player.getLocation().getBlockZ() >> 4; fchunk = getFactionChunk(player.getWorld(), x, z); if (fchunk == null) { player.sendMessage("§7[f] This land chunk is owned by no one."); return true; } if (fchunk.faction != fp.faction) { player.sendMessage(String.format("§7[f] Your faction is %s, but this land belongs to %s.", fp.faction.name, fchunk.faction.name)); return true; } fp.faction.chunks.get(player.getWorld().getName()).remove(LongHash.toLong(x, z)); // UPDATE FACTION POWER getFactionPower(fp.faction); getServer().broadcastMessage(String.format("§7[f] %s of faction %s unclaimed land", fp.name, fp.faction.name)); return true; } if (cmd.equals("unclaimall")) { FactionPlayer fp; Iterator<Entry<Long, FactionChunk>> i; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } // IS OUR RANK GOOD ENOUGH? if (fp.rank < fp.faction.mrc) { player.sendMessage(String.format("§7[f] Your rank of %d is below the required rank of %d to claim/unclaim.", fp.rank, fp.faction.mrc)); return true; } fp.faction.chunks = new HashMap<String, Map<Long, FactionChunk>>(); getServer().broadcastMessage(String.format("§7[f] %s of faction %s declaimed all land", fp.name, fp.faction.name)); return true; } if (cmd.equals("chkcharge")) { int icnt; int mid; byte dat; double pts; icnt = player.getItemInHand().getAmount(); mid = player.getItemInHand().getTypeId(); dat = player.getItemInHand().getData().getData(); pts = (double)getEMC(mid, dat); player.sendMessage(String.format("§7[f] %f/item total:%f", pts, pts * icnt)); return true; } if (cmd.equals("charge")) { FactionPlayer fp; int icnt; double pts; int mid; byte dat; fp = getFactionPlayer(player.getName()); if (fp == null) { player.sendMessage("§7[f] You are not in a faction."); return true; } icnt = player.getItemInHand().getAmount(); mid = player.getItemInHand().getTypeId(); dat = player.getItemInHand().getData().getData(); //pts = (double)EEMaps.getEMC(mid, dat); pts = (double)getEMC(mid, dat); player.sendMessage(String.format("§7[f] Item value is %f", pts)); pts = pts * icnt; if (pts == 0.0d) { player.sendMessage("§7[f] Item(s) in hand yield no charge value."); return true; } player.setItemInHand(null); synchronized (fp.faction) { fp.faction.power += pts; } //getServer().broadcastMessage(String.format("§7[f] %s in %s charged faction power!", player.getDisplayName(), fp.faction.name)); sendFactionMessage(fp.faction, String.format("§7[f] %s charged the faction power by %f to %f.", player.getDisplayName(), pts, getFactionPower(fp.faction))); return true; } // SHOW FACTION INFORMATION ABOUT OUR FACTION // OR ANOTHER FACTION SPECIFIED if (cmd.equalsIgnoreCase("who")) { FactionPlayer fp; Faction f; Iterator<Entry<String, FactionPlayer>> iter; Entry<String, FactionPlayer> e; String o; fp = getFactionPlayer(player.getName()); if (args.length < 2 && fp == null) { player.sendMessage("§7[f] You must either specify a faction or be in a faction!"); return true; } if (args.length == 2) { f = getFactionByName(args[1]); if (f == null) { fp = getFactionPlayer(args[1]); if (fp == null) { player.sendMessage(String.format("§7[f] Could not find a faction or player named '%s'!", args[1])); return true; } f = fp.faction; } } else { f = fp.faction; } if (f == null) { player.sendMessage(String.format("§7[f] The faction %s could not be found.", args[1])); return true; } // display name and description player.sendMessage(String.format("§6Faction: §7%s", f.name)); //player.sendMessage(String.format("Description: %s", f.desc)); // display land/power/maxpower if (fp != null) { player.sendMessage(String.format("§6Land: §7%d §6Power/Hour: §7%d §6Power: §7%d", f.chunks.size(), (int)(landPowerCostPerHour * f.chunks.size()), (int)getFactionPower(f) )); player.sendMessage(String.format("§6TimeLeft: §7%d hours", (int)(getFactionPower(f) / (landPowerCostPerHour * f.chunks.size())) )); } else { player.sendMessage(String.format("§6Land: §7%d", f.chunks.size() )); } // mri, mrc, flags, mrz, mrtp, mrsh player.sendMessage(String.format( "§6MRI:§7%d §6MRC:§7%d §6FLAGS:§7%d §6MRZ:§7%d §6MRTP:§7%d §6MRSH:§7%d", f.mri, f.mrc, f.flags, (int)f.mrz, (int)f.mrtp, f.mrsh )); iter = f.players.entrySet().iterator(); o = "§6Members:§r"; while (iter.hasNext()) { e = iter.next(); if (getServer().getPlayer(e.getKey()) != null) { o = String.format("%s, §6%s§7[%d]", o, e.getKey(), e.getValue().rank); } else { o = String.format("%s, §7%s§7[%d]", o, e.getKey(), e.getValue().rank); } } player.sendMessage(o); return true; } if (cmd.equals("inspect")) { Location loc; FactionChunk fc; int bx, bz; loc = player.getLocation(); bx = loc.getBlockX() >> 4; bz = loc.getBlockZ() >> 4; fc = getFactionChunk(player.getWorld(), bx, bz); if (fc == null) { player.sendMessage("§7[f] §7Land not claimed by anyone."); return true; } player.sendMessage(String.format("§6Faction:§r%s §6MinimumBuildRank:§r%d §6MinimumUseRank:§r%d", fc.faction.name, fc.mrb, fc.mru)); return true; } displayHelp(player, args); return false; }
diff --git a/lucene/src/test/org/apache/lucene/util/LuceneTestCase.java b/lucene/src/test/org/apache/lucene/util/LuceneTestCase.java index 913d5ca90..ff2d062c6 100644 --- a/lucene/src/test/org/apache/lucene/util/LuceneTestCase.java +++ b/lucene/src/test/org/apache/lucene/util/LuceneTestCase.java @@ -1,1112 +1,1112 @@ package org.apache.lucene.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.lang.annotation.Documented; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Index; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.Field.TermVector; import org.apache.lucene.index.*; import org.apache.lucene.index.codecs.Codec; import org.apache.lucene.index.codecs.CodecProvider; import org.apache.lucene.index.codecs.mockintblock.MockFixedIntBlockCodec; import org.apache.lucene.index.codecs.mockintblock.MockVariableIntBlockCodec; import org.apache.lucene.index.codecs.mocksep.MockSepCodec; import org.apache.lucene.index.codecs.preflex.PreFlexCodec; import org.apache.lucene.index.codecs.preflexrw.PreFlexRWCodec; import org.apache.lucene.index.codecs.pulsing.PulsingCodec; import org.apache.lucene.index.codecs.simpletext.SimpleTextCodec; import org.apache.lucene.index.codecs.standard.StandardCodec; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.FieldCache; import org.apache.lucene.search.FieldCache.CacheEntry; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.LockFactory; import org.apache.lucene.store.MockDirectoryWrapper; import org.apache.lucene.util.FieldCacheSanityChecker.Insanity; import org.junit.*; import org.junit.rules.TestWatchman; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.manipulation.Filter; import org.junit.runner.manipulation.NoTestsRemainException; import org.junit.runner.notification.RunNotifier; import org.junit.runners.BlockJUnit4ClassRunner; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.InitializationError; /** * Base class for all Lucene unit tests, Junit3 or Junit4 variant. * <p> * </p> * <p> * If you * override either <code>setUp()</code> or * <code>tearDown()</code> in your unit test, make sure you * call <code>super.setUp()</code> and * <code>super.tearDown()</code> * </p> * * @After - replaces setup * @Before - replaces teardown * @Test - any public method with this annotation is a test case, regardless * of its name * <p> * <p> * See Junit4 <a href="http://junit.org/junit/javadoc/4.7/">documentation</a> for a complete list of features. * <p> * Import from org.junit rather than junit.framework. * <p> * You should be able to use this class anywhere you used LuceneTestCase * if you annotate your derived class correctly with the annotations above * @see #assertSaneFieldCaches(String) */ @RunWith(LuceneTestCase.LuceneTestCaseRunner.class) public abstract class LuceneTestCase extends Assert { /** * true iff tests are run in verbose mode. Note: if it is false, tests are not * expected to print any messages. */ public static final boolean VERBOSE = Boolean.getBoolean("tests.verbose"); /** Use this constant when creating Analyzers and any other version-dependent stuff. * <p><b>NOTE:</b> Change this when development starts for new Lucene version: */ public static final Version TEST_VERSION_CURRENT = Version.LUCENE_40; /** * If this is set, it is the only method that should run. */ static final String TEST_METHOD; /** Create indexes in this directory, optimally use a subdir, named after the test */ public static final File TEMP_DIR; static { String method = System.getProperty("testmethod", "").trim(); TEST_METHOD = method.length() == 0 ? null : method; String s = System.getProperty("tempDir", System.getProperty("java.io.tmpdir")); if (s == null) throw new RuntimeException("To run tests, you need to define system property 'tempDir' or 'java.io.tmpdir'."); TEMP_DIR = new File(s); TEMP_DIR.mkdirs(); } // by default we randomly pick a different codec for // each test case (non-J4 tests) and each test class (J4 // tests) /** Gets the codec to run tests with. */ public static final String TEST_CODEC = System.getProperty("tests.codec", "randomPerField"); /** Gets the locale to run tests with */ public static final String TEST_LOCALE = System.getProperty("tests.locale", "random"); /** Gets the timezone to run tests with */ public static final String TEST_TIMEZONE = System.getProperty("tests.timezone", "random"); /** Gets the directory to run tests with */ public static final String TEST_DIRECTORY = System.getProperty("tests.directory", "random"); /** Get the number of times to run tests */ public static final int TEST_ITER = Integer.parseInt(System.getProperty("tests.iter", "1")); /** Get the random seed for tests */ public static final String TEST_SEED = System.getProperty("tests.seed", "random"); /** whether or not nightly tests should run */ public static final boolean TEST_NIGHTLY = Boolean.parseBoolean(System.getProperty("tests.nightly", "false")); /** the line file used by LineFileDocs */ public static final String TEST_LINE_DOCS_FILE = System.getProperty("tests.linedocsfile", "europarl.lines.txt.gz"); private static final Pattern codecWithParam = Pattern.compile("(.*)\\(\\s*(\\d+)\\s*\\)"); /** * A random multiplier which you should use when writing random tests: * multiply it by the number of iterations */ public static final int RANDOM_MULTIPLIER = Integer.parseInt(System.getProperty("tests.multiplier", "1")); private int savedBoolMaxClauseCount; private volatile Thread.UncaughtExceptionHandler savedUncaughtExceptionHandler = null; /** Used to track if setUp and tearDown are called correctly from subclasses */ private boolean setup; /** * Some tests expect the directory to contain a single segment, and want to do tests on that segment's reader. * This is an utility method to help them. */ public static SegmentReader getOnlySegmentReader(IndexReader reader) { if (reader instanceof SegmentReader) return (SegmentReader) reader; IndexReader[] subReaders = reader.getSequentialSubReaders(); if (subReaders.length != 1) throw new IllegalArgumentException(reader + " has " + subReaders.length + " segments instead of exactly one"); return (SegmentReader) subReaders[0]; } private static class UncaughtExceptionEntry { public final Thread thread; public final Throwable exception; public UncaughtExceptionEntry(Thread thread, Throwable exception) { this.thread = thread; this.exception = exception; } } private List<UncaughtExceptionEntry> uncaughtExceptions = Collections.synchronizedList(new ArrayList<UncaughtExceptionEntry>()); // saves default codec: we do this statically as many build indexes in @beforeClass private static String savedDefaultCodec; // default codec: not set when we use a per-field provider. private static Codec codec; // default codec provider private static CodecProvider savedCodecProvider; private static Locale locale; private static Locale savedLocale; private static TimeZone timeZone; private static TimeZone savedTimeZone; private static Map<MockDirectoryWrapper,StackTraceElement[]> stores; private static final String[] TEST_CODECS = new String[] {"MockSep", "MockFixedIntBlock", "MockVariableIntBlock"}; private static void swapCodec(Codec c, CodecProvider cp) { Codec prior = null; try { prior = cp.lookup(c.name); } catch (IllegalArgumentException iae) { } if (prior != null) { cp.unregister(prior); } cp.register(c); } // returns current default codec static Codec installTestCodecs(String codec, CodecProvider cp) { savedDefaultCodec = cp.getDefaultFieldCodec(); final boolean codecHasParam; int codecParam = 0; if (codec.equals("randomPerField")) { // lie codec = "Standard"; codecHasParam = false; } else if (codec.equals("random")) { codec = pickRandomCodec(random); codecHasParam = false; } else { Matcher m = codecWithParam.matcher(codec); if (m.matches()) { // codec has a fixed param codecHasParam = true; codec = m.group(1); codecParam = Integer.parseInt(m.group(2)); } else { codecHasParam = false; } } cp.setDefaultFieldCodec(codec); if (codec.equals("PreFlex")) { // If we're running w/ PreFlex codec we must swap in the // test-only PreFlexRW codec (since core PreFlex can // only read segments): swapCodec(new PreFlexRWCodec(), cp); } swapCodec(new MockSepCodec(), cp); swapCodec(new PulsingCodec(codecHasParam && "Pulsing".equals(codec) ? codecParam : _TestUtil.nextInt(random, 1, 20)), cp); swapCodec(new MockFixedIntBlockCodec(codecHasParam && "MockFixedIntBlock".equals(codec) ? codecParam : _TestUtil.nextInt(random, 1, 2000)), cp); // baseBlockSize cannot be over 127: swapCodec(new MockVariableIntBlockCodec(codecHasParam && "MockVariableIntBlock".equals(codec) ? codecParam : _TestUtil.nextInt(random, 1, 127)), cp); return cp.lookup(codec); } // returns current PreFlex codec static void removeTestCodecs(Codec codec, CodecProvider cp) { if (codec.name.equals("PreFlex")) { final Codec preFlex = cp.lookup("PreFlex"); if (preFlex != null) { cp.unregister(preFlex); } cp.register(new PreFlexCodec()); } cp.unregister(cp.lookup("MockSep")); cp.unregister(cp.lookup("MockFixedIntBlock")); cp.unregister(cp.lookup("MockVariableIntBlock")); swapCodec(new PulsingCodec(1), cp); cp.setDefaultFieldCodec(savedDefaultCodec); } // randomly picks from core and test codecs static String pickRandomCodec(Random rnd) { int idx = rnd.nextInt(CodecProvider.CORE_CODECS.length + TEST_CODECS.length); if (idx < CodecProvider.CORE_CODECS.length) { return CodecProvider.CORE_CODECS[idx]; } else { return TEST_CODECS[idx - CodecProvider.CORE_CODECS.length]; } } private static class TwoLongs { public final long l1, l2; public TwoLongs(long l1, long l2) { this.l1 = l1; this.l2 = l2; } @Override public String toString() { return l1 + ":" + l2; } public static TwoLongs fromString(String s) { final int i = s.indexOf(':'); assert i != -1; return new TwoLongs(Long.parseLong(s.substring(0, i)), Long.parseLong(s.substring(1+i))); } } /** @deprecated (4.0) until we fix no-fork problems in solr tests */ @Deprecated private static List<String> testClassesRun = new ArrayList<String>(); @BeforeClass public static void beforeClassLuceneTestCaseJ4() { staticSeed = "random".equals(TEST_SEED) ? seedRand.nextLong() : TwoLongs.fromString(TEST_SEED).l1; random.setSeed(staticSeed); stores = Collections.synchronizedMap(new IdentityHashMap<MockDirectoryWrapper,StackTraceElement[]>()); savedCodecProvider = CodecProvider.getDefault(); if ("randomPerField".equals(TEST_CODEC)) { if (random.nextInt(4) == 0) { // preflex-only setup codec = installTestCodecs("PreFlex", CodecProvider.getDefault()); } else { // per-field setup CodecProvider.setDefault(new RandomCodecProvider(random)); codec = installTestCodecs(TEST_CODEC, CodecProvider.getDefault()); } } else { // ordinary setup codec = installTestCodecs(TEST_CODEC, CodecProvider.getDefault()); } savedLocale = Locale.getDefault(); locale = TEST_LOCALE.equals("random") ? randomLocale(random) : localeForName(TEST_LOCALE); Locale.setDefault(locale); savedTimeZone = TimeZone.getDefault(); timeZone = TEST_TIMEZONE.equals("random") ? randomTimeZone(random) : TimeZone.getTimeZone(TEST_TIMEZONE); TimeZone.setDefault(timeZone); testsFailed = false; } @AfterClass public static void afterClassLuceneTestCaseJ4() { String codecDescription; CodecProvider cp = CodecProvider.getDefault(); if ("randomPerField".equals(TEST_CODEC)) { if (cp instanceof RandomCodecProvider) codecDescription = cp.toString(); else codecDescription = "PreFlex"; } else { codecDescription = codec.toString(); } if (CodecProvider.getDefault() == savedCodecProvider) removeTestCodecs(codec, CodecProvider.getDefault()); CodecProvider.setDefault(savedCodecProvider); Locale.setDefault(savedLocale); TimeZone.setDefault(savedTimeZone); System.clearProperty("solr.solr.home"); System.clearProperty("solr.data.dir"); // now look for unclosed resources if (!testsFailed) for (MockDirectoryWrapper d : stores.keySet()) { if (d.isOpen()) { StackTraceElement elements[] = stores.get(d); // Look for the first class that is not LuceneTestCase that requested // a Directory. The first two items are of Thread's, so skipping over // them. StackTraceElement element = null; for (int i = 2; i < elements.length; i++) { StackTraceElement ste = elements[i]; if (ste.getClassName().indexOf("LuceneTestCase") == -1) { element = ste; break; } } fail("directory of test was not closed, opened from: " + element); } } stores = null; // if verbose or tests failed, report some information back if (VERBOSE || testsFailed) System.out.println("NOTE: test params are: codec=" + codecDescription + ", locale=" + locale + ", timezone=" + (timeZone == null ? "(null)" : timeZone.getID())); if (testsFailed) { System.err.println("NOTE: all tests run in this JVM:"); System.err.println(Arrays.toString(testClassesRun.toArray())); } } private static boolean testsFailed; /* true if any tests failed */ // This is how we get control when errors occur. // Think of this as start/end/success/failed // events. @Rule public final TestWatchman intercept = new TestWatchman() { @Override public void failed(Throwable e, FrameworkMethod method) { // org.junit.internal.AssumptionViolatedException in older releases // org.junit.Assume.AssumptionViolatedException in recent ones if (e.getClass().getName().endsWith("AssumptionViolatedException")) { if (e.getCause() instanceof TestIgnoredException) e = e.getCause(); System.err.print("NOTE: Assume failed in '" + method.getName() + "' (ignored):"); if (VERBOSE) { System.err.println(); e.printStackTrace(System.err); } else { System.err.print(" "); System.err.println(e.getMessage()); } } else { testsFailed = true; reportAdditionalFailureInfo(); } super.failed(e, method); } @Override public void starting(FrameworkMethod method) { // set current method name for logging LuceneTestCase.this.name = method.getName(); super.starting(method); } }; @Before public void setUp() throws Exception { seed = "random".equals(TEST_SEED) ? seedRand.nextLong() : TwoLongs.fromString(TEST_SEED).l2; random.setSeed(seed); assertFalse("ensure your tearDown() calls super.tearDown()!!!", setup); setup = true; savedUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { uncaughtExceptions.add(new UncaughtExceptionEntry(t, e)); if (savedUncaughtExceptionHandler != null) savedUncaughtExceptionHandler.uncaughtException(t, e); } }); ConcurrentMergeScheduler.setTestMode(); savedBoolMaxClauseCount = BooleanQuery.getMaxClauseCount(); } /** * Forcible purges all cache entries from the FieldCache. * <p> * This method will be called by tearDown to clean up FieldCache.DEFAULT. * If a (poorly written) test has some expectation that the FieldCache * will persist across test methods (ie: a static IndexReader) this * method can be overridden to do nothing. * </p> * * @see FieldCache#purgeAllCaches() */ protected void purgeFieldCache(final FieldCache fc) { fc.purgeAllCaches(); } protected String getTestLabel() { return getClass().getName() + "." + getName(); } @After public void tearDown() throws Exception { assertTrue("ensure your setUp() calls super.setUp()!!!", setup); setup = false; BooleanQuery.setMaxClauseCount(savedBoolMaxClauseCount); try { if (!uncaughtExceptions.isEmpty()) { testsFailed = true; reportAdditionalFailureInfo(); System.err.println("The following exceptions were thrown by threads:"); for (UncaughtExceptionEntry entry : uncaughtExceptions) { System.err.println("*** Thread: " + entry.thread.getName() + " ***"); entry.exception.printStackTrace(System.err); } fail("Some threads threw uncaught exceptions!"); } // calling assertSaneFieldCaches here isn't as useful as having test // classes call it directly from the scope where the index readers // are used, because they could be gc'ed just before this tearDown // method is called. // // But it's better then nothing. // // If you are testing functionality that you know for a fact // "violates" FieldCache sanity, then you should either explicitly // call purgeFieldCache at the end of your test method, or refactor // your Test class so that the inconsistant FieldCache usages are // isolated in distinct test methods assertSaneFieldCaches(getTestLabel()); if (ConcurrentMergeScheduler.anyUnhandledExceptions()) { // Clear the failure so that we don't just keep // failing subsequent test cases ConcurrentMergeScheduler.clearUnhandledExceptions(); fail("ConcurrentMergeScheduler hit unhandled exceptions"); } } finally { purgeFieldCache(FieldCache.DEFAULT); } Thread.setDefaultUncaughtExceptionHandler(savedUncaughtExceptionHandler); } /** * Asserts that FieldCacheSanityChecker does not detect any * problems with FieldCache.DEFAULT. * <p> * If any problems are found, they are logged to System.err * (allong with the msg) when the Assertion is thrown. * </p> * <p> * This method is called by tearDown after every test method, * however IndexReaders scoped inside test methods may be garbage * collected prior to this method being called, causing errors to * be overlooked. Tests are encouraged to keep their IndexReaders * scoped at the class level, or to explicitly call this method * directly in the same scope as the IndexReader. * </p> * * @see FieldCacheSanityChecker */ protected void assertSaneFieldCaches(final String msg) { final CacheEntry[] entries = FieldCache.DEFAULT.getCacheEntries(); Insanity[] insanity = null; try { try { insanity = FieldCacheSanityChecker.checkSanity(entries); } catch (RuntimeException e) { dumpArray(msg + ": FieldCache", entries, System.err); throw e; } assertEquals(msg + ": Insane FieldCache usage(s) found", 0, insanity.length); insanity = null; } finally { // report this in the event of any exception/failure // if no failure, then insanity will be null anyway if (null != insanity) { dumpArray(msg + ": Insane FieldCache usage(s)", insanity, System.err); } } } // @deprecated (4.0) These deprecated methods should be removed soon, when all tests using no Epsilon are fixed: @Deprecated static public void assertEquals(double expected, double actual) { assertEquals(null, expected, actual); } @Deprecated static public void assertEquals(String message, double expected, double actual) { assertEquals(message, Double.valueOf(expected), Double.valueOf(actual)); } @Deprecated static public void assertEquals(float expected, float actual) { assertEquals(null, expected, actual); } @Deprecated static public void assertEquals(String message, float expected, float actual) { assertEquals(message, Float.valueOf(expected), Float.valueOf(actual)); } // Replacement for Assume jUnit class, so we can add a message with explanation: private static final class TestIgnoredException extends RuntimeException { TestIgnoredException(String msg) { super(msg); } TestIgnoredException(String msg, Throwable t) { super(msg, t); } @Override public String getMessage() { StringBuilder sb = new StringBuilder(super.getMessage()); if (getCause() != null) sb.append(" - ").append(getCause()); return sb.toString(); } // only this one is called by our code, exception is not used outside this class: @Override public void printStackTrace(PrintStream s) { if (getCause() != null) { s.println(super.toString() + " - Caused by:"); getCause().printStackTrace(s); } else { super.printStackTrace(s); } } } public static void assumeTrue(String msg, boolean b) { Assume.assumeNoException(b ? null : new TestIgnoredException(msg)); } public static void assumeFalse(String msg, boolean b) { assumeTrue(msg, !b); } public static void assumeNoException(String msg, Exception e) { Assume.assumeNoException(e == null ? null : new TestIgnoredException(msg, e)); } public static <T> Set<T> asSet(T... args) { return new HashSet<T>(Arrays.asList(args)); } /** * Convinience method for logging an iterator. * * @param label String logged before/after the items in the iterator * @param iter Each next() is toString()ed and logged on it's own line. If iter is null this is logged differnetly then an empty iterator. * @param stream Stream to log messages to. */ public static void dumpIterator(String label, Iterator<?> iter, PrintStream stream) { stream.println("*** BEGIN " + label + " ***"); if (null == iter) { stream.println(" ... NULL ..."); } else { while (iter.hasNext()) { stream.println(iter.next().toString()); } } stream.println("*** END " + label + " ***"); } /** * Convinience method for logging an array. Wraps the array in an iterator and delegates * * @see #dumpIterator(String,Iterator,PrintStream) */ public static void dumpArray(String label, Object[] objs, PrintStream stream) { Iterator<?> iter = (null == objs) ? null : Arrays.asList(objs).iterator(); dumpIterator(label, iter, stream); } /** create a new index writer config with random defaults */ public static IndexWriterConfig newIndexWriterConfig(Version v, Analyzer a) { return newIndexWriterConfig(random, v, a); } public static IndexWriterConfig newIndexWriterConfig(Random r, Version v, Analyzer a) { IndexWriterConfig c = new IndexWriterConfig(v, a); if (r.nextBoolean()) { c.setMergeScheduler(new SerialMergeScheduler()); } if (r.nextBoolean()) { if (r.nextInt(20) == 17) { c.setMaxBufferedDocs(2); } else { c.setMaxBufferedDocs(_TestUtil.nextInt(r, 2, 1000)); } } if (r.nextBoolean()) { c.setTermIndexInterval(_TestUtil.nextInt(r, 1, 1000)); } if (r.nextBoolean()) { c.setMaxThreadStates(_TestUtil.nextInt(r, 1, 20)); } c.setMergePolicy(newLogMergePolicy(r)); c.setReaderPooling(r.nextBoolean()); c.setReaderTermsIndexDivisor(_TestUtil.nextInt(r, 1, 4)); return c; } public static LogMergePolicy newLogMergePolicy() { return newLogMergePolicy(random); } public static LogMergePolicy newLogMergePolicy(Random r) { LogMergePolicy logmp = r.nextBoolean() ? new LogDocMergePolicy() : new LogByteSizeMergePolicy(); logmp.setUseCompoundDocStore(r.nextBoolean()); logmp.setUseCompoundFile(r.nextBoolean()); logmp.setCalibrateSizeByDeletes(r.nextBoolean()); if (r.nextInt(3) == 2) { logmp.setMergeFactor(2); } else { logmp.setMergeFactor(_TestUtil.nextInt(r, 2, 20)); } return logmp; } public static LogMergePolicy newLogMergePolicy(boolean useCFS) { LogMergePolicy logmp = newLogMergePolicy(); logmp.setUseCompoundFile(useCFS); logmp.setUseCompoundDocStore(useCFS); return logmp; } public static LogMergePolicy newLogMergePolicy(boolean useCFS, int mergeFactor) { LogMergePolicy logmp = newLogMergePolicy(); logmp.setUseCompoundFile(useCFS); logmp.setUseCompoundDocStore(useCFS); logmp.setMergeFactor(mergeFactor); return logmp; } public static LogMergePolicy newLogMergePolicy(int mergeFactor) { LogMergePolicy logmp = newLogMergePolicy(); logmp.setMergeFactor(mergeFactor); return logmp; } /** * Returns a new Directory instance. Use this when the test does not * care about the specific Directory implementation (most tests). * <p> * The Directory is wrapped with {@link MockDirectoryWrapper}. * By default this means it will be picky, such as ensuring that you * properly close it and all open files in your test. It will emulate * some features of Windows, such as not allowing open files to be * overwritten. */ public static MockDirectoryWrapper newDirectory() throws IOException { return newDirectory(random); } public static MockDirectoryWrapper newDirectory(Random r) throws IOException { Directory impl = newDirectoryImpl(r, TEST_DIRECTORY); MockDirectoryWrapper dir = new MockDirectoryWrapper(r, impl); stores.put(dir, Thread.currentThread().getStackTrace()); return dir; } /** * Returns a new Directory instance, with contents copied from the * provided directory. See {@link #newDirectory()} for more * information. */ public static MockDirectoryWrapper newDirectory(Directory d) throws IOException { return newDirectory(random, d); } /** Returns a new FSDirectory instance over the given file, which must be a folder. */ public static MockDirectoryWrapper newFSDirectory(File f) throws IOException { return newFSDirectory(f, null); } /** Returns a new FSDirectory instance over the given file, which must be a folder. */ public static MockDirectoryWrapper newFSDirectory(File f, LockFactory lf) throws IOException { String fsdirClass = TEST_DIRECTORY; if (fsdirClass.equals("random")) { fsdirClass = FS_DIRECTORIES[random.nextInt(FS_DIRECTORIES.length)]; } if (fsdirClass.indexOf(".") == -1) {// if not fully qualified, assume .store fsdirClass = "org.apache.lucene.store." + fsdirClass; } Class<? extends FSDirectory> clazz; try { try { clazz = Class.forName(fsdirClass).asSubclass(FSDirectory.class); } catch (ClassCastException e) { // TEST_DIRECTORY is not a sub-class of FSDirectory, so draw one at random fsdirClass = FS_DIRECTORIES[random.nextInt(FS_DIRECTORIES.length)]; clazz = Class.forName(fsdirClass).asSubclass(FSDirectory.class); } MockDirectoryWrapper dir = new MockDirectoryWrapper(random, newFSDirectoryImpl(clazz, f, lf)); stores.put(dir, Thread.currentThread().getStackTrace()); return dir; } catch (Exception e) { throw new RuntimeException(e); } } public static MockDirectoryWrapper newDirectory(Random r, Directory d) throws IOException { Directory impl = newDirectoryImpl(r, TEST_DIRECTORY); for (String file : d.listAll()) { d.copy(impl, file, file); } MockDirectoryWrapper dir = new MockDirectoryWrapper(r, impl); stores.put(dir, Thread.currentThread().getStackTrace()); return dir; } public static Field newField(String name, String value, Index index) { return newField(random, name, value, index); } public static Field newField(String name, String value, Store store, Index index) { return newField(random, name, value, store, index); } public static Field newField(String name, String value, Store store, Index index, TermVector tv) { return newField(random, name, value, store, index, tv); } public static Field newField(Random random, String name, String value, Index index) { return newField(random, name, value, Store.NO, index); } public static Field newField(Random random, String name, String value, Store store, Index index) { return newField(random, name, value, store, index, TermVector.NO); } public static Field newField(Random random, String name, String value, Store store, Index index, TermVector tv) { if (!index.isIndexed()) return new Field(name, value, store, index); if (!store.isStored() && random.nextBoolean()) store = Store.YES; // randomly store it tv = randomTVSetting(random, tv); return new Field(name, value, store, index, tv); } static final TermVector tvSettings[] = { TermVector.NO, TermVector.YES, TermVector.WITH_OFFSETS, TermVector.WITH_POSITIONS, TermVector.WITH_POSITIONS_OFFSETS }; private static TermVector randomTVSetting(Random random, TermVector minimum) { switch(minimum) { case NO: return tvSettings[_TestUtil.nextInt(random, 0, tvSettings.length-1)]; case YES: return tvSettings[_TestUtil.nextInt(random, 1, tvSettings.length-1)]; case WITH_OFFSETS: return random.nextBoolean() ? TermVector.WITH_OFFSETS : TermVector.WITH_POSITIONS_OFFSETS; case WITH_POSITIONS: return random.nextBoolean() ? TermVector.WITH_POSITIONS : TermVector.WITH_POSITIONS_OFFSETS; default: return TermVector.WITH_POSITIONS_OFFSETS; } } /** return a random Locale from the available locales on the system */ public static Locale randomLocale(Random random) { Locale locales[] = Locale.getAvailableLocales(); return locales[random.nextInt(locales.length)]; } /** return a random TimeZone from the available timezones on the system */ public static TimeZone randomTimeZone(Random random) { String tzIds[] = TimeZone.getAvailableIDs(); return TimeZone.getTimeZone(tzIds[random.nextInt(tzIds.length)]); } /** return a Locale object equivalent to its programmatic name */ public static Locale localeForName(String localeName) { String elements[] = localeName.split("\\_"); switch(elements.length) { case 3: return new Locale(elements[0], elements[1], elements[2]); case 2: return new Locale(elements[0], elements[1]); case 1: return new Locale(elements[0]); default: throw new IllegalArgumentException("Invalid Locale: " + localeName); } } private static final String FS_DIRECTORIES[] = { "SimpleFSDirectory", "NIOFSDirectory", "MMapDirectory" }; private static final String CORE_DIRECTORIES[] = { "RAMDirectory", FS_DIRECTORIES[0], FS_DIRECTORIES[1], FS_DIRECTORIES[2] }; public static String randomDirectory(Random random) { if (random.nextInt(10) == 0) { return CORE_DIRECTORIES[random.nextInt(CORE_DIRECTORIES.length)]; } else { return "RAMDirectory"; } } private static Directory newFSDirectoryImpl( Class<? extends FSDirectory> clazz, File file, LockFactory lockFactory) throws IOException { try { // Assuming every FSDirectory has a ctor(File), but not all may take a // LockFactory too, so setting it afterwards. Constructor<? extends FSDirectory> ctor = clazz.getConstructor(File.class); FSDirectory d = ctor.newInstance(file); if (lockFactory != null) { d.setLockFactory(lockFactory); } return d; } catch (Exception e) { return FSDirectory.open(file); } } static Directory newDirectoryImpl(Random random, String clazzName) { if (clazzName.equals("random")) clazzName = randomDirectory(random); if (clazzName.indexOf(".") == -1) // if not fully qualified, assume .store clazzName = "org.apache.lucene.store." + clazzName; try { final Class<? extends Directory> clazz = Class.forName(clazzName).asSubclass(Directory.class); // If it is a FSDirectory type, try its ctor(File) if (FSDirectory.class.isAssignableFrom(clazz)) { final File tmpFile = File.createTempFile("test", "tmp", TEMP_DIR); tmpFile.delete(); tmpFile.mkdir(); return newFSDirectoryImpl(clazz.asSubclass(FSDirectory.class), tmpFile, null); } // try empty ctor return clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public String getName() { return this.name; } /** Gets a resource from the classpath as {@link File}. This method should only be used, * if a real file is needed. To get a stream, code should prefer * {@link Class#getResourceAsStream} using {@code this.getClass()}. */ protected File getDataFile(String name) throws IOException { try { return new File(this.getClass().getResource(name).toURI()); } catch (Exception e) { throw new IOException("Cannot find resource: " + name); } } // We get here from InterceptTestCaseEvents on the 'failed' event.... public void reportAdditionalFailureInfo() { System.out.println("NOTE: reproduce with: ant test -Dtestcase=" + getClass().getSimpleName() + " -Dtestmethod=" + getName() + " -Dtests.seed=" + new TwoLongs(staticSeed, seed) + reproduceWithExtraParams()); } // extra params that were overridden needed to reproduce the command private String reproduceWithExtraParams() { StringBuilder sb = new StringBuilder(); if (!TEST_CODEC.equals("random")) sb.append(" -Dtests.codec=").append(TEST_CODEC); if (!TEST_LOCALE.equals("random")) sb.append(" -Dtests.locale=").append(TEST_LOCALE); if (!TEST_TIMEZONE.equals("random")) sb.append(" -Dtests.timezone=").append(TEST_TIMEZONE); if (!TEST_DIRECTORY.equals("random")) sb.append(" -Dtests.directory=").append(TEST_DIRECTORY); if (RANDOM_MULTIPLIER > 1) sb.append(" -Dtests.multiplier=").append(RANDOM_MULTIPLIER); return sb.toString(); } // recorded seed: for beforeClass private static long staticSeed; // seed for individual test methods, changed in @before private long seed; private static final Random seedRand = new Random(); protected static final Random random = new Random(); private String name = "<unknown>"; /** * Annotation for tests that should only be run during nightly builds. */ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface Nightly {} /** optionally filters the tests to be run by TEST_METHOD */ public static class LuceneTestCaseRunner extends BlockJUnit4ClassRunner { private List<FrameworkMethod> testMethods; @Override protected List<FrameworkMethod> computeTestMethods() { if (testMethods != null) return testMethods; testClassesRun.add(getTestClass().getJavaClass().getSimpleName()); - testMethods = getTestClass().getAnnotatedMethods(Test.class); + testMethods = new ArrayList<FrameworkMethod>(); for (Method m : getTestClass().getJavaClass().getMethods()) { // check if the current test's class has methods annotated with @Ignore final Ignore ignored = m.getAnnotation(Ignore.class); if (ignored != null && !m.getName().equals("alwaysIgnoredTestMethod")) { System.err.println("NOTE: Ignoring test method '" + m.getName() + "': " + ignored.value()); } // add methods starting with "test" final int mod = m.getModifiers(); - if (m.getName().startsWith("test") && - m.getAnnotation(Test.class) == null && + if (m.getAnnotation(Test.class) != null || + (m.getName().startsWith("test") && !Modifier.isAbstract(mod) && m.getParameterTypes().length == 0 && - m.getReturnType() == Void.TYPE) + m.getReturnType() == Void.TYPE)) { if (Modifier.isStatic(mod)) throw new RuntimeException("Test methods must not be static."); testMethods.add(new FrameworkMethod(m)); } } if (testMethods.isEmpty()) { throw new RuntimeException("No runnable methods!"); } if (TEST_NIGHTLY == false) { if (getTestClass().getJavaClass().isAnnotationPresent(Nightly.class)) { /* the test class is annotated with nightly, remove all methods */ String className = getTestClass().getJavaClass().getSimpleName(); System.err.println("NOTE: Ignoring nightly-only test class '" + className + "'"); testMethods.clear(); } else { /* remove all nightly-only methods */ for (int i = 0; i < testMethods.size(); i++) { final FrameworkMethod m = testMethods.get(i); if (m.getAnnotation(Nightly.class) != null) { System.err.println("NOTE: Ignoring nightly-only test method '" + m.getName() + "'"); testMethods.remove(i--); } } } /* dodge a possible "no-runnable methods" exception by adding a fake ignored test */ if (testMethods.isEmpty()) { try { testMethods.add(new FrameworkMethod(LuceneTestCase.class.getMethod("alwaysIgnoredTestMethod"))); } catch (Exception e) { throw new RuntimeException(e); } } } return testMethods; } @Override protected void runChild(FrameworkMethod arg0, RunNotifier arg1) { for (int i = 0; i < TEST_ITER; i++) super.runChild(arg0, arg1); } public LuceneTestCaseRunner(Class<?> clazz) throws InitializationError { super(clazz); Filter f = new Filter() { @Override public String describe() { return "filters according to TEST_METHOD"; } @Override public boolean shouldRun(Description d) { return TEST_METHOD == null || d.getMethodName().equals(TEST_METHOD); } }; try { f.apply(this); } catch (NoTestsRemainException e) { throw new RuntimeException(e); } } } private static class RandomCodecProvider extends CodecProvider { private List<Codec> knownCodecs = new ArrayList<Codec>(); private Map<String,Codec> previousMappings = new HashMap<String,Codec>(); private final int perFieldSeed; RandomCodecProvider(Random random) { this.perFieldSeed = random.nextInt(); register(new StandardCodec()); register(new PreFlexCodec()); register(new PulsingCodec(1)); register(new SimpleTextCodec()); Collections.shuffle(knownCodecs, random); } @Override public synchronized void register(Codec codec) { if (!codec.name.equals("PreFlex")) knownCodecs.add(codec); super.register(codec); } @Override public synchronized void unregister(Codec codec) { knownCodecs.remove(codec); super.unregister(codec); } @Override public synchronized String getFieldCodec(String name) { Codec codec = previousMappings.get(name); if (codec == null) { codec = knownCodecs.get(Math.abs(perFieldSeed ^ name.hashCode()) % knownCodecs.size()); previousMappings.put(name, codec); } return codec.name; } @Override public String toString() { return "RandomCodecProvider: " + previousMappings.toString(); } } @Ignore("just a hack") public final void alwaysIgnoredTestMethod() {} }
false
true
protected List<FrameworkMethod> computeTestMethods() { if (testMethods != null) return testMethods; testClassesRun.add(getTestClass().getJavaClass().getSimpleName()); testMethods = getTestClass().getAnnotatedMethods(Test.class); for (Method m : getTestClass().getJavaClass().getMethods()) { // check if the current test's class has methods annotated with @Ignore final Ignore ignored = m.getAnnotation(Ignore.class); if (ignored != null && !m.getName().equals("alwaysIgnoredTestMethod")) { System.err.println("NOTE: Ignoring test method '" + m.getName() + "': " + ignored.value()); } // add methods starting with "test" final int mod = m.getModifiers(); if (m.getName().startsWith("test") && m.getAnnotation(Test.class) == null && !Modifier.isAbstract(mod) && m.getParameterTypes().length == 0 && m.getReturnType() == Void.TYPE) { if (Modifier.isStatic(mod)) throw new RuntimeException("Test methods must not be static."); testMethods.add(new FrameworkMethod(m)); } } if (testMethods.isEmpty()) { throw new RuntimeException("No runnable methods!"); } if (TEST_NIGHTLY == false) { if (getTestClass().getJavaClass().isAnnotationPresent(Nightly.class)) { /* the test class is annotated with nightly, remove all methods */ String className = getTestClass().getJavaClass().getSimpleName(); System.err.println("NOTE: Ignoring nightly-only test class '" + className + "'"); testMethods.clear(); } else { /* remove all nightly-only methods */ for (int i = 0; i < testMethods.size(); i++) { final FrameworkMethod m = testMethods.get(i); if (m.getAnnotation(Nightly.class) != null) { System.err.println("NOTE: Ignoring nightly-only test method '" + m.getName() + "'"); testMethods.remove(i--); } } } /* dodge a possible "no-runnable methods" exception by adding a fake ignored test */ if (testMethods.isEmpty()) { try { testMethods.add(new FrameworkMethod(LuceneTestCase.class.getMethod("alwaysIgnoredTestMethod"))); } catch (Exception e) { throw new RuntimeException(e); } } } return testMethods; }
protected List<FrameworkMethod> computeTestMethods() { if (testMethods != null) return testMethods; testClassesRun.add(getTestClass().getJavaClass().getSimpleName()); testMethods = new ArrayList<FrameworkMethod>(); for (Method m : getTestClass().getJavaClass().getMethods()) { // check if the current test's class has methods annotated with @Ignore final Ignore ignored = m.getAnnotation(Ignore.class); if (ignored != null && !m.getName().equals("alwaysIgnoredTestMethod")) { System.err.println("NOTE: Ignoring test method '" + m.getName() + "': " + ignored.value()); } // add methods starting with "test" final int mod = m.getModifiers(); if (m.getAnnotation(Test.class) != null || (m.getName().startsWith("test") && !Modifier.isAbstract(mod) && m.getParameterTypes().length == 0 && m.getReturnType() == Void.TYPE)) { if (Modifier.isStatic(mod)) throw new RuntimeException("Test methods must not be static."); testMethods.add(new FrameworkMethod(m)); } } if (testMethods.isEmpty()) { throw new RuntimeException("No runnable methods!"); } if (TEST_NIGHTLY == false) { if (getTestClass().getJavaClass().isAnnotationPresent(Nightly.class)) { /* the test class is annotated with nightly, remove all methods */ String className = getTestClass().getJavaClass().getSimpleName(); System.err.println("NOTE: Ignoring nightly-only test class '" + className + "'"); testMethods.clear(); } else { /* remove all nightly-only methods */ for (int i = 0; i < testMethods.size(); i++) { final FrameworkMethod m = testMethods.get(i); if (m.getAnnotation(Nightly.class) != null) { System.err.println("NOTE: Ignoring nightly-only test method '" + m.getName() + "'"); testMethods.remove(i--); } } } /* dodge a possible "no-runnable methods" exception by adding a fake ignored test */ if (testMethods.isEmpty()) { try { testMethods.add(new FrameworkMethod(LuceneTestCase.class.getMethod("alwaysIgnoredTestMethod"))); } catch (Exception e) { throw new RuntimeException(e); } } } return testMethods; }
diff --git a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/CellArea.java b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/CellArea.java index e2fcfd84a..978a0361b 100644 --- a/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/CellArea.java +++ b/plugins/org.eclipse.birt.report.engine/src/org/eclipse/birt/report/engine/nLayout/area/impl/CellArea.java @@ -1,252 +1,252 @@ /*********************************************************************** * Copyright (c) 2009 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation ***********************************************************************/ package org.eclipse.birt.report.engine.nLayout.area.impl; import java.awt.Color; import java.util.Iterator; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.eclipse.birt.report.engine.nLayout.LayoutContext; import org.eclipse.birt.report.engine.nLayout.area.IContainerArea; import org.eclipse.birt.report.engine.nLayout.area.style.BackgroundImageInfo; import org.eclipse.birt.report.engine.nLayout.area.style.BoxStyle; import org.w3c.dom.css.CSSValue; public class CellArea extends BlockContainerArea implements IContainerArea { static int DEFAULT_PADDING = 1500; static LocalProperties CELL_DEFAULT = new LocalProperties( ); protected int rowSpan = 1; protected int colSpan = 1; protected int columnID = 0; protected int rowID = 0; static { CELL_DEFAULT.setPaddingTop( DEFAULT_PADDING ); CELL_DEFAULT.setPaddingRight( DEFAULT_PADDING ); CELL_DEFAULT.setPaddingBottom( DEFAULT_PADDING ); CELL_DEFAULT.setPaddingLeft( DEFAULT_PADDING ); }; public CellArea( ContainerArea parent, LayoutContext context, IContent content ) { super( parent, context, content ); } public CellArea( ) { super( ); localProperties = CELL_DEFAULT; } public CellArea( CellArea cell ) { super( cell ); rowSpan = cell.rowSpan; colSpan = cell.colSpan; columnID = cell.columnID; rowID = cell.rowID; } public int getColumnID( ) { return columnID; } public void setColumnID( int columnID ) { this.columnID = columnID; } public int getRowID( ) { return rowID; } public void setRowID( int rowID ) { this.rowID = rowID; } public int getColSpan( ) { return colSpan; } public void setColSpan( int colSpan ) { this.colSpan = colSpan; } public int getRowSpan( ) { return rowSpan; } public void setRowSpan( int rowSpan ) { this.rowSpan = rowSpan; } public void close( ) throws BirtException { height = currentBP + getOffsetY( ) + localProperties.getPaddingBottom( ); checkPageBreak(); parent.update( this ); finished = true; } public void initialize( ) throws BirtException { ICellContent cellContent = (ICellContent) content; rowSpan = cellContent.getRowSpan( ); columnID = cellContent.getColumn( ); colSpan = cellContent.getColSpan( ); TableArea table = getTable( ); hasStyle = true; width = table.getCellWidth( columnID, columnID + colSpan ); this.buildProperties( cellContent, context ); table.resolveBorderConflict( this, true ); maxAvaWidth = getContentWidth( ); boolean isLastColumn = ( columnID + colSpan == table.getColumnCount( ) ); if ( !table.isInInlineStacking && isLastColumn ) { isInInlineStacking = false; } else { isInInlineStacking = true; } this.bookmark = content.getBookmark( ); this.action = content.getHyperlinkAction( ); parent.add( this ); } protected void buildProperties( IContent content, LayoutContext context ) { IStyle style = content.getComputedStyle( ); boxStyle = new BoxStyle( ); Color color = PropertyUtil.getColor( style .getProperty( IStyle.STYLE_BACKGROUND_COLOR ) ); if ( color != null ) { boxStyle.setBackgroundColor( color ); } String url = content.getStyle().getBackgroundImage( ); if ( url != null ) { boxStyle.setBackgroundImage( new BackgroundImageInfo( getImageUrl( url ), style .getProperty( IStyle.STYLE_BACKGROUND_REPEAT ), getDimensionValue( style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_X ), width ), getDimensionValue( style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_Y ), width ) ) ); } localProperties = new LocalProperties( ); int maw = parent.getMaxAvaWidth( ); IStyle cs = content.getStyle( ); CSSValue padding = cs.getProperty( IStyle.STYLE_PADDING_TOP ); if ( padding == null ) { localProperties.setPaddingTop( DEFAULT_PADDING ); } else { localProperties.setPaddingTop( PropertyUtil.getDimensionValue( - padding, width ) ); + style.getProperty( IStyle.STYLE_PADDING_TOP ), width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_BOTTOM ); if ( padding == null ) { localProperties.setPaddingBottom( DEFAULT_PADDING ); } else { localProperties.setPaddingBottom( PropertyUtil.getDimensionValue( - padding, width ) ); + style.getProperty( IStyle.STYLE_PADDING_BOTTOM ), width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_LEFT ); if ( padding == null ) { localProperties.setPaddingLeft( DEFAULT_PADDING ); } else { localProperties.setPaddingLeft( PropertyUtil.getDimensionValue( - padding, width ) ); + style.getProperty( IStyle.STYLE_PADDING_LEFT ), width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_RIGHT); if ( padding == null ) { localProperties.setPaddingRight( DEFAULT_PADDING ); } else { localProperties.setPaddingRight( PropertyUtil.getDimensionValue( - padding, width ) ); + style.getProperty( IStyle.STYLE_PADDING_RIGHT), width ) ); } textAlign = content.getComputedStyle( ).getProperty( IStyle.STYLE_TEXT_ALIGN ); } public CellArea cloneArea( ) { CellArea cell = new CellArea(this); cell.setBoxStyle( new BoxStyle( cell.getBoxStyle( ) ) ); return cell; } public void update( AbstractArea area ) throws BirtException { super.update( area ); if ( currentIP + area.getAllocatedWidth( ) > getContentWidth( ) ) { setNeedClip( true ); } } public boolean isPageBreakAfterAvoid( ) { return false; } public boolean isPageBreakBeforeAvoid( ) { return false; } public boolean isPageBreakInsideAvoid( ) { return false; } public CellArea deepClone( ) { CellArea cell = (CellArea) super.deepClone( ); cell.setBoxStyle( new BoxStyle( cell.getBoxStyle( ) ) ); return cell; } }
false
true
protected void buildProperties( IContent content, LayoutContext context ) { IStyle style = content.getComputedStyle( ); boxStyle = new BoxStyle( ); Color color = PropertyUtil.getColor( style .getProperty( IStyle.STYLE_BACKGROUND_COLOR ) ); if ( color != null ) { boxStyle.setBackgroundColor( color ); } String url = content.getStyle().getBackgroundImage( ); if ( url != null ) { boxStyle.setBackgroundImage( new BackgroundImageInfo( getImageUrl( url ), style .getProperty( IStyle.STYLE_BACKGROUND_REPEAT ), getDimensionValue( style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_X ), width ), getDimensionValue( style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_Y ), width ) ) ); } localProperties = new LocalProperties( ); int maw = parent.getMaxAvaWidth( ); IStyle cs = content.getStyle( ); CSSValue padding = cs.getProperty( IStyle.STYLE_PADDING_TOP ); if ( padding == null ) { localProperties.setPaddingTop( DEFAULT_PADDING ); } else { localProperties.setPaddingTop( PropertyUtil.getDimensionValue( padding, width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_BOTTOM ); if ( padding == null ) { localProperties.setPaddingBottom( DEFAULT_PADDING ); } else { localProperties.setPaddingBottom( PropertyUtil.getDimensionValue( padding, width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_LEFT ); if ( padding == null ) { localProperties.setPaddingLeft( DEFAULT_PADDING ); } else { localProperties.setPaddingLeft( PropertyUtil.getDimensionValue( padding, width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_RIGHT); if ( padding == null ) { localProperties.setPaddingRight( DEFAULT_PADDING ); } else { localProperties.setPaddingRight( PropertyUtil.getDimensionValue( padding, width ) ); } textAlign = content.getComputedStyle( ).getProperty( IStyle.STYLE_TEXT_ALIGN ); }
protected void buildProperties( IContent content, LayoutContext context ) { IStyle style = content.getComputedStyle( ); boxStyle = new BoxStyle( ); Color color = PropertyUtil.getColor( style .getProperty( IStyle.STYLE_BACKGROUND_COLOR ) ); if ( color != null ) { boxStyle.setBackgroundColor( color ); } String url = content.getStyle().getBackgroundImage( ); if ( url != null ) { boxStyle.setBackgroundImage( new BackgroundImageInfo( getImageUrl( url ), style .getProperty( IStyle.STYLE_BACKGROUND_REPEAT ), getDimensionValue( style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_X ), width ), getDimensionValue( style .getProperty( IStyle.STYLE_BACKGROUND_POSITION_Y ), width ) ) ); } localProperties = new LocalProperties( ); int maw = parent.getMaxAvaWidth( ); IStyle cs = content.getStyle( ); CSSValue padding = cs.getProperty( IStyle.STYLE_PADDING_TOP ); if ( padding == null ) { localProperties.setPaddingTop( DEFAULT_PADDING ); } else { localProperties.setPaddingTop( PropertyUtil.getDimensionValue( style.getProperty( IStyle.STYLE_PADDING_TOP ), width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_BOTTOM ); if ( padding == null ) { localProperties.setPaddingBottom( DEFAULT_PADDING ); } else { localProperties.setPaddingBottom( PropertyUtil.getDimensionValue( style.getProperty( IStyle.STYLE_PADDING_BOTTOM ), width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_LEFT ); if ( padding == null ) { localProperties.setPaddingLeft( DEFAULT_PADDING ); } else { localProperties.setPaddingLeft( PropertyUtil.getDimensionValue( style.getProperty( IStyle.STYLE_PADDING_LEFT ), width ) ); } padding = cs.getProperty( IStyle.STYLE_PADDING_RIGHT); if ( padding == null ) { localProperties.setPaddingRight( DEFAULT_PADDING ); } else { localProperties.setPaddingRight( PropertyUtil.getDimensionValue( style.getProperty( IStyle.STYLE_PADDING_RIGHT), width ) ); } textAlign = content.getComputedStyle( ).getProperty( IStyle.STYLE_TEXT_ALIGN ); }
diff --git a/InsertingObjects/Callbacks/src/main/java/cbe/inserting/Callbacks.java b/InsertingObjects/Callbacks/src/main/java/cbe/inserting/Callbacks.java index 2340e0a..7c633a8 100644 --- a/InsertingObjects/Callbacks/src/main/java/cbe/inserting/Callbacks.java +++ b/InsertingObjects/Callbacks/src/main/java/cbe/inserting/Callbacks.java @@ -1,62 +1,62 @@ package cbe.inserting; import org.apache.cayenne.access.DataContext; import cbe.inserting.model.Person; /** * Cayenne By Example - https://github.com/mrg/cbe * * This example inserts a single Person object into the database and uses * Cayenne's lifecycle callbacks to automatically set the create and modify * dates in the Person. The callback is defined in the model. In Cayenne * Modeler, select the Person ObjEntity (Java class) and then the Callbacks tab * to see where the callbacks are defined. Look at Person.java to see the * implementation of the callbacks in the onPrePersist and anPreUpdate methods. * * This example is based upon BasicInserts1. * * @author mrg */ public class Callbacks { public Callbacks() throws InterruptedException { System.out.println("Initializing Cayenne"); // Create a new DataContext. This will also initialize the Cayenne // Framework. DataContext dataContext = DataContext.createDataContext(); System.out.println("Creating objects"); // Create a new Person object tracked by the DataContext. Person person = dataContext.newObject(Person.class); // Set values for the new person. person.setFirstName("System"); person.setLastName("Admin"); System.out.println("Persisting [1]"); // Commit the changes to the database. This will cause the pre-persist - // callback in the Person to fire. + // callback in the Person to fire setting the create date. dataContext.commitChanges(); System.out.println("Modifying objects"); // Update the person's last name. person.setLastName("Administrator"); System.out.println("Persisting [2]"); - // Commit the changes to the database. This will cause the post-persist - // callback in the Person to fire. + // Commit the changes to the database. This will cause the pre-update + // callback in the Person to fire setting the modification date.. dataContext.commitChanges(); } public static void main(String[] arguments) throws InterruptedException { new Callbacks(); } }
false
true
public Callbacks() throws InterruptedException { System.out.println("Initializing Cayenne"); // Create a new DataContext. This will also initialize the Cayenne // Framework. DataContext dataContext = DataContext.createDataContext(); System.out.println("Creating objects"); // Create a new Person object tracked by the DataContext. Person person = dataContext.newObject(Person.class); // Set values for the new person. person.setFirstName("System"); person.setLastName("Admin"); System.out.println("Persisting [1]"); // Commit the changes to the database. This will cause the pre-persist // callback in the Person to fire. dataContext.commitChanges(); System.out.println("Modifying objects"); // Update the person's last name. person.setLastName("Administrator"); System.out.println("Persisting [2]"); // Commit the changes to the database. This will cause the post-persist // callback in the Person to fire. dataContext.commitChanges(); }
public Callbacks() throws InterruptedException { System.out.println("Initializing Cayenne"); // Create a new DataContext. This will also initialize the Cayenne // Framework. DataContext dataContext = DataContext.createDataContext(); System.out.println("Creating objects"); // Create a new Person object tracked by the DataContext. Person person = dataContext.newObject(Person.class); // Set values for the new person. person.setFirstName("System"); person.setLastName("Admin"); System.out.println("Persisting [1]"); // Commit the changes to the database. This will cause the pre-persist // callback in the Person to fire setting the create date. dataContext.commitChanges(); System.out.println("Modifying objects"); // Update the person's last name. person.setLastName("Administrator"); System.out.println("Persisting [2]"); // Commit the changes to the database. This will cause the pre-update // callback in the Person to fire setting the modification date.. dataContext.commitChanges(); }
diff --git a/src/main/java/com/brainydroid/daydreaming/db/Poll.java b/src/main/java/com/brainydroid/daydreaming/db/Poll.java index 42277dd6..c501135e 100644 --- a/src/main/java/com/brainydroid/daydreaming/db/Poll.java +++ b/src/main/java/com/brainydroid/daydreaming/db/Poll.java @@ -1,150 +1,152 @@ package com.brainydroid.daydreaming.db; import com.brainydroid.daydreaming.background.Logger; import com.google.gson.annotations.Expose; import com.google.inject.Inject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public final class Poll extends StatusModel<Poll,PollsStorage> { private static String TAG = "Poll"; @Expose @Inject private ArrayList<Question> questions; @Expose private long notificationNtpTimestamp; @Expose private long notificationSystemTimestamp; public static final String STATUS_PENDING = "pollPending"; // Notification has appeared public static final String STATUS_RUNNING = "pollRunning"; // QuestionActivity is running public static final String STATUS_PARTIALLY_COMPLETED = "pollPartiallyCompleted"; // QuestionActivity was stopped, and Poll expired public static final String STATUS_COMPLETED = "pollCompleted"; // QuestionActivity completed @Inject transient PollsStorage pollsStorage; @Inject transient QuestionsStorage questionsStorage; @Inject transient Util util; public synchronized void populateQuestions() { Logger.d(TAG, "Populating poll"); int nSlots = questionsStorage.getNSlotsPerPoll(); HashMap<Integer, ArrayList<Question>> slots = new HashMap<Integer, ArrayList<Question>>(); // Get all our questions SlottedQuestions slottedQuestions = questionsStorage.getSlottedQuestions(); Logger.v(TAG, "Got {} questions from DB", slottedQuestions.size()); // First get the positioned groups, and convert their negative indices HashMap<Integer, ArrayList<Question>> positionedGroups = slottedQuestions.getPositionedQuestionGroups(); Logger.v(TAG, "Got {} positioned question groups", positionedGroups.size()); int originalIndex; int convertedIndex; for (Map.Entry<Integer, ArrayList<Question>> groupEntry : positionedGroups.entrySet()) { originalIndex = groupEntry.getKey(); convertedIndex = originalIndex < 0 ? nSlots + originalIndex : originalIndex; Logger.v(TAG, "Placing group at slot {}", convertedIndex); slots.put(convertedIndex, groupEntry.getValue()); } // Find which indices we still need to fill up ArrayList<Integer> remainingIndices = new ArrayList<Integer>(); for (int i = 0; i < nSlots; i++) { if (!slots.containsKey(i)) { remainingIndices.add(i); } } int nFloatingToFill = remainingIndices.size(); Logger.v(TAG, "Still have {} slots to fill", nFloatingToFill); // Get as many floating groups as there remains free slots (they're // already randomly ordered) ArrayList<ArrayList<Question>> floatingGroups = slottedQuestions.getRandomFloatingQuestionGroups( nFloatingToFill); Logger.v(TAG, "Got {} floating groups to fill the slots", floatingGroups.size()); for (int i = 0; i < nFloatingToFill; i++) { Logger.v(TAG, "Putting group {0} at slot {1}", floatingGroups.get(i).get(0).getSlot(), remainingIndices.get(i)); slots.put(remainingIndices.get(i), floatingGroups.get(i)); } // Shuffle each group internally, and store in a two-level ArrayList ArrayList<ArrayList<Question>> slotsArray = new ArrayList<ArrayList<Question>>(nSlots); ArrayList<Question> slotQuestions; for (Map.Entry<Integer, ArrayList<Question>> groupEntry : slots.entrySet()) { Logger.v(TAG, "Shuffling slot {}", groupEntry.getKey()); slotQuestions = groupEntry.getValue(); util.shuffle(slotQuestions); slotsArray.add(groupEntry.getKey(), slotQuestions); } // Finally flatten the two-level ArrayList Logger.v(TAG, "Flattening the slots into an array"); questions = new ArrayList<Question>(); for (ArrayList<Question> slot : slotsArray) { - questions.addAll(slot); + for (Question q : slot) { + addQuestion(q); + } } } public synchronized void addQuestion(Question question) { Logger.d(TAG, "Adding question {0} to poll", question.getName()); question.setPoll(this); questions.add(question); } public synchronized ArrayList<Question> getQuestions() { return questions; } public synchronized Question getQuestionByIndex(int index) { return questions.get(index); } public synchronized int getLength() { return questions.size(); } public synchronized long getNotificationNtpTimestamp() { return notificationNtpTimestamp; } public synchronized void setNotificationNtpTimestamp( long notificationNtpTimestamp) { Logger.v(TAG, "Setting notification ntpTimestamp"); this.notificationNtpTimestamp = notificationNtpTimestamp; saveIfSync(); } public synchronized long getNotificationSystemTimestamp() { return notificationSystemTimestamp; } public synchronized void setNotificationSystemTimestamp( long notificationSystemTimestamp) { Logger.v(TAG, "Setting notification systemTimestamp"); this.notificationSystemTimestamp = notificationSystemTimestamp; saveIfSync(); } @Override protected synchronized Poll self() { return this; } @Override protected synchronized PollsStorage getStorage() { return pollsStorage; } }
true
true
public synchronized void populateQuestions() { Logger.d(TAG, "Populating poll"); int nSlots = questionsStorage.getNSlotsPerPoll(); HashMap<Integer, ArrayList<Question>> slots = new HashMap<Integer, ArrayList<Question>>(); // Get all our questions SlottedQuestions slottedQuestions = questionsStorage.getSlottedQuestions(); Logger.v(TAG, "Got {} questions from DB", slottedQuestions.size()); // First get the positioned groups, and convert their negative indices HashMap<Integer, ArrayList<Question>> positionedGroups = slottedQuestions.getPositionedQuestionGroups(); Logger.v(TAG, "Got {} positioned question groups", positionedGroups.size()); int originalIndex; int convertedIndex; for (Map.Entry<Integer, ArrayList<Question>> groupEntry : positionedGroups.entrySet()) { originalIndex = groupEntry.getKey(); convertedIndex = originalIndex < 0 ? nSlots + originalIndex : originalIndex; Logger.v(TAG, "Placing group at slot {}", convertedIndex); slots.put(convertedIndex, groupEntry.getValue()); } // Find which indices we still need to fill up ArrayList<Integer> remainingIndices = new ArrayList<Integer>(); for (int i = 0; i < nSlots; i++) { if (!slots.containsKey(i)) { remainingIndices.add(i); } } int nFloatingToFill = remainingIndices.size(); Logger.v(TAG, "Still have {} slots to fill", nFloatingToFill); // Get as many floating groups as there remains free slots (they're // already randomly ordered) ArrayList<ArrayList<Question>> floatingGroups = slottedQuestions.getRandomFloatingQuestionGroups( nFloatingToFill); Logger.v(TAG, "Got {} floating groups to fill the slots", floatingGroups.size()); for (int i = 0; i < nFloatingToFill; i++) { Logger.v(TAG, "Putting group {0} at slot {1}", floatingGroups.get(i).get(0).getSlot(), remainingIndices.get(i)); slots.put(remainingIndices.get(i), floatingGroups.get(i)); } // Shuffle each group internally, and store in a two-level ArrayList ArrayList<ArrayList<Question>> slotsArray = new ArrayList<ArrayList<Question>>(nSlots); ArrayList<Question> slotQuestions; for (Map.Entry<Integer, ArrayList<Question>> groupEntry : slots.entrySet()) { Logger.v(TAG, "Shuffling slot {}", groupEntry.getKey()); slotQuestions = groupEntry.getValue(); util.shuffle(slotQuestions); slotsArray.add(groupEntry.getKey(), slotQuestions); } // Finally flatten the two-level ArrayList Logger.v(TAG, "Flattening the slots into an array"); questions = new ArrayList<Question>(); for (ArrayList<Question> slot : slotsArray) { questions.addAll(slot); } }
public synchronized void populateQuestions() { Logger.d(TAG, "Populating poll"); int nSlots = questionsStorage.getNSlotsPerPoll(); HashMap<Integer, ArrayList<Question>> slots = new HashMap<Integer, ArrayList<Question>>(); // Get all our questions SlottedQuestions slottedQuestions = questionsStorage.getSlottedQuestions(); Logger.v(TAG, "Got {} questions from DB", slottedQuestions.size()); // First get the positioned groups, and convert their negative indices HashMap<Integer, ArrayList<Question>> positionedGroups = slottedQuestions.getPositionedQuestionGroups(); Logger.v(TAG, "Got {} positioned question groups", positionedGroups.size()); int originalIndex; int convertedIndex; for (Map.Entry<Integer, ArrayList<Question>> groupEntry : positionedGroups.entrySet()) { originalIndex = groupEntry.getKey(); convertedIndex = originalIndex < 0 ? nSlots + originalIndex : originalIndex; Logger.v(TAG, "Placing group at slot {}", convertedIndex); slots.put(convertedIndex, groupEntry.getValue()); } // Find which indices we still need to fill up ArrayList<Integer> remainingIndices = new ArrayList<Integer>(); for (int i = 0; i < nSlots; i++) { if (!slots.containsKey(i)) { remainingIndices.add(i); } } int nFloatingToFill = remainingIndices.size(); Logger.v(TAG, "Still have {} slots to fill", nFloatingToFill); // Get as many floating groups as there remains free slots (they're // already randomly ordered) ArrayList<ArrayList<Question>> floatingGroups = slottedQuestions.getRandomFloatingQuestionGroups( nFloatingToFill); Logger.v(TAG, "Got {} floating groups to fill the slots", floatingGroups.size()); for (int i = 0; i < nFloatingToFill; i++) { Logger.v(TAG, "Putting group {0} at slot {1}", floatingGroups.get(i).get(0).getSlot(), remainingIndices.get(i)); slots.put(remainingIndices.get(i), floatingGroups.get(i)); } // Shuffle each group internally, and store in a two-level ArrayList ArrayList<ArrayList<Question>> slotsArray = new ArrayList<ArrayList<Question>>(nSlots); ArrayList<Question> slotQuestions; for (Map.Entry<Integer, ArrayList<Question>> groupEntry : slots.entrySet()) { Logger.v(TAG, "Shuffling slot {}", groupEntry.getKey()); slotQuestions = groupEntry.getValue(); util.shuffle(slotQuestions); slotsArray.add(groupEntry.getKey(), slotQuestions); } // Finally flatten the two-level ArrayList Logger.v(TAG, "Flattening the slots into an array"); questions = new ArrayList<Question>(); for (ArrayList<Question> slot : slotsArray) { for (Question q : slot) { addQuestion(q); } } }
diff --git a/Localization.java b/Localization.java index 0100d24..faf68f8 100644 --- a/Localization.java +++ b/Localization.java @@ -1,157 +1,157 @@ /** * Localization.java * @author jmd * * Main class for localization. Herp derp. */ import javax.imageio.ImageIO; import java.awt.image.ColorConvertOp; import java.awt.color.ColorSpace; import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; import java.util.Arrays; // for testing // Player imports import javaclient3.*; import javaclient3.structures.PlayerConstants; import javaclient3.structures.ranger.*; public class Localization { /** * Used for determining the angle that each laser beam fires at. */ public final static double RADIAN_PER_LASER = 0.00615094; /** * This is the offset in radians needed because the 0th sample is not at 0 radians */ public final static double LASER_ROBOT_OFFSET = 2.094395102; /** * Scale of the input map in meters/pixel (pulled from the .world file for the project) */ public final static double MAP_METERS_PER_PIXEL = 0.02; /** * Constant for potential field calculation. */ public final static double OBSTACLE_POTENTIAL_CONSTANT = 1.0; /** * Constant for potential field calculation. */ public final static double GOAL_POTENTIAL_CONSTANT = 1.0; /** * Loads in the map from an external file. Does some number fudging, * because the expected file is a PNG and the RGB value grabbed from it * for white is -1 (representing free space) and the rest (some other * negative number) is black (representing obstacles). * * @param filename the name of the file containing the map * @return a 2D integer array [x][y] containing the grayscale rgb value * at (x,y) where the origin is the top-left-most pixel */ public static int[][] getMap(String filename) { int[][] map; BufferedImage img = null; try { img = ImageIO.read(new File(filename)); } catch (IOException e) { e.printStackTrace(); } map = new int[img.getWidth()][img.getHeight()]; int pixel; for (int x = 0; x < img.getWidth(); x++) { for (int y = 0; y < img.getHeight(); y++) { pixel = img.getRGB(x,y); map[x][y] = (pixel == -1) ? 255 : 0; // some number fudging } } return map; } /** * Takes in a configuration space map (assuming the robot is a point) and * returns a workspace map (assuming the robot has a 10cm radius). This * lazily expands all the obstacles by 5cm in all directions * * @param map the configuration space map as a 2D integer array * @return the workspace map as a 2D integer array */ public static int[][] getWorkspaceMap(int[][] map) { int[][] csMap = new int[map.length][map[0].length]; for (int x = 0; x < csMap.length; x++) { for (int y = 0; y < csMap[0].length; y++) { if (map[x][y] == 0) { for (int i = -9; i < 9; i++) { for (int j = -9; j < 9; j++) { if (x+i < 0 || y+j < 0) continue; if (map[x+i][y+j] != 0) csMap[x+i][y+j] = 0; } } } else { csMap[x][y] = map[x][y]; } } } return csMap; } public static void main(String[] args) { int[][] map = getMap(args[0]); int[][] csMap = getWorkspaceMap(map); // System.out.println("map = " + Arrays.deepToString(map)); // System.out.println(); System.out.println("csMap = " + Arrays.deepToString(csMap)); // Testing junk... // @TODO Remove this at some point int mapObs = 0, csMapObs = 0; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { if (map[i][j] == 0) mapObs++; if (csMap[i][j] == 0) csMapObs++; } } System.out.printf("Original Obstacle Pixels: %d\n" + "Workspace Obstacle Pixels: %d\n", mapObs, csMapObs); // copypasta initalization stuff from other jawns /* PlayerClient pc; if (args.length == 1) pc = new PlayerClient("localhost",6665); else pc = new PlayerClient(args[1],Integer.valueOf(args[2])); Position2DInterface pos = pc.requestInterfacePosition2D(0,PlayerConstants.PLAYER_OPEN_MODE); RangerInterface ranger = pc.requestInterfaceRanger(0,PlayerConstants.PLAYER_OPEN_MODE); */ /* So as not to potentially overload the ranger interface, we should * probably pass the localizer to the wanderer and have the wanderer * update the localizer as it receives info from the ranger and pos. * * Or we would just let them independently abuse the ranger and pos. * Whatever. */ - Localizer loc = new Localizer(map.length,map[0].length); + Localizer loc = new Localizer(map); //Wanderer w = new Wanderer(pc,pos,ranger,loc); // loc.start(); // w.start(); } }
true
true
public static void main(String[] args) { int[][] map = getMap(args[0]); int[][] csMap = getWorkspaceMap(map); // System.out.println("map = " + Arrays.deepToString(map)); // System.out.println(); System.out.println("csMap = " + Arrays.deepToString(csMap)); // Testing junk... // @TODO Remove this at some point int mapObs = 0, csMapObs = 0; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { if (map[i][j] == 0) mapObs++; if (csMap[i][j] == 0) csMapObs++; } } System.out.printf("Original Obstacle Pixels: %d\n" + "Workspace Obstacle Pixels: %d\n", mapObs, csMapObs); // copypasta initalization stuff from other jawns /* PlayerClient pc; if (args.length == 1) pc = new PlayerClient("localhost",6665); else pc = new PlayerClient(args[1],Integer.valueOf(args[2])); Position2DInterface pos = pc.requestInterfacePosition2D(0,PlayerConstants.PLAYER_OPEN_MODE); RangerInterface ranger = pc.requestInterfaceRanger(0,PlayerConstants.PLAYER_OPEN_MODE); */ /* So as not to potentially overload the ranger interface, we should * probably pass the localizer to the wanderer and have the wanderer * update the localizer as it receives info from the ranger and pos. * * Or we would just let them independently abuse the ranger and pos. * Whatever. */ Localizer loc = new Localizer(map.length,map[0].length); //Wanderer w = new Wanderer(pc,pos,ranger,loc); // loc.start(); // w.start(); }
public static void main(String[] args) { int[][] map = getMap(args[0]); int[][] csMap = getWorkspaceMap(map); // System.out.println("map = " + Arrays.deepToString(map)); // System.out.println(); System.out.println("csMap = " + Arrays.deepToString(csMap)); // Testing junk... // @TODO Remove this at some point int mapObs = 0, csMapObs = 0; for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { if (map[i][j] == 0) mapObs++; if (csMap[i][j] == 0) csMapObs++; } } System.out.printf("Original Obstacle Pixels: %d\n" + "Workspace Obstacle Pixels: %d\n", mapObs, csMapObs); // copypasta initalization stuff from other jawns /* PlayerClient pc; if (args.length == 1) pc = new PlayerClient("localhost",6665); else pc = new PlayerClient(args[1],Integer.valueOf(args[2])); Position2DInterface pos = pc.requestInterfacePosition2D(0,PlayerConstants.PLAYER_OPEN_MODE); RangerInterface ranger = pc.requestInterfaceRanger(0,PlayerConstants.PLAYER_OPEN_MODE); */ /* So as not to potentially overload the ranger interface, we should * probably pass the localizer to the wanderer and have the wanderer * update the localizer as it receives info from the ranger and pos. * * Or we would just let them independently abuse the ranger and pos. * Whatever. */ Localizer loc = new Localizer(map); //Wanderer w = new Wanderer(pc,pos,ranger,loc); // loc.start(); // w.start(); }
diff --git a/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java b/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java index 7fab69c..8128e25 100644 --- a/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java +++ b/src/com/ftwinston/Killer/CraftBukkit/CraftBukkitAccess.java @@ -1,77 +1,77 @@ package com.ftwinston.Killer.CraftBukkit; import java.lang.reflect.Field; import java.util.HashMap; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.World.Environment; import org.bukkit.block.Block; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.Plugin; // a holder for everything that dives into the versioned CraftBukkit code that will break with every minecraft update public abstract class CraftBukkitAccess { public static CraftBukkitAccess createCorrectVersion(Plugin plugin) { // Get full package string of CraftServer class, then extract the version name from that // org.bukkit.craftbukkit.versionstring (or for pre-refactor, just org.bukkit.craftbukkit String packageName = plugin.getServer().getClass().getPackage().getName(); String version = packageName.substring(packageName.lastIndexOf('.') + 1); - if ( version.equals("v1_4_7")) + if ( version.equals("v1_4_R1")) return new v1_4_7(plugin); if ( version.equals("v1_4_6")) return new v1_4_6(plugin); if ( version.equals("v1_4_5")) return new v1_4_5(plugin); if ( version.equals("craftbukkit")) plugin.getLogger().warning("Killer minecraft requires at least CraftBukkit 1.4.5-R1.0 to function. Sorry."); else plugin.getLogger().warning("This version of Killer minecraft is not compatible with your server's version of CraftBukkit! (" + version + ") Please download a newer version of Killer minecraft."); return null; } protected CraftBukkitAccess(Plugin plugin) { this.plugin = plugin; } protected Plugin plugin; @SuppressWarnings("rawtypes") protected HashMap regionfiles; protected Field rafField; public abstract String getDefaultLevelName(); public abstract YamlConfiguration getBukkitConfiguration(); public abstract void saveBukkitConfiguration(YamlConfiguration configuration); public abstract String getServerProperty(String name, String defaultVal); public abstract void setServerProperty(String name, String value); public abstract void saveServerPropertiesFile(); public abstract void sendForScoreboard(Player viewer, String name, boolean show); public abstract void sendForScoreboard(Player viewer, Player other, boolean show); public abstract void forceRespawn(final Player player); public abstract void bindRegionFiles(); public void unbindRegionFiles() { regionfiles = null; rafField = null; } public abstract boolean clearWorldReference(String worldName); public abstract void forceUnloadWorld(World world); public abstract void accountForDefaultWorldDeletion(World newDefault); public abstract World createWorld(org.bukkit.WorldType type, Environment env, String name, long seed, ChunkGenerator generator, String generatorSettings, boolean generateStructures); public abstract Location findNearestNetherFortress(Location loc); public abstract boolean createFlyingEnderEye(Player player, Location target); public abstract void pushButton(Block b); }
true
true
public static CraftBukkitAccess createCorrectVersion(Plugin plugin) { // Get full package string of CraftServer class, then extract the version name from that // org.bukkit.craftbukkit.versionstring (or for pre-refactor, just org.bukkit.craftbukkit String packageName = plugin.getServer().getClass().getPackage().getName(); String version = packageName.substring(packageName.lastIndexOf('.') + 1); if ( version.equals("v1_4_7")) return new v1_4_7(plugin); if ( version.equals("v1_4_6")) return new v1_4_6(plugin); if ( version.equals("v1_4_5")) return new v1_4_5(plugin); if ( version.equals("craftbukkit")) plugin.getLogger().warning("Killer minecraft requires at least CraftBukkit 1.4.5-R1.0 to function. Sorry."); else plugin.getLogger().warning("This version of Killer minecraft is not compatible with your server's version of CraftBukkit! (" + version + ") Please download a newer version of Killer minecraft."); return null; }
public static CraftBukkitAccess createCorrectVersion(Plugin plugin) { // Get full package string of CraftServer class, then extract the version name from that // org.bukkit.craftbukkit.versionstring (or for pre-refactor, just org.bukkit.craftbukkit String packageName = plugin.getServer().getClass().getPackage().getName(); String version = packageName.substring(packageName.lastIndexOf('.') + 1); if ( version.equals("v1_4_R1")) return new v1_4_7(plugin); if ( version.equals("v1_4_6")) return new v1_4_6(plugin); if ( version.equals("v1_4_5")) return new v1_4_5(plugin); if ( version.equals("craftbukkit")) plugin.getLogger().warning("Killer minecraft requires at least CraftBukkit 1.4.5-R1.0 to function. Sorry."); else plugin.getLogger().warning("This version of Killer minecraft is not compatible with your server's version of CraftBukkit! (" + version + ") Please download a newer version of Killer minecraft."); return null; }
diff --git a/src/tzer0/PayDay/PayDay.java b/src/tzer0/PayDay/PayDay.java index 6b008f2..f1c16f8 100644 --- a/src/tzer0/PayDay/PayDay.java +++ b/src/tzer0/PayDay/PayDay.java @@ -1,347 +1,347 @@ package tzer0.PayDay; import java.util.LinkedList; import java.util.List; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.Event; import org.bukkit.event.Event.Priority; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.config.Configuration; import com.nijiko.coelho.iConomy.iConomy; import com.nijiko.coelho.iConomy.system.Bank; import com.nijiko.permissions.PermissionHandler; import com.nijikokun.bukkit.Permissions.Permissions; public class PayDay extends JavaPlugin { public PermissionHandler permissions; PluginDescriptionFile pdfFile; private Configuration conf; @Override public void onDisable() { } @Override public void onEnable() { pdfFile = this.getDescription(); conf = getConfiguration(); setupPermissions(); getServer().getPluginManager().registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, new PayDayPlayerListener(this), Priority.Normal, this); System.out.println(pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!"); } public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] uargs) { // Keeping everything lower-case except for account names. String[] args = new String[uargs.length]; for (int i = 0; i < args.length; i++) { uargs[i] = uargs[i].replace(".", ""); args[i] = uargs[i].toLowerCase(); } if (args.length == 0 || (args.length >= 1 && args[0].equalsIgnoreCase("help"))) { int page = 1; if (args.length == 2) { page = toInt(args[1], sender); } sender.sendMessage(ChatColor.GREEN+"PayDay " + pdfFile.getVersion() + " by TZer0"); if (page == 1) { sender.sendMessage(ChatColor.YELLOW+"Help (all commands start with /pd):"); sender.sendMessage(ChatColor.YELLOW+"checkerrors - checks for errors in the config-file"); sender.sendMessage(ChatColor.YELLOW+"players [#] - shows number # page in the list of players"); sender.sendMessage(ChatColor.YELLOW+"groups [#] - shows number # page in the list of groups"); sender.sendMessage(ChatColor.YELLOW+"payday - pays everyone their money, won't run if checkerrors fails"); sender.sendMessage(ChatColor.YELLOW+"payday group/player name - pays a specific group or player"); sender.sendMessage(ChatColor.YELLOW+"set group name value - creates a group with earns value per payday"); sender.sendMessage(ChatColor.YELLOW+"set player name groupname - assigns a player to a group"); sender.sendMessage(ChatColor.YELLOW+"move groupname1 groupname2 - moves all players from one group to another"); sender.sendMessage(ChatColor.YELLOW+"delete player/group name - deletes a group/player"); sender.sendMessage(ChatColor.YELLOW+"sync [overwrite] - imports players and groups from iConomy and Permissions"); sender.sendMessage(ChatColor.RED+"REMEMBER: player-names are CASE-SENSITIVE"); sender.sendMessage(ChatColor.YELLOW+"help 2 for aliases (very useful)"); } else if (page == 2) { sender.sendMessage(ChatColor.YELLOW+"Aliases:"); sender.sendMessage(ChatColor.YELLOW+"player = pl, players = pl, groups = gr"); sender.sendMessage(ChatColor.YELLOW+"group = gr, checkerrors = ce, payday = pd"); sender.sendMessage(ChatColor.YELLOW+"set = s, delete = d, move = mv"); sender.sendMessage(ChatColor.YELLOW+"sync = sy, overwrite = ow"); sender.sendMessage(ChatColor.YELLOW+"Example usage:"); sender.sendMessage(ChatColor.YELLOW+"/pd s gr epicgroup 10000"); sender.sendMessage(ChatColor.YELLOW+"/pd s pl TZer0 epicgroup"); sender.sendMessage(ChatColor.YELLOW+"/pd pd"); sender.sendMessage(ChatColor.YELLOW+"/pd d gr epicgroup"); } else { sender.sendMessage(ChatColor.YELLOW + "No such help-page!"); } return true; } else if (args.length >= 1 && (args[0].equalsIgnoreCase("sync") || (args[0].equalsIgnoreCase("sy")))) { // Imports data from Permissions and iConomy. Bank ic = iConomy.getBank(); if (permissions == null) { sender.sendMessage(ChatColor.RED + "Permissions unavailable - aborting."); } else { boolean overwrite = (args.length == 2 && (args[1].equalsIgnoreCase("overwrite") || args[1].equalsIgnoreCase("ow"))); for (String key: ic.getAccounts().keySet()) { if (conf.getString("players."+key) == null || overwrite) { - conf.setProperty("players."+key, permissions.getGroup("world", key)); - if (conf.getString("groups."+permissions.getGroup("world", key)) == null) { - conf.setProperty("groups."+permissions.getGroup("world", key), 0); + conf.setProperty("players."+key, permissions.getGroup("world", key).toLowerCase()); + if (conf.getString("groups."+permissions.getGroup("world", key).toLowerCase()) == null) { + conf.setProperty("groups."+permissions.getGroup("world", key).toLowerCase(), 0); } } } conf.save(); sender.sendMessage(ChatColor.GREEN+"Done!"); } return true; } else if (args.length >= 1 && (args[0].equalsIgnoreCase("checkerrors") || args[0].equalsIgnoreCase("ce"))) { // Utility - checks for errors while not running payday. if (!checkErrors(sender, iConomy.getBank())) { sender.sendMessage(ChatColor.GREEN+"No errors found."); } else { sender.sendMessage(ChatColor.RED + "Errors found, fix them before running payday"); } } else if (args.length >= 1 && (args[0].replace("players", "player").equalsIgnoreCase("player") || args[0].equalsIgnoreCase("pl"))) { // Lists players int page = 0; if (args.length == 2) { page = toInt(args[2], sender); } page(page, sender, "Player"); } else if (args.length >= 1 && (args[0].replace("groups", "group").equalsIgnoreCase("group") || args[0].equalsIgnoreCase("gr"))) { // Lists groups int page = 0; if (args.length == 2) { page = toInt(args[2], sender); } page(page, sender, "Group"); } else if (args.length >= 1 && (args[0].equalsIgnoreCase("payday") || args[0].equalsIgnoreCase("pd"))) { // Attempts to pay out the predefined amounts of cash, fails before paying out anything if // the config is incorrect Bank ic = iConomy.getBank(); if (checkErrors(sender, iConomy.getBank())) { sender.sendMessage(ChatColor.RED + "Errors found, fix them before running payday"); return true; } List<String> pay = null; if (args.length == 3) { pay = new LinkedList<String>(); List<String> full = conf.getKeys("players."); if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { for (String name : full) { if (conf.getString("players."+name).equalsIgnoreCase(args[2])) { pay.add(name); } } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (full.contains(uargs[2])) { pay.add(uargs[2]); } else { sender.sendMessage(ChatColor.RED + "No such player!"); return true; } } else { sender.sendMessage(ChatColor.RED + "Invalid 3rd parameter, must be group or player"); return true; } } else if (args.length == 1) { pay = conf.getKeys("players."); getServer().broadcastMessage(ChatColor.GOLD+"It is Pay Day!"); } if (args.length <= 3 || args.length == 1) { for (String pl : pay) { ic.getAccount(pl).add(conf.getInt("groups."+conf.getString("players."+pl, "none"),0)); } } else { sender.sendMessage(ChatColor.RED+"Incorrect format, see help"); return true; } sender.sendMessage(ChatColor.GREEN+"Payday complete"); } else if (args.length >= 1 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("s"))) { // sets either a group's income or a player's group if (args.length == 4) { if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { if (checkInt(args[3]) && !args[2].equalsIgnoreCase("none")) { conf.setProperty("groups."+args[2], Integer.parseInt(args[3])); conf.save(); sender.sendMessage(ChatColor.GREEN + "Done."); } else { sender.sendMessage("Invalid value."); } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (conf.getString("groups."+args[3]) != null) { conf.setProperty("players."+uargs[2], args[3]); conf.save(); sender.sendMessage(ChatColor.GREEN + "Done."); } else { sender.sendMessage(ChatColor.RED + "No such group"); } } else { sender.sendMessage(ChatColor.RED+ String.format("Unknown type %s!", uargs[2])); return true; } } else { sender.sendMessage(ChatColor.RED+"Invalid format, see help"); } } else if (args.length >= 1 && (args[0].equalsIgnoreCase("move") || args[0].equalsIgnoreCase("mv"))) { // Moves all players from one group to another - even if the group you're moving from does // no longer exist if (args.length == 3) { List<String> groups = conf.getKeys("groups."); if (!groups.contains(args[2])) { sender.sendMessage(ChatColor.RED + String.format("No such group %s", args[2])); } else { List<String> players = conf.getKeys("players."); for (String pl : players) { if (conf.getString("players."+pl).equalsIgnoreCase(args[1])) { conf.setProperty("players."+pl, args[2]); } conf.save(); } } } } else if (args.length >= 1 && (args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("d"))) { // deletes either a player or a group if (args.length == 3) { if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { if (conf.getString("groups."+args[2]) != null) { conf.removeProperty("groups."+args[2]); conf.save(); } else { sender.sendMessage(ChatColor.RED+"No such group: " + args[2]); return true; } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (conf.getString("players."+uargs[2]) != null) { conf.removeProperty("players."+uargs[2]); conf.save(); } else { sender.sendMessage(ChatColor.RED+"No such player: " + uargs[2]); return true; } } else { sender.sendMessage(ChatColor.RED+ String.format("Unknown type %s!", args[1])); return true; } sender.sendMessage(ChatColor.GREEN + "Done"); } else { sender.sendMessage(ChatColor.RED+"Incorrect format, see help"); } } else { sender.sendMessage(ChatColor.YELLOW + "No such command, see help!"); } return true; } /** * Checks the configuration for errors - true if errors are found. * * @param sender The one who will receive the error-messages * @param ic iConomy-bank * @return */ public boolean checkErrors(CommandSender sender, Bank ic) { sender.sendMessage(ChatColor.YELLOW+"Checking for errors."); boolean failed = false; if (conf.getString("failed.") != null) { conf.removeProperty("failed."); } List<String> keys = conf.getKeys("players."); List<String> dupefound = new LinkedList<String>(); List<String> groups = conf.getKeys("groups."); if (keys == null || groups == null) { sender.sendMessage(ChatColor.RED + "No configuration (groups or players)!"); return true; } for (String pl : keys) { if (!ic.hasAccount(pl)) { sender.sendMessage(ChatColor.RED+String.format("%s doesn't have an account!", pl)); failed = true; } for (String pl2 : keys) { if (!dupefound.contains(pl2) && pl.equalsIgnoreCase(pl2) && !pl.equals(pl2)) { sender.sendMessage(ChatColor.RED+String.format(ChatColor.RED + "%s may be a duplicate of %s (or vice versa)", pl, pl2)); dupefound.add(pl2); dupefound.add(pl); failed = true; } } if (!groups.contains(conf.getString("players."+pl))) { sender.sendMessage(ChatColor.RED+String.format("%s belongs to an invalid group - %s", pl, conf.getString("players."+pl))); failed = true; } } return failed; } /** * Displays information about either groups or players. * @param page Page to view * @param sender Who gets the output * @param node either group or player - decides what is shown. */ public void page(int page, CommandSender sender, String node) { List<String> items = conf.getKeys(node.toLowerCase()+"s."); if (items != null && page*10 < items.size()) { sender.sendMessage(String.format("Listing %ss, page %d of %d", node, page, (items.size()-1)/10+1)); for (int i = page*10; i < Math.min(items.size(), page*10+10); i++) { sender.sendMessage(items.get(i) + " - " + conf.getString(node.toLowerCase()+"s."+items.get(i), "error")); } if (items.size() > page*10+10) { sender.sendMessage(String.format("/pd %s %d for next page", node, page+1)); } } else { sender.sendMessage("No more items."); } } /** * Converts to int if valid, if not: returns 0 * @param in * @param sender * @return */ public int toInt(String in, CommandSender sender) { int out = 0; if (checkInt(in)) { out = Integer.parseInt(in); } return out; } /** * Checks if a string is valid as a representation of an unsigned int. */ public boolean checkInt(String in) { char chars[] = in.toCharArray(); for (int i = 0; i < chars.length; i++) { if (!Character.isDigit(chars[i])) { return false; } } return true; } /** * Basic Permissions-setup, see more here: https://github.com/TheYeti/Permissions/wiki/API-Reference */ private void setupPermissions() { Plugin test = this.getServer().getPluginManager().getPlugin("Permissions"); if (this.permissions == null) { if (test != null) { this.permissions = ((Permissions) test).getHandler(); } else { System.out.println(ChatColor.YELLOW + "Permissons not detected - defaulting to OP!"); } } } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] uargs) { // Keeping everything lower-case except for account names. String[] args = new String[uargs.length]; for (int i = 0; i < args.length; i++) { uargs[i] = uargs[i].replace(".", ""); args[i] = uargs[i].toLowerCase(); } if (args.length == 0 || (args.length >= 1 && args[0].equalsIgnoreCase("help"))) { int page = 1; if (args.length == 2) { page = toInt(args[1], sender); } sender.sendMessage(ChatColor.GREEN+"PayDay " + pdfFile.getVersion() + " by TZer0"); if (page == 1) { sender.sendMessage(ChatColor.YELLOW+"Help (all commands start with /pd):"); sender.sendMessage(ChatColor.YELLOW+"checkerrors - checks for errors in the config-file"); sender.sendMessage(ChatColor.YELLOW+"players [#] - shows number # page in the list of players"); sender.sendMessage(ChatColor.YELLOW+"groups [#] - shows number # page in the list of groups"); sender.sendMessage(ChatColor.YELLOW+"payday - pays everyone their money, won't run if checkerrors fails"); sender.sendMessage(ChatColor.YELLOW+"payday group/player name - pays a specific group or player"); sender.sendMessage(ChatColor.YELLOW+"set group name value - creates a group with earns value per payday"); sender.sendMessage(ChatColor.YELLOW+"set player name groupname - assigns a player to a group"); sender.sendMessage(ChatColor.YELLOW+"move groupname1 groupname2 - moves all players from one group to another"); sender.sendMessage(ChatColor.YELLOW+"delete player/group name - deletes a group/player"); sender.sendMessage(ChatColor.YELLOW+"sync [overwrite] - imports players and groups from iConomy and Permissions"); sender.sendMessage(ChatColor.RED+"REMEMBER: player-names are CASE-SENSITIVE"); sender.sendMessage(ChatColor.YELLOW+"help 2 for aliases (very useful)"); } else if (page == 2) { sender.sendMessage(ChatColor.YELLOW+"Aliases:"); sender.sendMessage(ChatColor.YELLOW+"player = pl, players = pl, groups = gr"); sender.sendMessage(ChatColor.YELLOW+"group = gr, checkerrors = ce, payday = pd"); sender.sendMessage(ChatColor.YELLOW+"set = s, delete = d, move = mv"); sender.sendMessage(ChatColor.YELLOW+"sync = sy, overwrite = ow"); sender.sendMessage(ChatColor.YELLOW+"Example usage:"); sender.sendMessage(ChatColor.YELLOW+"/pd s gr epicgroup 10000"); sender.sendMessage(ChatColor.YELLOW+"/pd s pl TZer0 epicgroup"); sender.sendMessage(ChatColor.YELLOW+"/pd pd"); sender.sendMessage(ChatColor.YELLOW+"/pd d gr epicgroup"); } else { sender.sendMessage(ChatColor.YELLOW + "No such help-page!"); } return true; } else if (args.length >= 1 && (args[0].equalsIgnoreCase("sync") || (args[0].equalsIgnoreCase("sy")))) { // Imports data from Permissions and iConomy. Bank ic = iConomy.getBank(); if (permissions == null) { sender.sendMessage(ChatColor.RED + "Permissions unavailable - aborting."); } else { boolean overwrite = (args.length == 2 && (args[1].equalsIgnoreCase("overwrite") || args[1].equalsIgnoreCase("ow"))); for (String key: ic.getAccounts().keySet()) { if (conf.getString("players."+key) == null || overwrite) { conf.setProperty("players."+key, permissions.getGroup("world", key)); if (conf.getString("groups."+permissions.getGroup("world", key)) == null) { conf.setProperty("groups."+permissions.getGroup("world", key), 0); } } } conf.save(); sender.sendMessage(ChatColor.GREEN+"Done!"); } return true; } else if (args.length >= 1 && (args[0].equalsIgnoreCase("checkerrors") || args[0].equalsIgnoreCase("ce"))) { // Utility - checks for errors while not running payday. if (!checkErrors(sender, iConomy.getBank())) { sender.sendMessage(ChatColor.GREEN+"No errors found."); } else { sender.sendMessage(ChatColor.RED + "Errors found, fix them before running payday"); } } else if (args.length >= 1 && (args[0].replace("players", "player").equalsIgnoreCase("player") || args[0].equalsIgnoreCase("pl"))) { // Lists players int page = 0; if (args.length == 2) { page = toInt(args[2], sender); } page(page, sender, "Player"); } else if (args.length >= 1 && (args[0].replace("groups", "group").equalsIgnoreCase("group") || args[0].equalsIgnoreCase("gr"))) { // Lists groups int page = 0; if (args.length == 2) { page = toInt(args[2], sender); } page(page, sender, "Group"); } else if (args.length >= 1 && (args[0].equalsIgnoreCase("payday") || args[0].equalsIgnoreCase("pd"))) { // Attempts to pay out the predefined amounts of cash, fails before paying out anything if // the config is incorrect Bank ic = iConomy.getBank(); if (checkErrors(sender, iConomy.getBank())) { sender.sendMessage(ChatColor.RED + "Errors found, fix them before running payday"); return true; } List<String> pay = null; if (args.length == 3) { pay = new LinkedList<String>(); List<String> full = conf.getKeys("players."); if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { for (String name : full) { if (conf.getString("players."+name).equalsIgnoreCase(args[2])) { pay.add(name); } } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (full.contains(uargs[2])) { pay.add(uargs[2]); } else { sender.sendMessage(ChatColor.RED + "No such player!"); return true; } } else { sender.sendMessage(ChatColor.RED + "Invalid 3rd parameter, must be group or player"); return true; } } else if (args.length == 1) { pay = conf.getKeys("players."); getServer().broadcastMessage(ChatColor.GOLD+"It is Pay Day!"); } if (args.length <= 3 || args.length == 1) { for (String pl : pay) { ic.getAccount(pl).add(conf.getInt("groups."+conf.getString("players."+pl, "none"),0)); } } else { sender.sendMessage(ChatColor.RED+"Incorrect format, see help"); return true; } sender.sendMessage(ChatColor.GREEN+"Payday complete"); } else if (args.length >= 1 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("s"))) { // sets either a group's income or a player's group if (args.length == 4) { if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { if (checkInt(args[3]) && !args[2].equalsIgnoreCase("none")) { conf.setProperty("groups."+args[2], Integer.parseInt(args[3])); conf.save(); sender.sendMessage(ChatColor.GREEN + "Done."); } else { sender.sendMessage("Invalid value."); } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (conf.getString("groups."+args[3]) != null) { conf.setProperty("players."+uargs[2], args[3]); conf.save(); sender.sendMessage(ChatColor.GREEN + "Done."); } else { sender.sendMessage(ChatColor.RED + "No such group"); } } else { sender.sendMessage(ChatColor.RED+ String.format("Unknown type %s!", uargs[2])); return true; } } else { sender.sendMessage(ChatColor.RED+"Invalid format, see help"); } } else if (args.length >= 1 && (args[0].equalsIgnoreCase("move") || args[0].equalsIgnoreCase("mv"))) { // Moves all players from one group to another - even if the group you're moving from does // no longer exist if (args.length == 3) { List<String> groups = conf.getKeys("groups."); if (!groups.contains(args[2])) { sender.sendMessage(ChatColor.RED + String.format("No such group %s", args[2])); } else { List<String> players = conf.getKeys("players."); for (String pl : players) { if (conf.getString("players."+pl).equalsIgnoreCase(args[1])) { conf.setProperty("players."+pl, args[2]); } conf.save(); } } } } else if (args.length >= 1 && (args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("d"))) { // deletes either a player or a group if (args.length == 3) { if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { if (conf.getString("groups."+args[2]) != null) { conf.removeProperty("groups."+args[2]); conf.save(); } else { sender.sendMessage(ChatColor.RED+"No such group: " + args[2]); return true; } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (conf.getString("players."+uargs[2]) != null) { conf.removeProperty("players."+uargs[2]); conf.save(); } else { sender.sendMessage(ChatColor.RED+"No such player: " + uargs[2]); return true; } } else { sender.sendMessage(ChatColor.RED+ String.format("Unknown type %s!", args[1])); return true; } sender.sendMessage(ChatColor.GREEN + "Done"); } else { sender.sendMessage(ChatColor.RED+"Incorrect format, see help"); } } else { sender.sendMessage(ChatColor.YELLOW + "No such command, see help!"); } return true; }
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] uargs) { // Keeping everything lower-case except for account names. String[] args = new String[uargs.length]; for (int i = 0; i < args.length; i++) { uargs[i] = uargs[i].replace(".", ""); args[i] = uargs[i].toLowerCase(); } if (args.length == 0 || (args.length >= 1 && args[0].equalsIgnoreCase("help"))) { int page = 1; if (args.length == 2) { page = toInt(args[1], sender); } sender.sendMessage(ChatColor.GREEN+"PayDay " + pdfFile.getVersion() + " by TZer0"); if (page == 1) { sender.sendMessage(ChatColor.YELLOW+"Help (all commands start with /pd):"); sender.sendMessage(ChatColor.YELLOW+"checkerrors - checks for errors in the config-file"); sender.sendMessage(ChatColor.YELLOW+"players [#] - shows number # page in the list of players"); sender.sendMessage(ChatColor.YELLOW+"groups [#] - shows number # page in the list of groups"); sender.sendMessage(ChatColor.YELLOW+"payday - pays everyone their money, won't run if checkerrors fails"); sender.sendMessage(ChatColor.YELLOW+"payday group/player name - pays a specific group or player"); sender.sendMessage(ChatColor.YELLOW+"set group name value - creates a group with earns value per payday"); sender.sendMessage(ChatColor.YELLOW+"set player name groupname - assigns a player to a group"); sender.sendMessage(ChatColor.YELLOW+"move groupname1 groupname2 - moves all players from one group to another"); sender.sendMessage(ChatColor.YELLOW+"delete player/group name - deletes a group/player"); sender.sendMessage(ChatColor.YELLOW+"sync [overwrite] - imports players and groups from iConomy and Permissions"); sender.sendMessage(ChatColor.RED+"REMEMBER: player-names are CASE-SENSITIVE"); sender.sendMessage(ChatColor.YELLOW+"help 2 for aliases (very useful)"); } else if (page == 2) { sender.sendMessage(ChatColor.YELLOW+"Aliases:"); sender.sendMessage(ChatColor.YELLOW+"player = pl, players = pl, groups = gr"); sender.sendMessage(ChatColor.YELLOW+"group = gr, checkerrors = ce, payday = pd"); sender.sendMessage(ChatColor.YELLOW+"set = s, delete = d, move = mv"); sender.sendMessage(ChatColor.YELLOW+"sync = sy, overwrite = ow"); sender.sendMessage(ChatColor.YELLOW+"Example usage:"); sender.sendMessage(ChatColor.YELLOW+"/pd s gr epicgroup 10000"); sender.sendMessage(ChatColor.YELLOW+"/pd s pl TZer0 epicgroup"); sender.sendMessage(ChatColor.YELLOW+"/pd pd"); sender.sendMessage(ChatColor.YELLOW+"/pd d gr epicgroup"); } else { sender.sendMessage(ChatColor.YELLOW + "No such help-page!"); } return true; } else if (args.length >= 1 && (args[0].equalsIgnoreCase("sync") || (args[0].equalsIgnoreCase("sy")))) { // Imports data from Permissions and iConomy. Bank ic = iConomy.getBank(); if (permissions == null) { sender.sendMessage(ChatColor.RED + "Permissions unavailable - aborting."); } else { boolean overwrite = (args.length == 2 && (args[1].equalsIgnoreCase("overwrite") || args[1].equalsIgnoreCase("ow"))); for (String key: ic.getAccounts().keySet()) { if (conf.getString("players."+key) == null || overwrite) { conf.setProperty("players."+key, permissions.getGroup("world", key).toLowerCase()); if (conf.getString("groups."+permissions.getGroup("world", key).toLowerCase()) == null) { conf.setProperty("groups."+permissions.getGroup("world", key).toLowerCase(), 0); } } } conf.save(); sender.sendMessage(ChatColor.GREEN+"Done!"); } return true; } else if (args.length >= 1 && (args[0].equalsIgnoreCase("checkerrors") || args[0].equalsIgnoreCase("ce"))) { // Utility - checks for errors while not running payday. if (!checkErrors(sender, iConomy.getBank())) { sender.sendMessage(ChatColor.GREEN+"No errors found."); } else { sender.sendMessage(ChatColor.RED + "Errors found, fix them before running payday"); } } else if (args.length >= 1 && (args[0].replace("players", "player").equalsIgnoreCase("player") || args[0].equalsIgnoreCase("pl"))) { // Lists players int page = 0; if (args.length == 2) { page = toInt(args[2], sender); } page(page, sender, "Player"); } else if (args.length >= 1 && (args[0].replace("groups", "group").equalsIgnoreCase("group") || args[0].equalsIgnoreCase("gr"))) { // Lists groups int page = 0; if (args.length == 2) { page = toInt(args[2], sender); } page(page, sender, "Group"); } else if (args.length >= 1 && (args[0].equalsIgnoreCase("payday") || args[0].equalsIgnoreCase("pd"))) { // Attempts to pay out the predefined amounts of cash, fails before paying out anything if // the config is incorrect Bank ic = iConomy.getBank(); if (checkErrors(sender, iConomy.getBank())) { sender.sendMessage(ChatColor.RED + "Errors found, fix them before running payday"); return true; } List<String> pay = null; if (args.length == 3) { pay = new LinkedList<String>(); List<String> full = conf.getKeys("players."); if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { for (String name : full) { if (conf.getString("players."+name).equalsIgnoreCase(args[2])) { pay.add(name); } } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (full.contains(uargs[2])) { pay.add(uargs[2]); } else { sender.sendMessage(ChatColor.RED + "No such player!"); return true; } } else { sender.sendMessage(ChatColor.RED + "Invalid 3rd parameter, must be group or player"); return true; } } else if (args.length == 1) { pay = conf.getKeys("players."); getServer().broadcastMessage(ChatColor.GOLD+"It is Pay Day!"); } if (args.length <= 3 || args.length == 1) { for (String pl : pay) { ic.getAccount(pl).add(conf.getInt("groups."+conf.getString("players."+pl, "none"),0)); } } else { sender.sendMessage(ChatColor.RED+"Incorrect format, see help"); return true; } sender.sendMessage(ChatColor.GREEN+"Payday complete"); } else if (args.length >= 1 && (args[0].equalsIgnoreCase("set") || args[0].equalsIgnoreCase("s"))) { // sets either a group's income or a player's group if (args.length == 4) { if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { if (checkInt(args[3]) && !args[2].equalsIgnoreCase("none")) { conf.setProperty("groups."+args[2], Integer.parseInt(args[3])); conf.save(); sender.sendMessage(ChatColor.GREEN + "Done."); } else { sender.sendMessage("Invalid value."); } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (conf.getString("groups."+args[3]) != null) { conf.setProperty("players."+uargs[2], args[3]); conf.save(); sender.sendMessage(ChatColor.GREEN + "Done."); } else { sender.sendMessage(ChatColor.RED + "No such group"); } } else { sender.sendMessage(ChatColor.RED+ String.format("Unknown type %s!", uargs[2])); return true; } } else { sender.sendMessage(ChatColor.RED+"Invalid format, see help"); } } else if (args.length >= 1 && (args[0].equalsIgnoreCase("move") || args[0].equalsIgnoreCase("mv"))) { // Moves all players from one group to another - even if the group you're moving from does // no longer exist if (args.length == 3) { List<String> groups = conf.getKeys("groups."); if (!groups.contains(args[2])) { sender.sendMessage(ChatColor.RED + String.format("No such group %s", args[2])); } else { List<String> players = conf.getKeys("players."); for (String pl : players) { if (conf.getString("players."+pl).equalsIgnoreCase(args[1])) { conf.setProperty("players."+pl, args[2]); } conf.save(); } } } } else if (args.length >= 1 && (args[0].equalsIgnoreCase("delete") || args[0].equalsIgnoreCase("d"))) { // deletes either a player or a group if (args.length == 3) { if (args[1].equalsIgnoreCase("group") || args[1].equalsIgnoreCase("gr")) { if (conf.getString("groups."+args[2]) != null) { conf.removeProperty("groups."+args[2]); conf.save(); } else { sender.sendMessage(ChatColor.RED+"No such group: " + args[2]); return true; } } else if (args[1].equalsIgnoreCase("player") || args[1].equalsIgnoreCase("pl")) { if (conf.getString("players."+uargs[2]) != null) { conf.removeProperty("players."+uargs[2]); conf.save(); } else { sender.sendMessage(ChatColor.RED+"No such player: " + uargs[2]); return true; } } else { sender.sendMessage(ChatColor.RED+ String.format("Unknown type %s!", args[1])); return true; } sender.sendMessage(ChatColor.GREEN + "Done"); } else { sender.sendMessage(ChatColor.RED+"Incorrect format, see help"); } } else { sender.sendMessage(ChatColor.YELLOW + "No such command, see help!"); } return true; }
diff --git a/Responder.java b/Responder.java index a727d7d..31b045a 100644 --- a/Responder.java +++ b/Responder.java @@ -1,217 +1,217 @@ /* Ahmet Aktay and Nathan Griffith * DarkChat * CS435: Final Project */ import java.io.*; import java.net.*; import java.util.*; class Responder implements Runnable { private Queue<Socket> q; private BufferedInputStream bin; private Socket socket; private UserList knownUsers; private String name; private Message pm; User toUser; User fromUser; User ofUser; public Responder(Queue<Socket> q, UserList knownUsers, Message pm, String name){ this.q = q; this.knownUsers = knownUsers; this.name = name; this.pm = pm; } public void run() { try { MyUtils.dPrintLine(String.format("Launching thread %s", name)); //Wait for an item to enter the socket queue while(true) { socket = null; while (socket==null) { synchronized(q) { while (q.isEmpty()) { try { q.wait(500); } catch (InterruptedException e) { MyUtils.dPrintLine("Connection interrupted"); } } socket = q.poll(); } } MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort())); // create read stream to get input BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); String ln = inFromClient.readLine(); int port = socket.getPort(); if (ln.equals("ONL")) //fromUser is online { ln = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String state = inFromClient.readLine(); //DEAL WITH USER synchronized (knownUsers) { fromUser = knownUsers.get(ln,true); //only get if exists } synchronized (fromUser) { if (fromUser != null) { fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); if (!fromUser.name.equals(pm.localUser.name)) { System.out.println(String.format("'%s' is online", fromUser.name)); if (state.equals("INIT")) { synchronized (pm) { pm.declareOnline(fromUser, false); } } } } } } else if (ln.equals("OFL")) { ln = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); //DEAL WITH USER synchronized (knownUsers) { fromUser = knownUsers.get(ln,true); //only get if exists } synchronized (fromUser) { if (fromUser != null) { fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); if (!fromUser.name.equals(pm.localUser.name)) { System.out.println(String.format("'%s' is offline", fromUser.name)); } } } } else if (ln.equals("CHT")) //fromUser is chatting with you! { String fromUsername = inFromClient.readLine(); String toUsername = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); ln = inFromClient.readLine(); synchronized (knownUsers) { fromUser = knownUsers.get(fromUsername,true); //only get if exists toUser = knownUsers.get(toUsername, true); } synchronized (fromUser) { if (!toUser.name.equals(pm.localUser.name)) { MyUtils.dPrintLine("Recieved chat with incorrect user fields:"); MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln)); } else if (fromUser != null) { System.out.println(String.format("%s: %s", fromUser.name,ln)); fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); } else { MyUtils.dPrintLine("Recieved chat from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); } } } else if (ln.equals("REQ")) // someone is requesting known users { String fromUserName = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String ofUserName = inFromClient.readLine(); Boolean friends = false; synchronized (knownUsers) { fromUser = knownUsers.get(fromUserName,true); ofUser = knownUsers.get(ofUserName,true); } if (fromUser == null) { MyUtils.dPrintLine("Recieved knowns REQuest from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); // do not respond } else if (ofUser == null) { MyUtils.dPrintLine("Recieved knowns REQuest of unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln)); pm.deliverFakeKnownList(ofUserName, fromUser); } else if (!friends) { MyUtils.dPrintLine("Recieved REQuest where users haven't met."); - MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list")); + MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list", fromUser.name, ofUserName)); pm.deliverFakeKnownList(ofUserName, fromUser); } else { MyUtils.dPrintLine("Received valid REQuest where users have met."); MyUtils.dPrintLine(String.format("%s wanted %s's knowns, delivering them via BUD.", fromUser, ofUser)); pm.deliverKnownList(ofUser, fromUser); } } else if (ln.equals("BUD")) // someone is delivering known users // TODO: check if we requested one { // String message = String.format("BUD\n%s\n%s\n", localUser.name, port, ofUserName); // String fromUserName = inFromClient.readLine(); // String ofUserName = inFromClient.readLine(); // port = Integer.parseInt(inFromClient.readLine()); // Boolean friends = false; // synchronized (knownUsers) { // fromUser = knownUsers.get(fromUserName,true); // ofUser = knownUsers.get(ofUserName,true); // } String fromUserName = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String ofUserName = inFromClient.readLine(); synchronized (knownUsers) { fromUser = knownUsers.get(fromUserName,true); ofUser = knownUsers.get(ofUserName,true); } if (fromUser == null) { MyUtils.dPrintLine("Recieved BUDs from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); } else if (ofUser == null) { MyUtils.dPrintLine("Recieved BUDs of unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln)); } else { MyUtils.dPrintLine("Received valid BUDs"); MyUtils.dPrintLine(String.format("%s sent %s's knowns, delivering them via BUD.", fromUser, ofUser)); synchronized(ofUser) { synchronized(knownUsers) { String budName = inFromClient.readLine(); while(budName != "") { User budUser = knownUsers.get(budName); synchronized (budUser) { ofUser.meetUser(budUser); } } budName = inFromClient.readLine(); } } } } else MyUtils.dPrintLine("Unrecognized message format"); socket.close(); } } catch (Exception e) { MyUtils.dPrintLine(String.format("%s",e)); //some sort of exception } } }
true
true
public void run() { try { MyUtils.dPrintLine(String.format("Launching thread %s", name)); //Wait for an item to enter the socket queue while(true) { socket = null; while (socket==null) { synchronized(q) { while (q.isEmpty()) { try { q.wait(500); } catch (InterruptedException e) { MyUtils.dPrintLine("Connection interrupted"); } } socket = q.poll(); } } MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort())); // create read stream to get input BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); String ln = inFromClient.readLine(); int port = socket.getPort(); if (ln.equals("ONL")) //fromUser is online { ln = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String state = inFromClient.readLine(); //DEAL WITH USER synchronized (knownUsers) { fromUser = knownUsers.get(ln,true); //only get if exists } synchronized (fromUser) { if (fromUser != null) { fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); if (!fromUser.name.equals(pm.localUser.name)) { System.out.println(String.format("'%s' is online", fromUser.name)); if (state.equals("INIT")) { synchronized (pm) { pm.declareOnline(fromUser, false); } } } } } } else if (ln.equals("OFL")) { ln = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); //DEAL WITH USER synchronized (knownUsers) { fromUser = knownUsers.get(ln,true); //only get if exists } synchronized (fromUser) { if (fromUser != null) { fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); if (!fromUser.name.equals(pm.localUser.name)) { System.out.println(String.format("'%s' is offline", fromUser.name)); } } } } else if (ln.equals("CHT")) //fromUser is chatting with you! { String fromUsername = inFromClient.readLine(); String toUsername = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); ln = inFromClient.readLine(); synchronized (knownUsers) { fromUser = knownUsers.get(fromUsername,true); //only get if exists toUser = knownUsers.get(toUsername, true); } synchronized (fromUser) { if (!toUser.name.equals(pm.localUser.name)) { MyUtils.dPrintLine("Recieved chat with incorrect user fields:"); MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln)); } else if (fromUser != null) { System.out.println(String.format("%s: %s", fromUser.name,ln)); fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); } else { MyUtils.dPrintLine("Recieved chat from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); } } } else if (ln.equals("REQ")) // someone is requesting known users { String fromUserName = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String ofUserName = inFromClient.readLine(); Boolean friends = false; synchronized (knownUsers) { fromUser = knownUsers.get(fromUserName,true); ofUser = knownUsers.get(ofUserName,true); } if (fromUser == null) { MyUtils.dPrintLine("Recieved knowns REQuest from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); // do not respond } else if (ofUser == null) { MyUtils.dPrintLine("Recieved knowns REQuest of unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln)); pm.deliverFakeKnownList(ofUserName, fromUser); } else if (!friends) { MyUtils.dPrintLine("Recieved REQuest where users haven't met."); MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list")); pm.deliverFakeKnownList(ofUserName, fromUser); } else { MyUtils.dPrintLine("Received valid REQuest where users have met."); MyUtils.dPrintLine(String.format("%s wanted %s's knowns, delivering them via BUD.", fromUser, ofUser)); pm.deliverKnownList(ofUser, fromUser); } } else if (ln.equals("BUD")) // someone is delivering known users // TODO: check if we requested one { // String message = String.format("BUD\n%s\n%s\n", localUser.name, port, ofUserName); // String fromUserName = inFromClient.readLine(); // String ofUserName = inFromClient.readLine(); // port = Integer.parseInt(inFromClient.readLine()); // Boolean friends = false; // synchronized (knownUsers) { // fromUser = knownUsers.get(fromUserName,true); // ofUser = knownUsers.get(ofUserName,true); // } String fromUserName = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String ofUserName = inFromClient.readLine(); synchronized (knownUsers) { fromUser = knownUsers.get(fromUserName,true); ofUser = knownUsers.get(ofUserName,true); } if (fromUser == null) { MyUtils.dPrintLine("Recieved BUDs from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); } else if (ofUser == null) { MyUtils.dPrintLine("Recieved BUDs of unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln)); } else { MyUtils.dPrintLine("Received valid BUDs"); MyUtils.dPrintLine(String.format("%s sent %s's knowns, delivering them via BUD.", fromUser, ofUser)); synchronized(ofUser) { synchronized(knownUsers) { String budName = inFromClient.readLine(); while(budName != "") { User budUser = knownUsers.get(budName); synchronized (budUser) { ofUser.meetUser(budUser); } } budName = inFromClient.readLine(); } } } } else MyUtils.dPrintLine("Unrecognized message format"); socket.close(); } } catch (Exception e) { MyUtils.dPrintLine(String.format("%s",e)); //some sort of exception } }
public void run() { try { MyUtils.dPrintLine(String.format("Launching thread %s", name)); //Wait for an item to enter the socket queue while(true) { socket = null; while (socket==null) { synchronized(q) { while (q.isEmpty()) { try { q.wait(500); } catch (InterruptedException e) { MyUtils.dPrintLine("Connection interrupted"); } } socket = q.poll(); } } MyUtils.dPrintLine(String.format("Connection from %s:%s", socket.getInetAddress().getHostName(),socket.getPort())); // create read stream to get input BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream())); String ln = inFromClient.readLine(); int port = socket.getPort(); if (ln.equals("ONL")) //fromUser is online { ln = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String state = inFromClient.readLine(); //DEAL WITH USER synchronized (knownUsers) { fromUser = knownUsers.get(ln,true); //only get if exists } synchronized (fromUser) { if (fromUser != null) { fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); if (!fromUser.name.equals(pm.localUser.name)) { System.out.println(String.format("'%s' is online", fromUser.name)); if (state.equals("INIT")) { synchronized (pm) { pm.declareOnline(fromUser, false); } } } } } } else if (ln.equals("OFL")) { ln = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); //DEAL WITH USER synchronized (knownUsers) { fromUser = knownUsers.get(ln,true); //only get if exists } synchronized (fromUser) { if (fromUser != null) { fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); if (!fromUser.name.equals(pm.localUser.name)) { System.out.println(String.format("'%s' is offline", fromUser.name)); } } } } else if (ln.equals("CHT")) //fromUser is chatting with you! { String fromUsername = inFromClient.readLine(); String toUsername = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); ln = inFromClient.readLine(); synchronized (knownUsers) { fromUser = knownUsers.get(fromUsername,true); //only get if exists toUser = knownUsers.get(toUsername, true); } synchronized (fromUser) { if (!toUser.name.equals(pm.localUser.name)) { MyUtils.dPrintLine("Recieved chat with incorrect user fields:"); MyUtils.dPrintLine(String.format("%s to %s: %s", fromUser.name,toUser.name,ln)); } else if (fromUser != null) { System.out.println(String.format("%s: %s", fromUser.name,ln)); fromUser.putSession(new InetSocketAddress(socket.getInetAddress(),port)); } else { MyUtils.dPrintLine("Recieved chat from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); } } } else if (ln.equals("REQ")) // someone is requesting known users { String fromUserName = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String ofUserName = inFromClient.readLine(); Boolean friends = false; synchronized (knownUsers) { fromUser = knownUsers.get(fromUserName,true); ofUser = knownUsers.get(ofUserName,true); } if (fromUser == null) { MyUtils.dPrintLine("Recieved knowns REQuest from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); // do not respond } else if (ofUser == null) { MyUtils.dPrintLine("Recieved knowns REQuest of unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln)); pm.deliverFakeKnownList(ofUserName, fromUser); } else if (!friends) { MyUtils.dPrintLine("Recieved REQuest where users haven't met."); MyUtils.dPrintLine(String.format("%s wanted %s's knowns but hadn't met them. delivering empty list", fromUser.name, ofUserName)); pm.deliverFakeKnownList(ofUserName, fromUser); } else { MyUtils.dPrintLine("Received valid REQuest where users have met."); MyUtils.dPrintLine(String.format("%s wanted %s's knowns, delivering them via BUD.", fromUser, ofUser)); pm.deliverKnownList(ofUser, fromUser); } } else if (ln.equals("BUD")) // someone is delivering known users // TODO: check if we requested one { // String message = String.format("BUD\n%s\n%s\n", localUser.name, port, ofUserName); // String fromUserName = inFromClient.readLine(); // String ofUserName = inFromClient.readLine(); // port = Integer.parseInt(inFromClient.readLine()); // Boolean friends = false; // synchronized (knownUsers) { // fromUser = knownUsers.get(fromUserName,true); // ofUser = knownUsers.get(ofUserName,true); // } String fromUserName = inFromClient.readLine(); port = Integer.parseInt(inFromClient.readLine()); String ofUserName = inFromClient.readLine(); synchronized (knownUsers) { fromUser = knownUsers.get(fromUserName,true); ofUser = knownUsers.get(ofUserName,true); } if (fromUser == null) { MyUtils.dPrintLine("Recieved BUDs from unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", fromUser.name,ln)); } else if (ofUser == null) { MyUtils.dPrintLine("Recieved BUDs of unknown user:"); MyUtils.dPrintLine(String.format("%s: %s", ofUser.name,ln)); } else { MyUtils.dPrintLine("Received valid BUDs"); MyUtils.dPrintLine(String.format("%s sent %s's knowns, delivering them via BUD.", fromUser, ofUser)); synchronized(ofUser) { synchronized(knownUsers) { String budName = inFromClient.readLine(); while(budName != "") { User budUser = knownUsers.get(budName); synchronized (budUser) { ofUser.meetUser(budUser); } } budName = inFromClient.readLine(); } } } } else MyUtils.dPrintLine("Unrecognized message format"); socket.close(); } } catch (Exception e) { MyUtils.dPrintLine(String.format("%s",e)); //some sort of exception } }
diff --git a/org.eclipse.virgo.ide.runtime.core/src/org/eclipse/virgo/ide/runtime/internal/core/runtimes/VirgoRuntimeProvider.java b/org.eclipse.virgo.ide.runtime.core/src/org/eclipse/virgo/ide/runtime/internal/core/runtimes/VirgoRuntimeProvider.java index 8270598..5411a32 100644 --- a/org.eclipse.virgo.ide.runtime.core/src/org/eclipse/virgo/ide/runtime/internal/core/runtimes/VirgoRuntimeProvider.java +++ b/org.eclipse.virgo.ide.runtime.core/src/org/eclipse/virgo/ide/runtime/internal/core/runtimes/VirgoRuntimeProvider.java @@ -1,429 +1,429 @@ /******************************************************************************* * Copyright (c) 2010 SpringSource, a divison of VMware, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * SpringSource, a division of VMware, Inc. - initial API and implementation *******************************************************************************/ package org.eclipse.virgo.ide.runtime.internal.core.runtimes; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Status; import org.eclipse.jdt.launching.IRuntimeClasspathEntry; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.libra.framework.editor.core.model.IBundle; import org.eclipse.virgo.ide.manifest.core.dependencies.IDependencyLocator; import org.eclipse.virgo.ide.manifest.core.dependencies.IDependencyLocator.JavaVersion; import org.eclipse.virgo.ide.runtime.core.IServerBehaviour; import org.eclipse.virgo.ide.runtime.core.IServerRuntimeProvider; import org.eclipse.virgo.ide.runtime.core.ServerCorePlugin; import org.eclipse.virgo.ide.runtime.core.ServerUtils; import org.eclipse.virgo.ide.runtime.internal.core.DeploymentIdentity; import org.eclipse.virgo.ide.runtime.internal.core.command.GenericJmxServerDeployCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.IServerCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxBundleAdminExecuteCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxBundleAdminServerCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxServerDeployCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxServerPingCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxServerRefreshCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxServerShutdownCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxServerUndeployCommand; import org.eclipse.virgo.ide.runtime.internal.core.command.JmxServerUpdateCommand; import org.eclipse.virgo.util.common.StringUtils; import org.eclipse.wst.server.core.IModule; import org.eclipse.wst.server.core.IRuntime; import org.eclipse.wst.server.core.IServer; import org.eclipse.wst.server.core.model.IModuleFile; import org.eclipse.wst.server.core.util.PublishHelper; /** * {@link IServerRuntimeProvider} for Generic Virgo Server. * * @author Terry Hon * @author Christian Dupuis * @author Miles Parker * @since 2.0.0 */ public abstract class VirgoRuntimeProvider implements IServerRuntimeProvider { private static final String EXT_DIR = "ext"; private static final String USR_DIR = "usr"; private static final String REPOSITORY_DIR = "repository"; public static final String SERVER_VIRGO_BASE = "org.eclipse.virgo.server.runtime.virgo"; private static final String BUNDLE_OBJECT_NAME = "org.eclipse.virgo.kernel:type=Model,artifact-type=bundle,name=$NAME,version=$VERSION"; private static final String DEPLOYER_MBEAN_NAME = "org.eclipse.virgo.kernel:category=Control,type=Deployer"; private static final String PAR_OBJECT_NAME = "org.eclipse.virgo.kernel:type=Model,artifact-type=par,name=$NAME,version=$VERSION"; private static final String PLAN_OBJECT_NAME = "org.eclipse.virgo.kernel:type=Model,artifact-type=plan,name=$NAME,version=$VERSION"; private static final String RECOVERY_MONITOR_MBEAN_NAME = "org.eclipse.virgo.kernel:category=Control,type=RecoveryMonitor"; private static final String SHUTDOWN_MBEAN_NAME = "org.eclipse.virgo.kernel:type=Shutdown"; /** * {@inheritDoc} */ public String getDeployerMBeanName() { return DEPLOYER_MBEAN_NAME; } /** * {@inheritDoc} */ public String getRecoveryMonitorMBeanName() { return RECOVERY_MONITOR_MBEAN_NAME; } /** * {@inheritDoc} Provides generic runtime arguments shared by all versions. */ public String[] getRuntimeVMArguments(IServerBehaviour behaviour, IPath installPath, IPath configPath, IPath deployPath) { String serverHome = ServerUtils.getServer(behaviour).getRuntimeBaseDirectory().toOSString(); List<String> list = new ArrayList<String>(); list.add("-XX:+HeapDumpOnOutOfMemoryError"); list.add("-XX:ErrorFile=\"" + serverHome + "/serviceability/error.log\""); list.add("-XX:HeapDumpPath=\"" + serverHome + "/serviceability/heap_dump.hprof\""); list.add("-Djava.rmi.server.hostname=127.0.0.1"); list.add("-Dorg.eclipse.virgo.kernel.home=\"" + serverHome + "\""); list.add("-Djava.io.tmpdir=\"" + serverHome + "/work/tmp/\""); list.add("-Dcom.sun.management.jmxremote"); list.add("-Dcom.sun.management.jmxremote.port=" + ServerUtils.getServer(behaviour).getMBeanServerPort()); list.add("-Dcom.sun.management.jmxremote.authenticate=false"); list.add("-Dcom.sun.management.jmxremote.ssl=false"); list.add("-Dorg.eclipse.virgo.kernel.authentication.file=\"" + serverHome + "/" + getConfigDir() + "/org.eclipse.virgo.kernel.users.properties\""); list.add("-Djava.security.auth.login.config=\"" + serverHome + "/" + getConfigDir() + "/org.eclipse.virgo.kernel.authentication.config\""); if (getInstallationType(ServerUtils.getServer(behaviour).getRuntime().getRuntime()) == InstallationType.JETTY) { list.add("-Djetty.home=\"" + serverHome + "/jetty\""); } return list.toArray(new String[list.size()]); } /** * {@inheritDoc} */ public IServerCommand<Void> getServerUndeployCommand(IServerBehaviour serverBehaviour, IModule module) { return new JmxServerUndeployCommand(serverBehaviour, module, BUNDLE_OBJECT_NAME, PAR_OBJECT_NAME, PLAN_OBJECT_NAME); } /** * {@inheritDoc} */ public IServerCommand<Void> getServerUpdateCommand(IServerBehaviour serverBehaviour, IModule module, IModuleFile moduleFile, DeploymentIdentity identity, String bundleSymbolicName, String targetPath) { return new JmxServerUpdateCommand(serverBehaviour, module, moduleFile, identity, bundleSymbolicName, targetPath, BUNDLE_OBJECT_NAME, PAR_OBJECT_NAME, PLAN_OBJECT_NAME); } /** * {@inheritDoc} */ public String getShutdownMBeanName() { return SHUTDOWN_MBEAN_NAME; } /** * {@inheritDoc} * * @throws IOException */ public Properties getProperties(IPath installPath, String type) throws IOException { String version = installPath.append("lib").append("." + type).toOSString(); File versionFile = new File(version); if (versionFile.exists()) { InputStream is = null; is = new FileInputStream(versionFile); Properties versionProperties = new Properties(); versionProperties.load(is); try { is.close(); } catch (IOException e) { } return versionProperties; } else { throw new IOException("Installation does not contain a properties file. Path: " + installPath); } } protected String getRepositoryConfigurationFileName() { return "org.eclipse.virgo.repository.properties"; } /** * {@inheritDoc} */ public IStatus canAddModule(IModule module) { return Status.OK_STATUS; } public IServerCommand<Boolean> getServerPingCommand(IServerBehaviour IServerBehaviour) { return new JmxServerPingCommand(IServerBehaviour); } /** * {@inheritDoc} */ public IServerCommand<Void> getServerShutdownCommand(IServerBehaviour IServerBehaviour) { return new JmxServerShutdownCommand(IServerBehaviour); } /** * {@inheritDoc} */ public IServerCommand<Void> getServerRefreshCommand(IServerBehaviour IServerBehaviour, IModule module, String bundleSymbolicName) { return new JmxServerRefreshCommand(IServerBehaviour, module, bundleSymbolicName); } /** * {@inheritDoc} */ public IServerCommand<DeploymentIdentity> getServerDeployCommand(IServerBehaviour IServerBehaviour, URI connectorBundleUri) { return new GenericJmxServerDeployCommand(IServerBehaviour, connectorBundleUri); } /** * {@inheritDoc} */ public String[] getExcludedRuntimeProgramArguments(boolean starting) { List<String> list = new ArrayList<String>(); return list.toArray(new String[list.size()]); } /** * {@inheritDoc} */ public String getConfigPath(IRuntime runtime) { return runtime.getLocation().append(getConfigDir()).append("server.config").toString(); } /** * {@inheritDoc} */ public String getProfilePath(IRuntime runtime) { return runtime.getLocation().append(getProfileDir()).append("java6-server.profile").toString(); } /** * {@inheritDoc} */ public IPath getRuntimeBaseDirectory(IServer server) { return server.getRuntime().getLocation(); } /** * Provides runtime class path common to server versions. * * @see org.eclipse.virgo.ide.runtime.core.IServerRuntimeProvider#getRuntimeClasspath(org.eclipse.core.runtime.IPath) */ public List<IRuntimeClasspathEntry> getRuntimeClasspath(IPath installPath) { List<IRuntimeClasspathEntry> cp = new ArrayList<IRuntimeClasspathEntry>(); IPath binPath = installPath.append("lib"); if (binPath.toFile().exists()) { File libFolder = binPath.toFile(); for (File library : libFolder.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && pathname.toString().endsWith(".jar"); } })) { IPath path = binPath.append(library.getName()); cp.add(JavaRuntime.newArchiveRuntimeClasspathEntry(path)); } } return cp; } /** * {@inheritDoc} */ public String getUserLevelBundleRepositoryPath(IRuntime runtime) { return runtime.getLocation().append(REPOSITORY_DIR).append(USR_DIR).toString(); } /** * {@inheritDoc} */ public String getUserLevelLibraryRepositoryPath(IRuntime runtime) { return runtime.getLocation().append(REPOSITORY_DIR).append(USR_DIR).toString(); } /** * @see org.eclipse.virgo.ide.runtime.core.IServerRuntimeProvider#getExtLevelBundleRepositoryPath(org.eclipse.wst.server.core.IRuntime) */ public String getExtLevelBundleRepositoryPath(IRuntime runtime) { return runtime.getLocation().append(REPOSITORY_DIR).append(EXT_DIR).toString(); } /** * {@inheritDoc} */ public IServerCommand<DeploymentIdentity> getServerDeployCommand(IServerBehaviour IServerBehaviour, IModule module) { return new JmxServerDeployCommand(IServerBehaviour, module); } /** * {@inheritDoc} */ public IServerCommand<Map<Long, IBundle>> getServerBundleAdminCommand(IServerBehaviour serverBehaviour) { return new JmxBundleAdminServerCommand(serverBehaviour); } /** * {@inheritDoc} */ public IServerCommand<String> getServerBundleAdminExecuteCommand(IServerBehaviour serverBehaviour, String command) { return new JmxBundleAdminExecuteCommand(serverBehaviour, command); } private void createRepositoryConfiguration(IServerBehaviour serverBehaviour, String fileName) { // copy repository.properties into the stage and add the stage // repository File serverHome = ServerUtils.getServer(serverBehaviour).getRuntimeBaseDirectory().toFile(); Properties properties = new Properties(); try { - properties.load(new FileInputStream(new File(serverHome, "config" + File.separatorChar + fileName))); + properties.load(new FileInputStream(new File(serverHome, getConfigDir() + File.separatorChar + fileName))); } catch (FileNotFoundException e) { // TODO CD add logging } catch (IOException e) { // TODO CD add logging } properties.put("stage.type", "watched"); properties.put("stage.watchDirectory", "stage"); String chain = properties.getProperty("chain"); chain = "stage" + (StringUtils.hasLength(chain) ? "," + chain : ""); properties.put("chain", chain); try { File stageDirectory = new File(serverHome, "stage"); if (!stageDirectory.exists()) { stageDirectory.mkdirs(); } properties.store( new FileOutputStream(new File(serverHome, "stage" + File.separator + fileName)), "Generated by Virgo IDE " + ServerCorePlugin.getDefault().getBundle().getVersion()); } catch (FileNotFoundException e) { // TODO CD add logging } catch (IOException e) { // TODO CD add logging } } public void preStartup(IServerBehaviour serverBehaviour) { if (ServerUtils.getServer(serverBehaviour).shouldCleanStartup()) { File serverHome = ServerUtils.getServer(serverBehaviour).getRuntimeBaseDirectory().toFile(); PublishHelper.deleteDirectory(new File(serverHome, "work"), new NullProgressMonitor()); PublishHelper.deleteDirectory(new File(serverHome, "serviceability"), new NullProgressMonitor()); } createRepositoryConfiguration(serverBehaviour, getRepositoryConfigurationFileName()); } public boolean isHandlerFor(IRuntime runtime) { IPath configPath = runtime.getLocation().append(getConfigDir()); File configDir = configPath.toFile(); return configDir.exists(); } /** * {@inheritDoc} */ public IStatus verifyInstallation(IRuntime runtime) { InstallationType installation = getInstallationType(runtime); if (installation == null) { return new Status(Status.ERROR, ServerCorePlugin.PLUGIN_ID, "Invalid Virgo Server: Could not determine version."); } return new Status(Status.OK, ServerCorePlugin.PLUGIN_ID, "Valid installation: " + getName(runtime) + "."); } public InstallationType getInstallationType(IRuntime runtime) { Properties versionProperties; IPath location = runtime.getLocation(); try { versionProperties = getProperties(location, "version"); } catch (IOException e) { return null; } String versionString = versionProperties.getProperty("virgo.server.version"); if (versionString != null) { if (location.append("jetty").toFile().exists()) { return InstallationType.JETTY; } else { return InstallationType.TOMCAT; } } versionString = versionProperties.getProperty("virgo.kernel.version"); if (versionString != null) { return InstallationType.KERNEL; } return null; } public String getVersionName(IRuntime runtime) { Properties versionProperties; try { versionProperties = getProperties(runtime.getLocation(), "version"); } catch (IOException e) { return null; } String versionString = versionProperties.getProperty("virgo.server.version"); if (versionString == null) { versionString = versionProperties.getProperty("virgo.kernel.version"); } if (versionString == null) { versionString = versionProperties.getProperty("virgo.nano.version"); } if (versionString == null) { versionString = "Unknown"; } return versionString; } public String getName(IRuntime runtime) { return getInstallationType(runtime).getName() + " v" + getVersionName(runtime); } public abstract String getID(); public abstract String getSupportedVersions(); /** * Non-API */ abstract String getConfigDir(); /** * Non-API */ abstract String getProfileDir(); }
true
true
private void createRepositoryConfiguration(IServerBehaviour serverBehaviour, String fileName) { // copy repository.properties into the stage and add the stage // repository File serverHome = ServerUtils.getServer(serverBehaviour).getRuntimeBaseDirectory().toFile(); Properties properties = new Properties(); try { properties.load(new FileInputStream(new File(serverHome, "config" + File.separatorChar + fileName))); } catch (FileNotFoundException e) { // TODO CD add logging } catch (IOException e) { // TODO CD add logging } properties.put("stage.type", "watched"); properties.put("stage.watchDirectory", "stage"); String chain = properties.getProperty("chain"); chain = "stage" + (StringUtils.hasLength(chain) ? "," + chain : ""); properties.put("chain", chain); try { File stageDirectory = new File(serverHome, "stage"); if (!stageDirectory.exists()) { stageDirectory.mkdirs(); } properties.store( new FileOutputStream(new File(serverHome, "stage" + File.separator + fileName)), "Generated by Virgo IDE " + ServerCorePlugin.getDefault().getBundle().getVersion()); } catch (FileNotFoundException e) { // TODO CD add logging } catch (IOException e) { // TODO CD add logging } }
private void createRepositoryConfiguration(IServerBehaviour serverBehaviour, String fileName) { // copy repository.properties into the stage and add the stage // repository File serverHome = ServerUtils.getServer(serverBehaviour).getRuntimeBaseDirectory().toFile(); Properties properties = new Properties(); try { properties.load(new FileInputStream(new File(serverHome, getConfigDir() + File.separatorChar + fileName))); } catch (FileNotFoundException e) { // TODO CD add logging } catch (IOException e) { // TODO CD add logging } properties.put("stage.type", "watched"); properties.put("stage.watchDirectory", "stage"); String chain = properties.getProperty("chain"); chain = "stage" + (StringUtils.hasLength(chain) ? "," + chain : ""); properties.put("chain", chain); try { File stageDirectory = new File(serverHome, "stage"); if (!stageDirectory.exists()) { stageDirectory.mkdirs(); } properties.store( new FileOutputStream(new File(serverHome, "stage" + File.separator + fileName)), "Generated by Virgo IDE " + ServerCorePlugin.getDefault().getBundle().getVersion()); } catch (FileNotFoundException e) { // TODO CD add logging } catch (IOException e) { // TODO CD add logging } }
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/blockpacked/TestForUtil.java b/lucene/core/src/test/org/apache/lucene/codecs/blockpacked/TestForUtil.java index 834e8fbab8..158328fb02 100644 --- a/lucene/core/src/test/org/apache/lucene/codecs/blockpacked/TestForUtil.java +++ b/lucene/core/src/test/org/apache/lucene/codecs/blockpacked/TestForUtil.java @@ -1,94 +1,94 @@ package org.apache.lucene.codecs.blockpacked; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import static org.apache.lucene.codecs.blockpacked.BlockPackedPostingsFormat.BLOCK_SIZE; import static org.apache.lucene.codecs.blockpacked.ForUtil.MIN_DATA_SIZE; import static org.apache.lucene.codecs.blockpacked.ForUtil.MIN_ENCODED_SIZE; import java.io.IOException; import java.util.Arrays; import org.apache.lucene.store.Directory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util.packed.PackedInts; import com.carrotsearch.randomizedtesting.generators.RandomInts; public class TestForUtil extends LuceneTestCase { public void testEncodeDecode() throws IOException { final int iterations = RandomInts.randomIntBetween(random(), 1, 1000); final float acceptableOverheadRatio = random().nextFloat(); - final int[] values = new int[iterations * BLOCK_SIZE + ForUtil.MIN_DATA_SIZE]; + final int[] values = new int[(iterations - 1) * BLOCK_SIZE + ForUtil.MIN_DATA_SIZE]; for (int i = 0; i < iterations; ++i) { final int bpv = random().nextInt(32); if (bpv == 0) { final int value = RandomInts.randomIntBetween(random(), 0, Integer.MAX_VALUE); for (int j = 0; j < BLOCK_SIZE; ++j) { values[i * BLOCK_SIZE + j] = value; } } else { for (int j = 0; j < BLOCK_SIZE; ++j) { values[i * BLOCK_SIZE + j] = RandomInts.randomIntBetween(random(), 0, (int) PackedInts.maxValue(bpv)); } } } final Directory d = new RAMDirectory(); final long endPointer; { // encode IndexOutput out = d.createOutput("test.bin", IOContext.DEFAULT); final ForUtil forUtil = new ForUtil(acceptableOverheadRatio, out); for (int i = 0; i < iterations; ++i) { forUtil.writeBlock( - Arrays.copyOfRange(values, iterations * BLOCK_SIZE, values.length), + Arrays.copyOfRange(values, i * BLOCK_SIZE, values.length), new byte[MIN_ENCODED_SIZE], out); } endPointer = out.getFilePointer(); out.close(); } { // decode IndexInput in = d.openInput("test.bin", IOContext.READONCE); final ForUtil forUtil = new ForUtil(in); for (int i = 0; i < iterations; ++i) { if (random().nextBoolean()) { forUtil.skipBlock(in); continue; } final int[] restored = new int[MIN_DATA_SIZE]; forUtil.readBlock(in, new byte[MIN_ENCODED_SIZE], restored); - assertArrayEquals(Arrays.copyOfRange(values, iterations * BLOCK_SIZE, (iterations + 1) * BLOCK_SIZE), + assertArrayEquals(Arrays.copyOfRange(values, i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE), Arrays.copyOf(restored, BLOCK_SIZE)); } assertEquals(endPointer, in.getFilePointer()); in.close(); } } }
false
true
public void testEncodeDecode() throws IOException { final int iterations = RandomInts.randomIntBetween(random(), 1, 1000); final float acceptableOverheadRatio = random().nextFloat(); final int[] values = new int[iterations * BLOCK_SIZE + ForUtil.MIN_DATA_SIZE]; for (int i = 0; i < iterations; ++i) { final int bpv = random().nextInt(32); if (bpv == 0) { final int value = RandomInts.randomIntBetween(random(), 0, Integer.MAX_VALUE); for (int j = 0; j < BLOCK_SIZE; ++j) { values[i * BLOCK_SIZE + j] = value; } } else { for (int j = 0; j < BLOCK_SIZE; ++j) { values[i * BLOCK_SIZE + j] = RandomInts.randomIntBetween(random(), 0, (int) PackedInts.maxValue(bpv)); } } } final Directory d = new RAMDirectory(); final long endPointer; { // encode IndexOutput out = d.createOutput("test.bin", IOContext.DEFAULT); final ForUtil forUtil = new ForUtil(acceptableOverheadRatio, out); for (int i = 0; i < iterations; ++i) { forUtil.writeBlock( Arrays.copyOfRange(values, iterations * BLOCK_SIZE, values.length), new byte[MIN_ENCODED_SIZE], out); } endPointer = out.getFilePointer(); out.close(); } { // decode IndexInput in = d.openInput("test.bin", IOContext.READONCE); final ForUtil forUtil = new ForUtil(in); for (int i = 0; i < iterations; ++i) { if (random().nextBoolean()) { forUtil.skipBlock(in); continue; } final int[] restored = new int[MIN_DATA_SIZE]; forUtil.readBlock(in, new byte[MIN_ENCODED_SIZE], restored); assertArrayEquals(Arrays.copyOfRange(values, iterations * BLOCK_SIZE, (iterations + 1) * BLOCK_SIZE), Arrays.copyOf(restored, BLOCK_SIZE)); } assertEquals(endPointer, in.getFilePointer()); in.close(); } }
public void testEncodeDecode() throws IOException { final int iterations = RandomInts.randomIntBetween(random(), 1, 1000); final float acceptableOverheadRatio = random().nextFloat(); final int[] values = new int[(iterations - 1) * BLOCK_SIZE + ForUtil.MIN_DATA_SIZE]; for (int i = 0; i < iterations; ++i) { final int bpv = random().nextInt(32); if (bpv == 0) { final int value = RandomInts.randomIntBetween(random(), 0, Integer.MAX_VALUE); for (int j = 0; j < BLOCK_SIZE; ++j) { values[i * BLOCK_SIZE + j] = value; } } else { for (int j = 0; j < BLOCK_SIZE; ++j) { values[i * BLOCK_SIZE + j] = RandomInts.randomIntBetween(random(), 0, (int) PackedInts.maxValue(bpv)); } } } final Directory d = new RAMDirectory(); final long endPointer; { // encode IndexOutput out = d.createOutput("test.bin", IOContext.DEFAULT); final ForUtil forUtil = new ForUtil(acceptableOverheadRatio, out); for (int i = 0; i < iterations; ++i) { forUtil.writeBlock( Arrays.copyOfRange(values, i * BLOCK_SIZE, values.length), new byte[MIN_ENCODED_SIZE], out); } endPointer = out.getFilePointer(); out.close(); } { // decode IndexInput in = d.openInput("test.bin", IOContext.READONCE); final ForUtil forUtil = new ForUtil(in); for (int i = 0; i < iterations; ++i) { if (random().nextBoolean()) { forUtil.skipBlock(in); continue; } final int[] restored = new int[MIN_DATA_SIZE]; forUtil.readBlock(in, new byte[MIN_ENCODED_SIZE], restored); assertArrayEquals(Arrays.copyOfRange(values, i * BLOCK_SIZE, (i + 1) * BLOCK_SIZE), Arrays.copyOf(restored, BLOCK_SIZE)); } assertEquals(endPointer, in.getFilePointer()); in.close(); } }
diff --git a/src/com/matburt/mobileorg/OrgFileParser.java b/src/com/matburt/mobileorg/OrgFileParser.java index 1b71640..d665d44 100644 --- a/src/com/matburt/mobileorg/OrgFileParser.java +++ b/src/com/matburt/mobileorg/OrgFileParser.java @@ -1,402 +1,404 @@ package com.matburt.mobileorg; import java.util.Map; import java.util.ArrayList; import java.util.Stack; import java.util.EmptyStackException; import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.io.FileInputStream; import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.DataInputStream; import java.io.IOException; import java.io.FileNotFoundException; import android.text.TextUtils; import android.util.Log; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; class OrgFileParser { class TitleComponents { String title; String todo; String priority; ArrayList<String> tags = new ArrayList<String>(); } ArrayList<String> orgPaths; ArrayList<Node> nodeList = new ArrayList<Node>(); String storageMode = null; Pattern titlePattern = null; FileInputStream fstream; Node rootNode = new Node("", Node.HEADING); MobileOrgDatabase appdb; public static final String LT = "MobileOrg"; public String orgDir = "/sdcard/mobileorg/"; OrgFileParser(ArrayList<String> orgpaths, String storageMode, MobileOrgDatabase appdb, String orgBasePath) { this.appdb = appdb; this.storageMode = storageMode; this.orgPaths = orgpaths; this.orgDir = orgBasePath; } private Pattern prepareTitlePattern() { if (this.titlePattern == null) { StringBuffer pattern = new StringBuffer(); pattern.append("^(?:([A-Z]{2,}:?\\s*"); pattern.append(")\\s*)?"); pattern.append("(\\[\\#.*\\])?(.*?)"); pattern.append("\\s*(?::([^\\s]+):)?$"); this.titlePattern = Pattern.compile(pattern.toString()); } return this.titlePattern; } private TitleComponents parseTitle (String orgTitle) { TitleComponents component = new TitleComponents(); String title = orgTitle.trim(); Pattern pattern = prepareTitlePattern(); Matcher m = pattern.matcher(title); if (m.find()) { if (m.group(1) != null) component.todo = m.group(1); if (m.group(2) != null) { component.priority = m.group(2); component.priority = component.priority.replace("#", ""); component.priority = component.priority.replace("[", ""); component.priority = component.priority.replace("]", ""); } component.title = m.group(3); String tags = m.group(4); if (tags != null) { for (String tag : tags.split(":")) { component.tags.add(tag); } } } else { Log.w(LT, "Title not matched: " + title); component.title = title; } return component; } private String stripTitle(String orgTitle) { Pattern titlePattern = Pattern.compile("<before.*</before>|<after.*</after>"); Matcher titleMatcher = titlePattern.matcher(orgTitle); String newTitle = ""; if (titleMatcher.find()) { newTitle += orgTitle.substring(0, titleMatcher.start()); newTitle += orgTitle.substring(titleMatcher.end(), orgTitle.length()); } else { newTitle = orgTitle; } return newTitle; } public long createEntry(String heading, int nodeType, String content, long parentId) { ContentValues recValues = new ContentValues(); recValues.put("heading", heading); recValues.put("type", nodeType); recValues.put("content", content); recValues.put("parentid", parentId); return this.appdb.appdb.insert("data", null, recValues); } public void addContent(long nodeId, String content) { ContentValues recValues = new ContentValues(); recValues.put("content", content + "\n"); this.appdb.appdb.update("data", recValues, "id = ?", new String[] {Long.toString(nodeId)}); } public String getNodePath(Node baseNode) { String npath = baseNode.nodeName; Node pnode = baseNode; while ((pnode = pnode.parentNode) != null) { if (pnode.nodeName.length() > 0) { npath = pnode.nodeName + "/" + npath; } } npath = "olp:" + npath; return npath; } public void parse(Node fileNode, BufferedReader breader) { try { String thisLine; Stack<Node> nodeStack = new Stack(); Pattern propertiesLine = Pattern.compile("^\\s*:[A-Z]+:"); if(breader == null) { breader = this.getHandle(fileNode.nodeName); } nodeStack.push(fileNode); int nodeDepth = 0; while ((thisLine = breader.readLine()) != null) { int numstars = 0; if (thisLine.length() < 1 || thisLine.charAt(0) == '#') { continue; } for (int idx = 0; idx < thisLine.length(); idx++) { if (thisLine.charAt(idx) != '*') { break; } numstars++; } if (numstars >= thisLine.length() || thisLine.charAt(numstars) != ' ') { numstars = 0; } //headings if (numstars > 0) { String title = thisLine.substring(numstars+1); TitleComponents titleComp = parseTitle(this.stripTitle(title)); Node newNode = new Node(titleComp.title, Node.HEADING); newNode.setFullTitle(this.stripTitle(title)); newNode.todo = titleComp.todo; newNode.priority = titleComp.priority; newNode.tags.addAll(titleComp.tags); if (numstars > nodeDepth) { try { Node lastNode = nodeStack.peek(); newNode.setParentNode(lastNode); newNode.addProperty("ID", this.getNodePath(newNode)); lastNode.addChildNode(newNode); } catch (EmptyStackException e) { } nodeStack.push(newNode); nodeDepth++; } else if (numstars == nodeDepth) { nodeStack.pop(); nodeStack.peek().addChildNode(newNode); nodeStack.push(newNode); } else if (numstars < nodeDepth) { for (;numstars <= nodeDepth; nodeDepth--) { nodeStack.pop(); } Node lastNode = nodeStack.peek(); newNode.setParentNode(lastNode); newNode.addProperty("ID", this.getNodePath(newNode)); lastNode.addChildNode(newNode); nodeStack.push(newNode); nodeDepth++; } } //content else { Matcher propm = propertiesLine.matcher(thisLine); Node lastNode = nodeStack.peek(); if (thisLine.indexOf(":ID:") != -1) { String trimmedLine = thisLine.substring(thisLine.indexOf(":ID:")+4).trim(); lastNode.addProperty("ID", trimmedLine); continue; } else if (propm.find()) { continue; } else if (thisLine.indexOf("DEADLINE:") != -1 || thisLine.indexOf("SCHEDULED:") != -1) { try { Pattern deadlineP = Pattern.compile( "^.*(DEADLINE: <.+?>)"); Matcher deadlineM = deadlineP.matcher(thisLine); Pattern schedP = Pattern.compile( "^.*(SCHEDULED: <.+?>)"); Matcher schedM = schedP.matcher(thisLine); - SimpleDateFormat formatter = new SimpleDateFormat( + SimpleDateFormat dFormatter = new SimpleDateFormat( "'DEADLINE': <yyyy-MM-dd EEE>"); + SimpleDateFormat sFormatter = new SimpleDateFormat( + "'SCHEDULED': <yyyy-MM-dd EEE>"); if (deadlineM.find()) { - lastNode.deadline = formatter.parse(deadlineM.group(1)); + lastNode.deadline = dFormatter.parse(deadlineM.group(1)); } if (schedM.find()) { - lastNode.deadline = formatter.parse(schedM.group(1)); + lastNode.schedule = sFormatter.parse(schedM.group(1)); } } catch (java.text.ParseException e) { Log.e(LT, "Could not parse deadline"); } continue; } lastNode.addPayload(thisLine); } } for (;nodeDepth > 0; nodeDepth--) { nodeStack.pop(); } fileNode.parsed = true; breader.close(); } catch (IOException e) { Log.e(LT, "IO Exception on readerline: " + e.getMessage()); } } public void parse() { Stack<Node> nodeStack = new Stack(); nodeStack.push(this.rootNode); for (int jdx = 0; jdx < this.orgPaths.size(); jdx++) { Log.d(LT, "Parsing: " + orgPaths.get(jdx)); //if file is encrypted just add a placeholder node to be parsed later if(orgPaths.get(jdx).endsWith(".gpg") || orgPaths.get(jdx).endsWith(".pgp") || orgPaths.get(jdx).endsWith(".enc")) { Node nnode = new Node(orgPaths.get(jdx), Node.HEADING, true); nnode.setParentNode(nodeStack.peek()); nnode.addProperty("ID", this.getNodePath(nnode)); nodeStack.peek().addChildNode(nnode); continue; } Node fileNode = new Node(this.orgPaths.get(jdx), Node.HEADING, false); fileNode.setParentNode(nodeStack.peek()); fileNode.addProperty("ID", this.getNodePath(fileNode)); nodeStack.peek().addChildNode(fileNode); nodeStack.push(fileNode); parse(fileNode, null); nodeStack.pop(); } } public ArrayList<EditNode> parseEdits() { Pattern editTitlePattern = Pattern.compile("F\\((edit:.*?)\\) \\[\\[(.*?)\\]\\[(.*?)\\]\\]"); Pattern createTitlePattern = Pattern.compile("^\\*\\s+(.*)"); ArrayList<EditNode> edits = new ArrayList<EditNode>(); BufferedReader breader = this.getHandle("mobileorg.org"); if (breader == null) return edits; String thisLine; boolean awaitingOldVal = false; boolean awaitingNewVal = false; boolean awaitingCaptureBody = false; EditNode thisNode = null; try { while ((thisLine = breader.readLine()) != null) { Matcher editm = editTitlePattern.matcher(thisLine); Matcher createm = createTitlePattern.matcher(thisLine); if (editm.find()) { thisNode = new EditNode(); if (editm.group(1) != null) thisNode.editType = editm.group(1).split(":")[1]; if (editm.group(2) != null) thisNode.nodeId = editm.group(2).split(":")[1]; if (editm.group(3) == null) thisNode.title = editm.group(3); } else if (createm.find()) { } else { if (thisLine.indexOf("** Old value") != -1) { awaitingOldVal = true; continue; } else if (thisLine.indexOf("** New value") != -1) { awaitingOldVal = false; awaitingNewVal = true; continue; } else if (thisLine.indexOf("** End of edit") != -1) { awaitingNewVal = false; edits.add(thisNode); } if (awaitingOldVal) { thisNode.oldVal += thisLine; } if (awaitingNewVal) { thisNode.newVal += thisLine; } } } } catch (java.io.IOException e) { Log.e(LT, "IO Exception caught trying to read edits file"); } return edits; } public BufferedReader getHandle(String filename) { BufferedReader breader = null; try { if (this.storageMode == null || this.storageMode.equals("internal")) { String normalized = filename.replace("/", "_"); this.fstream = new FileInputStream("/data/data/com.matburt.mobileorg/files/" + normalized); } else if (this.storageMode.equals("sdcard")) { String dirActual = ""; if (filename.equals("mobileorg.org")) { dirActual = "/sdcard/mobileorg/"; } else { dirActual = this.orgDir; } this.fstream = new FileInputStream(dirActual + filename); } else { Log.e(LT, "[Parse] Unknown storage mechanism: " + this.storageMode); this.fstream = null; } DataInputStream in = new DataInputStream(this.fstream); breader = new BufferedReader(new InputStreamReader(in)); } catch (Exception e) { Log.e(LT, "Error: " + e.getMessage() + " in file " + filename); } return breader; } public static byte[] getRawFileData(String baseDir, String filename) { try { File file = new File(baseDir + filename); FileInputStream is = new FileInputStream(file); byte[] buffer = new byte[(int)file.length()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead=is.read(buffer, offset, buffer.length-offset)) >= 0) { offset += numRead; } is.close(); if (offset < buffer.length) { throw new IOException("Could not completely read file "+file.getName()); } return buffer; } catch (Exception e) { Log.e(LT, "Error: " + e.getMessage() + " in file " + filename); return null; } } }
false
true
public void parse(Node fileNode, BufferedReader breader) { try { String thisLine; Stack<Node> nodeStack = new Stack(); Pattern propertiesLine = Pattern.compile("^\\s*:[A-Z]+:"); if(breader == null) { breader = this.getHandle(fileNode.nodeName); } nodeStack.push(fileNode); int nodeDepth = 0; while ((thisLine = breader.readLine()) != null) { int numstars = 0; if (thisLine.length() < 1 || thisLine.charAt(0) == '#') { continue; } for (int idx = 0; idx < thisLine.length(); idx++) { if (thisLine.charAt(idx) != '*') { break; } numstars++; } if (numstars >= thisLine.length() || thisLine.charAt(numstars) != ' ') { numstars = 0; } //headings if (numstars > 0) { String title = thisLine.substring(numstars+1); TitleComponents titleComp = parseTitle(this.stripTitle(title)); Node newNode = new Node(titleComp.title, Node.HEADING); newNode.setFullTitle(this.stripTitle(title)); newNode.todo = titleComp.todo; newNode.priority = titleComp.priority; newNode.tags.addAll(titleComp.tags); if (numstars > nodeDepth) { try { Node lastNode = nodeStack.peek(); newNode.setParentNode(lastNode); newNode.addProperty("ID", this.getNodePath(newNode)); lastNode.addChildNode(newNode); } catch (EmptyStackException e) { } nodeStack.push(newNode); nodeDepth++; } else if (numstars == nodeDepth) { nodeStack.pop(); nodeStack.peek().addChildNode(newNode); nodeStack.push(newNode); } else if (numstars < nodeDepth) { for (;numstars <= nodeDepth; nodeDepth--) { nodeStack.pop(); } Node lastNode = nodeStack.peek(); newNode.setParentNode(lastNode); newNode.addProperty("ID", this.getNodePath(newNode)); lastNode.addChildNode(newNode); nodeStack.push(newNode); nodeDepth++; } } //content else { Matcher propm = propertiesLine.matcher(thisLine); Node lastNode = nodeStack.peek(); if (thisLine.indexOf(":ID:") != -1) { String trimmedLine = thisLine.substring(thisLine.indexOf(":ID:")+4).trim(); lastNode.addProperty("ID", trimmedLine); continue; } else if (propm.find()) { continue; } else if (thisLine.indexOf("DEADLINE:") != -1 || thisLine.indexOf("SCHEDULED:") != -1) { try { Pattern deadlineP = Pattern.compile( "^.*(DEADLINE: <.+?>)"); Matcher deadlineM = deadlineP.matcher(thisLine); Pattern schedP = Pattern.compile( "^.*(SCHEDULED: <.+?>)"); Matcher schedM = schedP.matcher(thisLine); SimpleDateFormat formatter = new SimpleDateFormat( "'DEADLINE': <yyyy-MM-dd EEE>"); if (deadlineM.find()) { lastNode.deadline = formatter.parse(deadlineM.group(1)); } if (schedM.find()) { lastNode.deadline = formatter.parse(schedM.group(1)); } } catch (java.text.ParseException e) { Log.e(LT, "Could not parse deadline"); } continue; } lastNode.addPayload(thisLine); } } for (;nodeDepth > 0; nodeDepth--) { nodeStack.pop(); } fileNode.parsed = true; breader.close(); } catch (IOException e) { Log.e(LT, "IO Exception on readerline: " + e.getMessage()); } }
public void parse(Node fileNode, BufferedReader breader) { try { String thisLine; Stack<Node> nodeStack = new Stack(); Pattern propertiesLine = Pattern.compile("^\\s*:[A-Z]+:"); if(breader == null) { breader = this.getHandle(fileNode.nodeName); } nodeStack.push(fileNode); int nodeDepth = 0; while ((thisLine = breader.readLine()) != null) { int numstars = 0; if (thisLine.length() < 1 || thisLine.charAt(0) == '#') { continue; } for (int idx = 0; idx < thisLine.length(); idx++) { if (thisLine.charAt(idx) != '*') { break; } numstars++; } if (numstars >= thisLine.length() || thisLine.charAt(numstars) != ' ') { numstars = 0; } //headings if (numstars > 0) { String title = thisLine.substring(numstars+1); TitleComponents titleComp = parseTitle(this.stripTitle(title)); Node newNode = new Node(titleComp.title, Node.HEADING); newNode.setFullTitle(this.stripTitle(title)); newNode.todo = titleComp.todo; newNode.priority = titleComp.priority; newNode.tags.addAll(titleComp.tags); if (numstars > nodeDepth) { try { Node lastNode = nodeStack.peek(); newNode.setParentNode(lastNode); newNode.addProperty("ID", this.getNodePath(newNode)); lastNode.addChildNode(newNode); } catch (EmptyStackException e) { } nodeStack.push(newNode); nodeDepth++; } else if (numstars == nodeDepth) { nodeStack.pop(); nodeStack.peek().addChildNode(newNode); nodeStack.push(newNode); } else if (numstars < nodeDepth) { for (;numstars <= nodeDepth; nodeDepth--) { nodeStack.pop(); } Node lastNode = nodeStack.peek(); newNode.setParentNode(lastNode); newNode.addProperty("ID", this.getNodePath(newNode)); lastNode.addChildNode(newNode); nodeStack.push(newNode); nodeDepth++; } } //content else { Matcher propm = propertiesLine.matcher(thisLine); Node lastNode = nodeStack.peek(); if (thisLine.indexOf(":ID:") != -1) { String trimmedLine = thisLine.substring(thisLine.indexOf(":ID:")+4).trim(); lastNode.addProperty("ID", trimmedLine); continue; } else if (propm.find()) { continue; } else if (thisLine.indexOf("DEADLINE:") != -1 || thisLine.indexOf("SCHEDULED:") != -1) { try { Pattern deadlineP = Pattern.compile( "^.*(DEADLINE: <.+?>)"); Matcher deadlineM = deadlineP.matcher(thisLine); Pattern schedP = Pattern.compile( "^.*(SCHEDULED: <.+?>)"); Matcher schedM = schedP.matcher(thisLine); SimpleDateFormat dFormatter = new SimpleDateFormat( "'DEADLINE': <yyyy-MM-dd EEE>"); SimpleDateFormat sFormatter = new SimpleDateFormat( "'SCHEDULED': <yyyy-MM-dd EEE>"); if (deadlineM.find()) { lastNode.deadline = dFormatter.parse(deadlineM.group(1)); } if (schedM.find()) { lastNode.schedule = sFormatter.parse(schedM.group(1)); } } catch (java.text.ParseException e) { Log.e(LT, "Could not parse deadline"); } continue; } lastNode.addPayload(thisLine); } } for (;nodeDepth > 0; nodeDepth--) { nodeStack.pop(); } fileNode.parsed = true; breader.close(); } catch (IOException e) { Log.e(LT, "IO Exception on readerline: " + e.getMessage()); } }
diff --git a/cosmo/src/main/java/org/osaf/cosmo/eim/schema/event/EventApplicator.java b/cosmo/src/main/java/org/osaf/cosmo/eim/schema/event/EventApplicator.java index 1858ed170..8d76e3b97 100644 --- a/cosmo/src/main/java/org/osaf/cosmo/eim/schema/event/EventApplicator.java +++ b/cosmo/src/main/java/org/osaf/cosmo/eim/schema/event/EventApplicator.java @@ -1,188 +1,188 @@ /* * Copyright 2006 Open Source Applications Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osaf.cosmo.eim.schema.event; import java.text.ParseException; import net.fortuna.ical4j.model.DateTime; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osaf.cosmo.calendar.ICalDate; import org.osaf.cosmo.calendar.UnknownTimeZoneException; import org.osaf.cosmo.eim.EimRecord; import org.osaf.cosmo.eim.EimRecordField; import org.osaf.cosmo.eim.TextField; import org.osaf.cosmo.eim.schema.BaseStampApplicator; import org.osaf.cosmo.eim.schema.EimFieldValidator; import org.osaf.cosmo.eim.schema.EimSchemaException; import org.osaf.cosmo.eim.schema.EimValidationException; import org.osaf.cosmo.eim.schema.EimValueConverter; import org.osaf.cosmo.eim.schema.text.DurationFormat; import org.osaf.cosmo.model.BaseEventStamp; import org.osaf.cosmo.model.EventExceptionStamp; import org.osaf.cosmo.model.EventStamp; import org.osaf.cosmo.model.Item; import org.osaf.cosmo.model.NoteItem; import org.osaf.cosmo.model.Stamp; /** * Applies EIM records to event stamps. * * @see EventStamp */ public class EventApplicator extends BaseStampApplicator implements EventConstants { private static final Log log = LogFactory.getLog(EventApplicator.class); /** */ public EventApplicator(Item item) { super(PREFIX_EVENT, NS_EVENT, item); setStamp(BaseEventStamp.getStamp(item)); } /** * Creates and returns a stamp instance that can be added by * <code>BaseStampApplicator</code> to the item. Used when a * stamp record is applied to an item that does not already have * that stamp. */ protected Stamp createStamp(EimRecord record) throws EimSchemaException { BaseEventStamp eventStamp = null; NoteItem note = (NoteItem) getItem(); // Create master event stamp, or event exception stamp if(note.getModifies()==null) { eventStamp = new EventStamp(getItem()); eventStamp.createCalendar(); } else { eventStamp = new EventExceptionStamp(getItem()); eventStamp.createCalendar(); String recurrenceId = note.getUid().split( EventExceptionStamp.RECURRENCEID_DELIMITER)[1]; ICalDate icd = EimValueConverter.toICalDate(recurrenceId); eventStamp.setRecurrenceId(icd.getDate()); } // need to copy reminderTime to alarm in event if(note.getReminderTime()!=null) { eventStamp.creatDisplayAlarm(); eventStamp.setDisplayAlarmDescription("display alarm"); DateTime dt = new DateTime(true); dt.setTime(note.getReminderTime().getTime()); eventStamp.setDisplayAlarmTriggerDate(dt); } return eventStamp; } /** * Copies record field values to stamp properties and * attributes. * * @throws EimValidationException if the field value is invalid * @throws EimSchemaException if the field is improperly * constructed or cannot otherwise be applied to the event */ protected void applyField(EimRecordField field) throws EimSchemaException { BaseEventStamp event = (BaseEventStamp) getStamp(); if (field.getName().equals(FIELD_DTSTART)) { if(field.isMissing()) { handleMissingDtStart(); handleMissingAttribute("anyTime"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_DTSTART); ICalDate icd = EimValueConverter.toICalDate(value); event.setStartDate(icd.getDate()); event.setAnyTime(icd.isAnyTime()); } } else if (field.getName().equals(FIELD_DURATION)) { if(field.isMissing()) { handleMissingAttribute("duration"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_DURATION); try { event.setDuration(DurationFormat.getInstance().parse(value)); } catch (ParseException e) { - throw new EimValidationException("Illegal duration", e); + throw new EimValidationException("Illegal duration " + value, e); } } } else if (field.getName().equals(FIELD_LOCATION)) { if(field.isMissing()) { handleMissingAttribute("location"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_LOCATION); event.setLocation(value); } } else if (field.getName().equals(FIELD_RRULE)) { String value = EimFieldValidator.validateText(field, MAXLEN_RRULE); event.setRecurrenceRules(EimValueConverter.toICalRecurs(value)); } else if (field.getName().equals(FIELD_EXRULE)) { String value = EimFieldValidator.validateText(field, MAXLEN_EXRULE); event.setExceptionRules(EimValueConverter.toICalRecurs(value)); } else if (field.getName().equals(FIELD_RDATE)) { String value = EimFieldValidator.validateText(field, MAXLEN_RDATE); ICalDate icd = EimValueConverter.toICalDate(value); event.setRecurrenceDates(icd != null ? icd.getDateList() : null); } else if (field.getName().equals(FIELD_EXDATE)) { String value = EimFieldValidator.validateText(field, MAXLEN_EXDATE); ICalDate icd = EimValueConverter.toICalDate(value); event.setExceptionDates(icd != null ? icd.getDateList() : null); } else if (field.getName().equals(FIELD_STATUS)) { if(field.isMissing()) { handleMissingAttribute("status"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_STATUS); event.setStatus(value); } } else { applyUnknownField(field); } } @Override protected Stamp getParentStamp() { NoteItem noteMod = (NoteItem) getItem(); NoteItem parentNote = noteMod.getModifies(); if(parentNote!=null) return parentNote.getStamp(BaseEventStamp.class); else return null; } private void handleMissingDtStart() throws EimSchemaException { checkIsModification(); // A missing dtstart on a modification means that the start date // is equal to the recurrenceId BaseEventStamp event = (BaseEventStamp) getStamp(); event.setStartDate(event.getRecurrenceId()); } }
true
true
protected void applyField(EimRecordField field) throws EimSchemaException { BaseEventStamp event = (BaseEventStamp) getStamp(); if (field.getName().equals(FIELD_DTSTART)) { if(field.isMissing()) { handleMissingDtStart(); handleMissingAttribute("anyTime"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_DTSTART); ICalDate icd = EimValueConverter.toICalDate(value); event.setStartDate(icd.getDate()); event.setAnyTime(icd.isAnyTime()); } } else if (field.getName().equals(FIELD_DURATION)) { if(field.isMissing()) { handleMissingAttribute("duration"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_DURATION); try { event.setDuration(DurationFormat.getInstance().parse(value)); } catch (ParseException e) { throw new EimValidationException("Illegal duration", e); } } } else if (field.getName().equals(FIELD_LOCATION)) { if(field.isMissing()) { handleMissingAttribute("location"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_LOCATION); event.setLocation(value); } } else if (field.getName().equals(FIELD_RRULE)) { String value = EimFieldValidator.validateText(field, MAXLEN_RRULE); event.setRecurrenceRules(EimValueConverter.toICalRecurs(value)); } else if (field.getName().equals(FIELD_EXRULE)) { String value = EimFieldValidator.validateText(field, MAXLEN_EXRULE); event.setExceptionRules(EimValueConverter.toICalRecurs(value)); } else if (field.getName().equals(FIELD_RDATE)) { String value = EimFieldValidator.validateText(field, MAXLEN_RDATE); ICalDate icd = EimValueConverter.toICalDate(value); event.setRecurrenceDates(icd != null ? icd.getDateList() : null); } else if (field.getName().equals(FIELD_EXDATE)) { String value = EimFieldValidator.validateText(field, MAXLEN_EXDATE); ICalDate icd = EimValueConverter.toICalDate(value); event.setExceptionDates(icd != null ? icd.getDateList() : null); } else if (field.getName().equals(FIELD_STATUS)) { if(field.isMissing()) { handleMissingAttribute("status"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_STATUS); event.setStatus(value); } } else { applyUnknownField(field); } }
protected void applyField(EimRecordField field) throws EimSchemaException { BaseEventStamp event = (BaseEventStamp) getStamp(); if (field.getName().equals(FIELD_DTSTART)) { if(field.isMissing()) { handleMissingDtStart(); handleMissingAttribute("anyTime"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_DTSTART); ICalDate icd = EimValueConverter.toICalDate(value); event.setStartDate(icd.getDate()); event.setAnyTime(icd.isAnyTime()); } } else if (field.getName().equals(FIELD_DURATION)) { if(field.isMissing()) { handleMissingAttribute("duration"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_DURATION); try { event.setDuration(DurationFormat.getInstance().parse(value)); } catch (ParseException e) { throw new EimValidationException("Illegal duration " + value, e); } } } else if (field.getName().equals(FIELD_LOCATION)) { if(field.isMissing()) { handleMissingAttribute("location"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_LOCATION); event.setLocation(value); } } else if (field.getName().equals(FIELD_RRULE)) { String value = EimFieldValidator.validateText(field, MAXLEN_RRULE); event.setRecurrenceRules(EimValueConverter.toICalRecurs(value)); } else if (field.getName().equals(FIELD_EXRULE)) { String value = EimFieldValidator.validateText(field, MAXLEN_EXRULE); event.setExceptionRules(EimValueConverter.toICalRecurs(value)); } else if (field.getName().equals(FIELD_RDATE)) { String value = EimFieldValidator.validateText(field, MAXLEN_RDATE); ICalDate icd = EimValueConverter.toICalDate(value); event.setRecurrenceDates(icd != null ? icd.getDateList() : null); } else if (field.getName().equals(FIELD_EXDATE)) { String value = EimFieldValidator.validateText(field, MAXLEN_EXDATE); ICalDate icd = EimValueConverter.toICalDate(value); event.setExceptionDates(icd != null ? icd.getDateList() : null); } else if (field.getName().equals(FIELD_STATUS)) { if(field.isMissing()) { handleMissingAttribute("status"); } else { String value = EimFieldValidator.validateText(field, MAXLEN_STATUS); event.setStatus(value); } } else { applyUnknownField(field); } }
diff --git a/src/il/ac/tau/team3/shareaprayer/FindPrayer.java b/src/il/ac/tau/team3/shareaprayer/FindPrayer.java index 5d48764..bac58fc 100644 --- a/src/il/ac/tau/team3/shareaprayer/FindPrayer.java +++ b/src/il/ac/tau/team3/shareaprayer/FindPrayer.java @@ -1,1118 +1,1118 @@ package il.ac.tau.team3.shareaprayer; import il.ac.tau.team3.addressQuery.MapsQueryLocation; import il.ac.tau.team3.addressQuery.MapsQueryLonLat; import il.ac.tau.team3.common.GeneralPlace; import il.ac.tau.team3.common.GeneralUser; import il.ac.tau.team3.common.SPGeoPoint; import il.ac.tau.team3.common.SPUtils; import il.ac.tau.team3.common.UnknownLocationException; import il.ac.tau.team3.spcomm.ACommHandler; import il.ac.tau.team3.spcomm.ICommHandler; import il.ac.tau.team3.spcomm.SPComm; import il.ac.tau.team3.uiutils.ISPMenuItem; import il.ac.tau.team3.uiutils.MenuFacebookUtils; import il.ac.tau.team3.uiutils.MenuSettingsUtils; import il.ac.tau.team3.uiutils.MenuStatusUtils; import il.ac.tau.team3.uiutils.MenuUtils; import il.ac.tau.team3.uiutils.SPMenu; import il.ac.tau.team3.uiutils.PlacesDetailsUI; import il.ac.tau.team3.uiutils.SPMenu.ISPOnMenuItemSelectedListener; import il.ac.tau.team3.uiutils.SPMenus; import il.ac.tau.team3.uiutils.SPMenus.ESPMenuItem; import il.ac.tau.team3.uiutils.SPMenus.ESPSubMenuFind; import il.ac.tau.team3.uiutils.SPMenus.ESPSubMenuPlaces; import il.ac.tau.team3.uiutils.UIUtils; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.mapsforge.android.maps.GeoPoint; import org.mapsforge.android.maps.ItemizedOverlay; import org.mapsforge.android.maps.MapActivity; import org.mapsforge.android.maps.OverlayItem; import org.mapsforge.android.maps.PrayerArrayItemizedOverlay; import android.accounts.Account; import android.accounts.AccountManager; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.PopupWindow.OnDismissListener; import android.widget.TextView; import android.widget.Toast; public class FindPrayer extends MapActivity { public final static int SHAHARIT = 4; public final static int MINHA = 2; public final static int ARVIT = 1; private Drawable userDefaultMarker; private Drawable glowClosestMarker; private Drawable othersDefaultMarker; private Drawable synagougeMarker; private Drawable synagougeClosestMarker; private Drawable searchMarker; private PrayerArrayItemizedOverlay userOverlay; private PrayerArrayItemizedOverlay searchQueryOverlay; private PrayerArrayItemizedOverlay otherUsersOverlay; private PlaceArrayItemizedOverlay publicPlaceOverlay; private PlaceArrayItemizedOverlay closestPlaceOverlay; private SPComm comm = new SPComm(); private FacebookConnector facebookConnector = null; private boolean tracking_mode = true; public IStatusWriter getStatusBar() { return statusBar; } private Integer calculateViewableRadius(SPGeoPoint center) { if (center == null) { return null; } GeoPoint screenEdge = mapView.getProjection().fromPixels(mapView.getWidth(), mapView.getHeight()); if (screenEdge == null) { return null; } double distance = SPUtils.calculateDistanceMeters(center.getLongitudeInDegrees(), center.getLatitudeInDegrees(), screenEdge.getLongitude() , screenEdge.getLatitude()); return (int) Math.ceil(distance); } private GeneralPlace determineClosestPlace(GeneralPlace[] places){ if (null == places) { return null; } try { GeneralPlace closestPlace = null; double userLat = svcGetter.getService().getUser().getSpGeoPoint().getLatitudeInDegrees(); double userLong = svcGetter.getService().getUser().getSpGeoPoint().getLongitudeInDegrees(); double distance = SPUtils.INFINITY; double tmp = 0; for (GeneralPlace place : places){ tmp = SPUtils.calculateDistanceMeters(userLong, userLat, place.getSpGeoPoint().getLongitudeInDegrees() , place.getSpGeoPoint().getLatitudeInDegrees()); if(tmp < distance){ distance = tmp; closestPlace = place; } } return closestPlace; } catch (UserNotFoundException e) { Log.d("FindPrayer:determineClosestPlace","Unable to find user"); return null; } catch (UnknownLocationException e) { //Log.e("FidPrayer:determineClosestPlace",e.getMessage()); Log.d("FindPrayer:determineClosestPlace","Unknown location"); return null; } catch (ServiceNotConnected e) { Log.d("FindPrayer:determineClosestPlace","service not connected"); //Log.d("FinndPrayer:determineClosestPlace",e.getMessage()); return null; } catch (NullPointerException e) { e.printStackTrace(); //Log.d("FindPrayer:determineClosestPlace",e.getMessage()); return null; } } public SPComm getSPComm() { return comm; } private void updateUsersOnMap(SPGeoPoint center) { Integer radius = calculateViewableRadius(center); if (null == radius) { return; } comm.requestGetUsers(center.getLatitudeInDegrees(), center.getLongitudeInDegrees(), radius, new ACommHandler<GeneralUser[]>() { public void onRecv(final GeneralUser[] users) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { ILocationSvc locSvc; GeneralUser thisUser = null; try { locSvc = svcGetter.getService(); } catch (ServiceNotConnected e) { Log.d("FindPrayer:updateUsersOnMap","service not connected"); e.printStackTrace(); return; } try { thisUser = locSvc.getUser(); } catch (UserNotFoundException e) { Log.d("FindPrayer:updateUsersOnMap","user not found exception"); e.printStackTrace(); return; } catch (NullPointerException e) { Log.d("FindPrayer:updateUsersOnMap",e.getMessage()); e.printStackTrace(); } try { List<UserOverlayItem> userOverlayList = new ArrayList<UserOverlayItem>(); userOverlayList.add(new UserOverlayItem(thisUser)); userOverlay.changeItems(userOverlayList); } catch (UnknownLocationException e) { e.printStackTrace(); } catch (NullPointerException e) { Log.d("FindPrayer:updateUsersOnMap",e.getMessage()); e.printStackTrace(); } if (null != users) { List<UserOverlayItem> usersOverlayList = new ArrayList<UserOverlayItem>(users.length); for (GeneralUser user : users) { try { if (!thisUser.getName().equals(user.getName())) { usersOverlayList.add(new UserOverlayItem(user)); } } catch (UnknownLocationException e) { Log.d("FindPrayer:updateUsersOnMap","unknown location exception"); e.printStackTrace(); } catch (NullPointerException e) { Log.d("FindPrayer:updateUsersOnMap",e.getMessage()); } } otherUsersOverlay.changeItems(usersOverlayList); } } }); } }); } private void updatePlacesOnMap(SPGeoPoint center) { Integer radius = calculateViewableRadius(center); if (null == radius) { return; } comm.requestGetPlaces(center.getLatitudeInDegrees(), center.getLongitudeInDegrees(), radius, new ACommHandler<GeneralPlace[]>() { public void onRecv(final GeneralPlace[] places) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { GeneralPlace closestPlace = determineClosestPlace(places); if(closestPlace!=null){ List<PlaceOverlayItem> closestPlacesOverlayList = new ArrayList<PlaceOverlayItem>(); try { closestPlacesOverlayList.add(new PlaceOverlayItem(closestPlace, closestPlace.getName(), closestPlace.getAddress(), synagougeClosestMarker, glowClosestMarker)); } catch (UnknownLocationException e) { e.printStackTrace(); } closestPlaceOverlay.changeItems(closestPlacesOverlayList); } else { closestPlaceOverlay.clear(); } if (null != places) { List<PlaceOverlayItem> placesOverlayList = new ArrayList<PlaceOverlayItem>(places.length); for (GeneralPlace place : places) { if ((closestPlace == null) || (!(place.getId().equals(closestPlace.getId())))){ try { placesOverlayList.add(new PlaceOverlayItem(place, place.getName(), place.getAddress(), synagougeMarker)); } catch (UnknownLocationException e) { Log.d("FindPrayer:updatePlacesOnMap","unknown location"); e.printStackTrace(); } } } publicPlaceOverlay.changeItems(placesOverlayList); } } }); } }); } private ServiceConnector svcGetter = new ServiceConnector(); public ServiceConnector getSvcGetter() { return svcGetter; } private ILocationProv locationListener; private StatusBarOverlay statusBar; private SPMapView mapView; private EditText editText; public void close() { try { refreshTask.interrupt(); refreshTask.join(); } catch (InterruptedException e) { return; } } private Thread refreshTask = new Thread() { @Override public void run() { while (! isInterrupted()) { try { synchronized (this) { wait(10000); } try { updateUsersOnMap(SPUtils.toSPGeoPoint(mapView.getMapCenter())); updatePlacesOnMap(SPUtils.toSPGeoPoint(mapView.getMapCenter())); statusBar.write("refreshing...", R.drawable.action_refresh, 1000); } catch (NullPointerException e) { //Log.d("FindPrayer",e.getMessage()); e.printStackTrace(); statusBar.write("Unable to connect to server.", R.drawable.status_bar_error_icon, 1000); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } }; private ServiceConnection svcConn; public Thread getRefreshTask() { return refreshTask; } private void NewPlaceCall(SPGeoPoint point){ try { UIUtils.createNewPlaceDialog( point, this , svcGetter.getService().getUser()); } catch (UserNotFoundException e) { } catch (ServiceNotConnected e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onDestroy() { try { svcGetter.getService().UnRegisterListner(locationListener); svcGetter.setService(null); } catch (ServiceNotConnected e) { // TODO Auto-generated catch block e.printStackTrace(); } unbindService(svcConn); statusBar.closeHandler(); comm.closeHandler(); close(); super.onDestroy(); } @Override protected void onStart () { super.onStart(); bindService(new Intent(LocServ.ACTION_SERVICE), svcConn, BIND_AUTO_CREATE); Toast toast = Toast.makeText(getApplicationContext(), "Long tap on map to create a new place", Toast.LENGTH_LONG); toast.show(); } private void registerUser(GeneralUser user) { refreshTask.start(); try { mapView.getController().setCenter(SPUtils.toGeoPoint(user.getSpGeoPoint())); } catch (UnknownLocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } synchronized(refreshTask){ refreshTask.notify(); }; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (SPMapView) findViewById(R.id.view1); editText = (EditText) findViewById(R.id.addressBar); UIUtils.initSearchBar(editText); mapView.registerTapListener(new IMapTapDetect() { public void onTouchEvent(SPGeoPoint sp) { NewPlaceCall(sp); } public void onMoveEvent(SPGeoPoint sp) { tracking_mode = false; } }); editText.setOnEditorActionListener (new EditText.OnEditorActionListener() { public boolean onEditorAction(final TextView v, int actionId, KeyEvent event) { if ((EditorInfo.IME_ACTION_DONE == actionId) || ((event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))) { statusBar.write("Searching for the place...", R.drawable.action_refresh, 2000); editText.setBackgroundResource(R.drawable.selector_edittext_yellow); editText.refreshDrawableState(); comm.searchForAddress(v.getText().toString(), new ACommHandler<MapsQueryLonLat[]>() { @Override public void onRecv(final MapsQueryLonLat[] Obj) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { try { double latitude = Obj[0].getLat(); double longitude = Obj[0].getLon(); GeoPoint gp = new GeoPoint(latitude, longitude); mapView.getController().setCenter(gp); mapView.getController().setZoom(mapView.getMaxZoomLevel()); synchronized(refreshTask) { refreshTask.notify(); } searchQueryOverlay.clear(); searchQueryOverlay.addItem(new OverlayItem(gp, "Search query result", v.getText().toString())); Toast toast = Toast.makeText(getApplicationContext(), "Long tap on map to create a new place", Toast.LENGTH_LONG); toast.show(); statusBar.write("Search: place found!", R.drawable.status_bar_accept_icon, 2000); editText.setBackgroundResource(R.drawable.selector_edittext_green); editText.refreshDrawableState(); } catch (NullPointerException e) { if(statusBar != null){ statusBar.write("Search: Place wasn't found.", R.drawable.status_bar_error_icon, 2000); } //Log.d("FindPrayer",e.getMessage()); e.printStackTrace(); onError(Obj); } catch (ArrayIndexOutOfBoundsException e) { if(statusBar != null){ statusBar.write("Search: Place wasn't found.", R.drawable.status_bar_error_icon, 2000); } e.printStackTrace(); //Log.d("FindPrayer",e.getMessage()); onError(Obj); } } });//@END: Runnable. } @Override public void onError(MapsQueryLonLat[] Obj) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { FindPrayer.this.editText.setBackgroundResource(R.drawable.selector_edittext_red); FindPrayer.this.editText.refreshDrawableState(); //super.onError(Obj); } }); } }); return true; } editText.setBackgroundResource(R.drawable.selector_edittext_yellow); return false; } }); /* * User overlay and icon: */ userDefaultMarker = ItemizedOverlay.boundCenterBottom(this.getResources().getDrawable(R.drawable.user_red_sruga)); userOverlay = new UserArrayItemizedOverlay(userDefaultMarker, this); mapView.getOverlays().add(userOverlay); searchMarker = ItemizedOverlay.boundCenterBottom(this.getResources().getDrawable(R.drawable.search_found_icon_green)); searchQueryOverlay = new PrayerArrayItemizedOverlay(searchMarker, this); mapView.getOverlays().add(searchQueryOverlay); statusBar = new StatusBarOverlay(this, mapView.getPaddingTop() + 24, mapView.getWidth() / 100, 16); mapView.getOverlays().add(statusBar); /* * Synagouge overlay */ synagougeMarker = this.getResources().getDrawable(R.drawable.place_white); publicPlaceOverlay = new PlaceArrayItemizedOverlay(synagougeMarker, this); mapView.getOverlays().add(publicPlaceOverlay); synagougeClosestMarker = this.getResources().getDrawable(R.drawable.place_white_david); glowClosestMarker = this.getResources().getDrawable(R.drawable.place_glow_thin); closestPlaceOverlay = new PlaceArrayItemizedOverlay(synagougeClosestMarker, this); mapView.getOverlays().add(closestPlaceOverlay); /* * Other users overlay and icons: */ othersDefaultMarker = this.getResources().getDrawable(R.drawable.user_blue_sruga); otherUsersOverlay = new UserArrayItemizedOverlay(othersDefaultMarker, this); mapView.getOverlays().add(otherUsersOverlay); // Define a listener that responds to location updates locationListener = new ILocationProv() { // Called when a new location is found by the network location provider. public void LocationChanged(SPGeoPoint point) { if (tracking_mode) { mapView.getController().setCenter(SPUtils.toGeoPoint(point)); } synchronized(refreshTask) { refreshTask.notify(); } } public void OnUserChange(GeneralUser user) { registerUser(user); if (! refreshTask.isAlive()) { refreshTask.start(); } } }; svcConn = new ServiceConnection() { public void onServiceDisconnected(ComponentName className) { svcGetter.setService(null); } public void onServiceConnected(ComponentName arg0, IBinder arg1) { svcGetter.setService((ILocationSvc) arg1); ILocationSvc service = null; try { service = svcGetter.getService(); service.RegisterListner(locationListener); GeneralUser user = service.getUser(); registerUser(user); } catch (ServiceNotConnected e) { Log.d("ShareAPrayer", "Service is not connected"); } catch (UserNotFoundException e) { String[] names; List<Account> accounts = new LinkedList<Account>(); for (Account a : AccountManager.get(FindPrayer.this).getAccounts()) { if (a.name.contains("@")) { accounts.add(a); } } try { names = UIUtils.HandleFirstTimeDialog(accounts.toArray(new Account[0]), FindPrayer.this); service.setNames(names); } catch (NullPointerException e_) { //Log.d("FindPrayer",e_.getMessage()); e.printStackTrace(); } } } }; mapView.registerTapListener(new IMapTapDetect() { class TimerRefreshTask extends TimerTask { @Override public void run() { synchronized (refreshTask) { refreshTask.notify(); } } }; private Timer t = new Timer(); private TimerTask ts = new TimerRefreshTask(); @Override public void onMoveEvent(SPGeoPoint sp) { // TODO Auto-generated method stub ts.cancel(); t.purge(); ts = new TimerRefreshTask(); t.schedule(ts, 1000); } }); facebookConnector = new FacebookConnector(this); - facebookConnector.setConnectOnStartup(true); + facebookConnector.connectOnStartup(); /* * Registering one listener for passing all events to activity with out making it consume them. */ mapView.registerTapListener(new IMapTapDetect() { /** * Delegating to the original function for comfort. * Note: The method is now final, because it's dangerous!. * This way if we fix this bypasses, all the code will be in the appropriate place. */ @Override public void onAnyEvent(MotionEvent event) { FindPrayer.this.onTouchEvent(event); } }); } public FacebookConnector getFacebookConnector() { return facebookConnector; } public void setFacebookConnector(FacebookConnector facebookConnector) { this.facebookConnector = facebookConnector; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (null != facebookConnector) { facebookConnector.autherizeCallback(requestCode, resultCode, data); //// } } private void centerMap() { ILocationSvc service; try { service = this.svcGetter.getService(); } catch (ServiceNotConnected sne) { sne.printStackTrace(); return; } GeneralUser user; try { user = service.getUser(); } catch (UserNotFoundException unfe) { unfe.printStackTrace(); return; } SPGeoPoint center; try { center = user.getSpGeoPoint(); } catch (UnknownLocationException ule) { ule.printStackTrace(); return; } this.mapView.getController().setCenter(SPUtils.toGeoPoint(center)); } private Account[] getAccounts() { Account[] accounts = AccountManager.get(FindPrayer.this).getAccounts(); if (null == accounts) { accounts = new Account[0]; } return accounts; } ///////////////////////////////////////////////////////////////////////////////////////////////////// ///////// Menu: ///////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////// /** * The custom Options-Menu for this Activity. * @init null: * Dew to @imp restrains. * @imp Lazy-initialization done via initializeMenu(). */ private SPMenu menu = null; /** * @imp Lazy-initialization. */ private void initializeMenu() { if (null == this.menu) { this.menu = new SPMenu(ESPMenuItem.values(), new ISPOnMenuItemSelectedListener() { public void onMenuItemSelected(ISPMenuItem item, View view) { final int id = item.id(); if (id == SPMenus.ESPSubMenuFind.ME.id()) { tracking_mode = true; FindPrayer.this.centerMap(); FindPrayer.this.menu.hide(); } else if (id == ESPMenuItem.FACEBOOK.id()) { FindPrayer.this.menu.hide(); new MenuFacebookUtils(FindPrayer.this); } else if (id == ESPSubMenuFind.CLOSEST.id()) { // Taking the closest (for now) from the map's overlay. ArrayList<OverlayItem> listOfOneItemIfAnyOnMap = FindPrayer.this.closestPlaceOverlay.getOverlayItems(); if (null != listOfOneItemIfAnyOnMap && listOfOneItemIfAnyOnMap.size() > 0) { FindPrayer.this.mapView.getController().setCenter(listOfOneItemIfAnyOnMap.get(0).getPoint()); } else { Toast.makeText(FindPrayer.this, "Sorry, there seem to be no places open for prayers.\nPlese consider creating one.", Toast.LENGTH_LONG).show(); } FindPrayer.this.menu.hide(); } else if (id == SPMenus.ESPSubMenuFind.ADDRESS.id()) { EditText edittext = (EditText) FindPrayer.this.findViewById(R.id.addressBar); edittext.setVisibility(View.VISIBLE); edittext.setFocusable(true); FindPrayer.this.menu.onMenuDismiss(new OnDismissListener() { public void onDismiss() { InputMethodManager keyboardMenager = (InputMethodManager) FindPrayer.this.getSystemService(INPUT_METHOD_SERVICE); keyboardMenager.showSoftInput(FindPrayer.this.editText, InputMethodManager.SHOW_FORCED /* | InputMethodManager.SHOW_IMPLICIT */); } }); // Apparently, only the sub gets closed... FindPrayer.this.menu.hide(); // TODO this is BAD, make separate methods in SPMenu. } else if (id == SPMenus.ESPSubMenuSettings.PROFILE.id()) { try { MenuSettingsUtils.createEditDetailsDialog(svcGetter.getService().getUser(), FindPrayer.this); } catch (UserNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceNotConnected e) { // TODO Auto-generated catch block e.printStackTrace(); } FindPrayer.this.menu.hide(); } else if (id == SPMenus.ESPSubMenuSettings.VIEW.id()) { MenuSettingsUtils.CreateChooseMinMaxDialog(FindPrayer.this); FindPrayer.this.menu.hide(); } else if (id == SPMenus.ESPSubMenuPlaces.JOINED.id()){ FindPrayer.this.menu.hide(); new PlacesDetailsUI(FindPrayer.this, svcGetter, comm, "Places I joined to", PlacesDetailsUI.Actions.JOINER, publicPlaceOverlay); } else if (id == SPMenus.ESPSubMenuPlaces.OWNED.id()){ FindPrayer.this.menu.hide(); new PlacesDetailsUI(FindPrayer.this, svcGetter, comm, "Places I own", PlacesDetailsUI.Actions.OWNER, publicPlaceOverlay); } else if (id == ESPSubMenuPlaces.CREATE.id()) { try { UIUtils.createNewPlaceDialog(null, FindPrayer.this, svcGetter.getService().getUser()); } catch (UserNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceNotConnected e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (id == ESPMenuItem.STATUS.id()){ try { MenuStatusUtils.createEditStatusDialog(svcGetter.getService().getUser(), FindPrayer.this); } catch (UserNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ServiceNotConnected e) { // TODO Auto-generated catch block e.printStackTrace(); } FindPrayer.this.menu.hide(); } else if (id == ESPMenuItem.EXIT.id()) { FindPrayer.this.menu.onMenuDismiss(new OnDismissListener() { public void onDismiss() { FindPrayer.this.finish(); //android.os.Process.killProcess(android.os.Process.myPid()); } }); } else { if (!item.hasSubMenu()){ FindPrayer.this.menu.hide(); } } } }); } } /** * @callBack On first menu button push. * @invokes onPrepareOptionsMenu(). * @param Menu menu: * Ignored. */ @Override public boolean onCreateOptionsMenu(Menu menu) { this.initializeMenu(); return true; } /** * Handles all about menu showing, even closing. * @callBack On menu button push. * @pre onCreateOptionsMenu(menu). * @param Menu menu: * Ignored. */ @Override public boolean onPrepareOptionsMenu(Menu menu) { this.menu.handleMenuButtonClick(this, R.id.view1); return true; } /** * @final because of menu showing. * @pre this.mapView.onTouchEvent() */ @Override public final boolean onTouchEvent(MotionEvent event) { /* Handle menu */ if (SPMenu.isShowing(this.menu)) { this.menu.hide(); } return true; } @Override public void onBackPressed() { if (SPMenu.isShowing(this.menu)) { this.menu.hide(); } else { super.onBackPressed(); } } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { return super.onMenuItemSelected(featureId, item); } public void setUser(String[] names) { // TODO Auto-generated method stub try { ILocationSvc service = svcGetter.getService(); service.setNames(names); } catch (ServiceNotConnected e) { } } public void setStatus(String status) { ILocationSvc service; try { service = svcGetter.getService(); service.setStatus(status); } catch (ServiceNotConnected e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UserNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (SPMapView) findViewById(R.id.view1); editText = (EditText) findViewById(R.id.addressBar); UIUtils.initSearchBar(editText); mapView.registerTapListener(new IMapTapDetect() { public void onTouchEvent(SPGeoPoint sp) { NewPlaceCall(sp); } public void onMoveEvent(SPGeoPoint sp) { tracking_mode = false; } }); editText.setOnEditorActionListener (new EditText.OnEditorActionListener() { public boolean onEditorAction(final TextView v, int actionId, KeyEvent event) { if ((EditorInfo.IME_ACTION_DONE == actionId) || ((event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))) { statusBar.write("Searching for the place...", R.drawable.action_refresh, 2000); editText.setBackgroundResource(R.drawable.selector_edittext_yellow); editText.refreshDrawableState(); comm.searchForAddress(v.getText().toString(), new ACommHandler<MapsQueryLonLat[]>() { @Override public void onRecv(final MapsQueryLonLat[] Obj) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { try { double latitude = Obj[0].getLat(); double longitude = Obj[0].getLon(); GeoPoint gp = new GeoPoint(latitude, longitude); mapView.getController().setCenter(gp); mapView.getController().setZoom(mapView.getMaxZoomLevel()); synchronized(refreshTask) { refreshTask.notify(); } searchQueryOverlay.clear(); searchQueryOverlay.addItem(new OverlayItem(gp, "Search query result", v.getText().toString())); Toast toast = Toast.makeText(getApplicationContext(), "Long tap on map to create a new place", Toast.LENGTH_LONG); toast.show(); statusBar.write("Search: place found!", R.drawable.status_bar_accept_icon, 2000); editText.setBackgroundResource(R.drawable.selector_edittext_green); editText.refreshDrawableState(); } catch (NullPointerException e) { if(statusBar != null){ statusBar.write("Search: Place wasn't found.", R.drawable.status_bar_error_icon, 2000); } //Log.d("FindPrayer",e.getMessage()); e.printStackTrace(); onError(Obj); } catch (ArrayIndexOutOfBoundsException e) { if(statusBar != null){ statusBar.write("Search: Place wasn't found.", R.drawable.status_bar_error_icon, 2000); } e.printStackTrace(); //Log.d("FindPrayer",e.getMessage()); onError(Obj); } } });//@END: Runnable. } @Override public void onError(MapsQueryLonLat[] Obj) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { FindPrayer.this.editText.setBackgroundResource(R.drawable.selector_edittext_red); FindPrayer.this.editText.refreshDrawableState(); //super.onError(Obj); } }); } }); return true; } editText.setBackgroundResource(R.drawable.selector_edittext_yellow); return false; } }); /* * User overlay and icon: */ userDefaultMarker = ItemizedOverlay.boundCenterBottom(this.getResources().getDrawable(R.drawable.user_red_sruga)); userOverlay = new UserArrayItemizedOverlay(userDefaultMarker, this); mapView.getOverlays().add(userOverlay); searchMarker = ItemizedOverlay.boundCenterBottom(this.getResources().getDrawable(R.drawable.search_found_icon_green)); searchQueryOverlay = new PrayerArrayItemizedOverlay(searchMarker, this); mapView.getOverlays().add(searchQueryOverlay); statusBar = new StatusBarOverlay(this, mapView.getPaddingTop() + 24, mapView.getWidth() / 100, 16); mapView.getOverlays().add(statusBar); /* * Synagouge overlay */ synagougeMarker = this.getResources().getDrawable(R.drawable.place_white); publicPlaceOverlay = new PlaceArrayItemizedOverlay(synagougeMarker, this); mapView.getOverlays().add(publicPlaceOverlay); synagougeClosestMarker = this.getResources().getDrawable(R.drawable.place_white_david); glowClosestMarker = this.getResources().getDrawable(R.drawable.place_glow_thin); closestPlaceOverlay = new PlaceArrayItemizedOverlay(synagougeClosestMarker, this); mapView.getOverlays().add(closestPlaceOverlay); /* * Other users overlay and icons: */ othersDefaultMarker = this.getResources().getDrawable(R.drawable.user_blue_sruga); otherUsersOverlay = new UserArrayItemizedOverlay(othersDefaultMarker, this); mapView.getOverlays().add(otherUsersOverlay); // Define a listener that responds to location updates locationListener = new ILocationProv() { // Called when a new location is found by the network location provider. public void LocationChanged(SPGeoPoint point) { if (tracking_mode) { mapView.getController().setCenter(SPUtils.toGeoPoint(point)); } synchronized(refreshTask) { refreshTask.notify(); } } public void OnUserChange(GeneralUser user) { registerUser(user); if (! refreshTask.isAlive()) { refreshTask.start(); } } }; svcConn = new ServiceConnection() { public void onServiceDisconnected(ComponentName className) { svcGetter.setService(null); } public void onServiceConnected(ComponentName arg0, IBinder arg1) { svcGetter.setService((ILocationSvc) arg1); ILocationSvc service = null; try { service = svcGetter.getService(); service.RegisterListner(locationListener); GeneralUser user = service.getUser(); registerUser(user); } catch (ServiceNotConnected e) { Log.d("ShareAPrayer", "Service is not connected"); } catch (UserNotFoundException e) { String[] names; List<Account> accounts = new LinkedList<Account>(); for (Account a : AccountManager.get(FindPrayer.this).getAccounts()) { if (a.name.contains("@")) { accounts.add(a); } } try { names = UIUtils.HandleFirstTimeDialog(accounts.toArray(new Account[0]), FindPrayer.this); service.setNames(names); } catch (NullPointerException e_) { //Log.d("FindPrayer",e_.getMessage()); e.printStackTrace(); } } } }; mapView.registerTapListener(new IMapTapDetect() { class TimerRefreshTask extends TimerTask { @Override public void run() { synchronized (refreshTask) { refreshTask.notify(); } } }; private Timer t = new Timer(); private TimerTask ts = new TimerRefreshTask(); @Override public void onMoveEvent(SPGeoPoint sp) { // TODO Auto-generated method stub ts.cancel(); t.purge(); ts = new TimerRefreshTask(); t.schedule(ts, 1000); } }); facebookConnector = new FacebookConnector(this); facebookConnector.setConnectOnStartup(true); /* * Registering one listener for passing all events to activity with out making it consume them. */ mapView.registerTapListener(new IMapTapDetect() { /** * Delegating to the original function for comfort. * Note: The method is now final, because it's dangerous!. * This way if we fix this bypasses, all the code will be in the appropriate place. */ @Override public void onAnyEvent(MotionEvent event) { FindPrayer.this.onTouchEvent(event); } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mapView = (SPMapView) findViewById(R.id.view1); editText = (EditText) findViewById(R.id.addressBar); UIUtils.initSearchBar(editText); mapView.registerTapListener(new IMapTapDetect() { public void onTouchEvent(SPGeoPoint sp) { NewPlaceCall(sp); } public void onMoveEvent(SPGeoPoint sp) { tracking_mode = false; } }); editText.setOnEditorActionListener (new EditText.OnEditorActionListener() { public boolean onEditorAction(final TextView v, int actionId, KeyEvent event) { if ((EditorInfo.IME_ACTION_DONE == actionId) || ((event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))) { statusBar.write("Searching for the place...", R.drawable.action_refresh, 2000); editText.setBackgroundResource(R.drawable.selector_edittext_yellow); editText.refreshDrawableState(); comm.searchForAddress(v.getText().toString(), new ACommHandler<MapsQueryLonLat[]>() { @Override public void onRecv(final MapsQueryLonLat[] Obj) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { try { double latitude = Obj[0].getLat(); double longitude = Obj[0].getLon(); GeoPoint gp = new GeoPoint(latitude, longitude); mapView.getController().setCenter(gp); mapView.getController().setZoom(mapView.getMaxZoomLevel()); synchronized(refreshTask) { refreshTask.notify(); } searchQueryOverlay.clear(); searchQueryOverlay.addItem(new OverlayItem(gp, "Search query result", v.getText().toString())); Toast toast = Toast.makeText(getApplicationContext(), "Long tap on map to create a new place", Toast.LENGTH_LONG); toast.show(); statusBar.write("Search: place found!", R.drawable.status_bar_accept_icon, 2000); editText.setBackgroundResource(R.drawable.selector_edittext_green); editText.refreshDrawableState(); } catch (NullPointerException e) { if(statusBar != null){ statusBar.write("Search: Place wasn't found.", R.drawable.status_bar_error_icon, 2000); } //Log.d("FindPrayer",e.getMessage()); e.printStackTrace(); onError(Obj); } catch (ArrayIndexOutOfBoundsException e) { if(statusBar != null){ statusBar.write("Search: Place wasn't found.", R.drawable.status_bar_error_icon, 2000); } e.printStackTrace(); //Log.d("FindPrayer",e.getMessage()); onError(Obj); } } });//@END: Runnable. } @Override public void onError(MapsQueryLonLat[] Obj) { FindPrayer.this.runOnUiThread(new Runnable() { public void run() { FindPrayer.this.editText.setBackgroundResource(R.drawable.selector_edittext_red); FindPrayer.this.editText.refreshDrawableState(); //super.onError(Obj); } }); } }); return true; } editText.setBackgroundResource(R.drawable.selector_edittext_yellow); return false; } }); /* * User overlay and icon: */ userDefaultMarker = ItemizedOverlay.boundCenterBottom(this.getResources().getDrawable(R.drawable.user_red_sruga)); userOverlay = new UserArrayItemizedOverlay(userDefaultMarker, this); mapView.getOverlays().add(userOverlay); searchMarker = ItemizedOverlay.boundCenterBottom(this.getResources().getDrawable(R.drawable.search_found_icon_green)); searchQueryOverlay = new PrayerArrayItemizedOverlay(searchMarker, this); mapView.getOverlays().add(searchQueryOverlay); statusBar = new StatusBarOverlay(this, mapView.getPaddingTop() + 24, mapView.getWidth() / 100, 16); mapView.getOverlays().add(statusBar); /* * Synagouge overlay */ synagougeMarker = this.getResources().getDrawable(R.drawable.place_white); publicPlaceOverlay = new PlaceArrayItemizedOverlay(synagougeMarker, this); mapView.getOverlays().add(publicPlaceOverlay); synagougeClosestMarker = this.getResources().getDrawable(R.drawable.place_white_david); glowClosestMarker = this.getResources().getDrawable(R.drawable.place_glow_thin); closestPlaceOverlay = new PlaceArrayItemizedOverlay(synagougeClosestMarker, this); mapView.getOverlays().add(closestPlaceOverlay); /* * Other users overlay and icons: */ othersDefaultMarker = this.getResources().getDrawable(R.drawable.user_blue_sruga); otherUsersOverlay = new UserArrayItemizedOverlay(othersDefaultMarker, this); mapView.getOverlays().add(otherUsersOverlay); // Define a listener that responds to location updates locationListener = new ILocationProv() { // Called when a new location is found by the network location provider. public void LocationChanged(SPGeoPoint point) { if (tracking_mode) { mapView.getController().setCenter(SPUtils.toGeoPoint(point)); } synchronized(refreshTask) { refreshTask.notify(); } } public void OnUserChange(GeneralUser user) { registerUser(user); if (! refreshTask.isAlive()) { refreshTask.start(); } } }; svcConn = new ServiceConnection() { public void onServiceDisconnected(ComponentName className) { svcGetter.setService(null); } public void onServiceConnected(ComponentName arg0, IBinder arg1) { svcGetter.setService((ILocationSvc) arg1); ILocationSvc service = null; try { service = svcGetter.getService(); service.RegisterListner(locationListener); GeneralUser user = service.getUser(); registerUser(user); } catch (ServiceNotConnected e) { Log.d("ShareAPrayer", "Service is not connected"); } catch (UserNotFoundException e) { String[] names; List<Account> accounts = new LinkedList<Account>(); for (Account a : AccountManager.get(FindPrayer.this).getAccounts()) { if (a.name.contains("@")) { accounts.add(a); } } try { names = UIUtils.HandleFirstTimeDialog(accounts.toArray(new Account[0]), FindPrayer.this); service.setNames(names); } catch (NullPointerException e_) { //Log.d("FindPrayer",e_.getMessage()); e.printStackTrace(); } } } }; mapView.registerTapListener(new IMapTapDetect() { class TimerRefreshTask extends TimerTask { @Override public void run() { synchronized (refreshTask) { refreshTask.notify(); } } }; private Timer t = new Timer(); private TimerTask ts = new TimerRefreshTask(); @Override public void onMoveEvent(SPGeoPoint sp) { // TODO Auto-generated method stub ts.cancel(); t.purge(); ts = new TimerRefreshTask(); t.schedule(ts, 1000); } }); facebookConnector = new FacebookConnector(this); facebookConnector.connectOnStartup(); /* * Registering one listener for passing all events to activity with out making it consume them. */ mapView.registerTapListener(new IMapTapDetect() { /** * Delegating to the original function for comfort. * Note: The method is now final, because it's dangerous!. * This way if we fix this bypasses, all the code will be in the appropriate place. */ @Override public void onAnyEvent(MotionEvent event) { FindPrayer.this.onTouchEvent(event); } }); }
diff --git a/src/SpriteAction/Homing.java b/src/SpriteAction/Homing.java index 7db16ed..bcc67a6 100644 --- a/src/SpriteAction/Homing.java +++ b/src/SpriteAction/Homing.java @@ -1,34 +1,36 @@ package SpriteAction; import java.awt.Point; import com.golden.gamedev.object.Sprite; import sprites.HomingProjectile; import sprites.HomingEnemy; import sprites.GeneralSprite; public class Homing extends SpriteAction { public Homing(GeneralSprite s) { super(s); } @Override public void actionPerformed(Object object) { Sprite target = ((HomingEnemy)mySprite).getMyTarget(); - double x =target.getX()-target.getWidth()/2; + double x = target.getX()-target.getWidth()/2; double y = target.getY()-target.getHeight()/2; - double angleToTarget = Math.atan2( (x-mySprite.getY()),(y-mySprite.getX())); + double myX = mySprite.getX()-mySprite.getWidth()/2; + double myY = mySprite.getY()-mySprite.getHeight()/2; + double angleToTarget = Math.atan2( (y-myY),(x-myX)); angleToTarget = Math.toDegrees(angleToTarget); if(angleToTarget< 0){ angleToTarget+=360; } angleToTarget+=90; mySprite.setMovement(.04, angleToTarget); } }
false
true
public void actionPerformed(Object object) { Sprite target = ((HomingEnemy)mySprite).getMyTarget(); double x =target.getX()-target.getWidth()/2; double y = target.getY()-target.getHeight()/2; double angleToTarget = Math.atan2( (x-mySprite.getY()),(y-mySprite.getX())); angleToTarget = Math.toDegrees(angleToTarget); if(angleToTarget< 0){ angleToTarget+=360; } angleToTarget+=90; mySprite.setMovement(.04, angleToTarget); }
public void actionPerformed(Object object) { Sprite target = ((HomingEnemy)mySprite).getMyTarget(); double x = target.getX()-target.getWidth()/2; double y = target.getY()-target.getHeight()/2; double myX = mySprite.getX()-mySprite.getWidth()/2; double myY = mySprite.getY()-mySprite.getHeight()/2; double angleToTarget = Math.atan2( (y-myY),(x-myX)); angleToTarget = Math.toDegrees(angleToTarget); if(angleToTarget< 0){ angleToTarget+=360; } angleToTarget+=90; mySprite.setMovement(.04, angleToTarget); }
diff --git a/sal-api/src/main/java/com/atlassian/sal/api/auth/Authenticator.java b/sal-api/src/main/java/com/atlassian/sal/api/auth/Authenticator.java index b3596ef4..141ffc9a 100644 --- a/sal-api/src/main/java/com/atlassian/sal/api/auth/Authenticator.java +++ b/sal-api/src/main/java/com/atlassian/sal/api/auth/Authenticator.java @@ -1,137 +1,129 @@ package com.atlassian.sal.api.auth; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.atlassian.sal.api.message.Message; /** * Authenticates requests * * @since 2.0 */ public interface Authenticator { /** * Authenticates a request * @param request The request * @param response The response * @return The result of the authentication */ Result authenticate(HttpServletRequest request, HttpServletResponse response); /** * Encapsulates the results of an authentication attempt. Includes the result status, any problem that * occurred, and possibly the authenticated users {@link Principal}. */ static class Result { private final Result.Status status; private final Message message; private final Principal principal; Result(final Result.Status status) { this(status, null, null); } Result(final Result.Status status, final Message message) { this(status, message, null); } Result(final Result.Status status, final Principal principal) { this(status, null, principal); } Result(final Result.Status status, final Message message, final Principal principal) { if (status == null) { - throw new IllegalArgumentException("status"); - } - if (message == null) - { - throw new IllegalArgumentException("message"); - } - if (principal == null) - { - throw new IllegalArgumentException("principal"); + throw new NullPointerException("status"); } this.status = status; this.message = message; this.principal = principal; } public Result.Status getStatus() { return status; } public String getMessage() { return message.toString(); } public Principal getPrincipal() { return principal; } public static enum Status { SUCCESS("success"), FAILED("failed"), ERROR("error"), NO_ATTEMPT("no attempt"); private final String name; private Status(final String name) { this.name = name; } @Override public String toString() { return name; } } public static final class NoAttempt extends Result { public NoAttempt() { super(Status.NO_ATTEMPT); } } public static final class Error extends Result { public Error(final Message message) { super(Status.ERROR, message); } } public static final class Failure extends Result { public Failure(final Message message) { super(Status.FAILED, message); } } public static final class Success extends Result { public Success(final Principal principal) { super(Status.SUCCESS, principal); } } } }
true
true
Result(final Result.Status status, final Message message, final Principal principal) { if (status == null) { throw new IllegalArgumentException("status"); } if (message == null) { throw new IllegalArgumentException("message"); } if (principal == null) { throw new IllegalArgumentException("principal"); } this.status = status; this.message = message; this.principal = principal; }
Result(final Result.Status status, final Message message, final Principal principal) { if (status == null) { throw new NullPointerException("status"); } this.status = status; this.message = message; this.principal = principal; }
diff --git a/AndroidVkSdk/src/com/perm/kate/api/Group.java b/AndroidVkSdk/src/com/perm/kate/api/Group.java index 69581f6..b247793 100644 --- a/AndroidVkSdk/src/com/perm/kate/api/Group.java +++ b/AndroidVkSdk/src/com/perm/kate/api/Group.java @@ -1,58 +1,58 @@ package com.perm.kate.api; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Group { public long gid; public String name; public String photo;//50*50 public Boolean is_closed; public Boolean is_member; //это новые поля, которых у нас пока нет в базе //public String screen_name; //public Boolean is_admin; public String photo_medium;//100*100 public String photo_big;//200*200 public static Group parse(JSONObject o) throws JSONException{ Group g=new Group(); g.gid = o.getLong("gid"); g.name = Api.unescape(o.getString("name")); g.photo = o.getString("photo"); g.photo_medium = o.optString("photo_medium"); g.photo_big = o.optString("photo_big"); String is_closed = o.optString("is_closed"); if(is_closed != null) g.is_closed = is_closed.equals("1"); String is_member = o.optString("is_member"); if(is_member != null) - g.is_member = is_closed.equals("1"); + g.is_member = is_member.equals("1"); //это новые поля, которых у нас пока нет в базе //g.screen_name=o.optString("screen_name"); //String is_admin=o.optString("is_admin"); //if(is_admin!=null) // g.is_admin=is_admin.equals("1"); //g.photo_medium = o.getString("photo_medium"); //g.photo_big = o.getString("photo_big"); return g; } public static ArrayList<Group> parseGroups(JSONArray jgroups) throws JSONException { ArrayList<Group> groups=new ArrayList<Group>(); for(int i = 0; i < jgroups.length(); i++) { //для метода groups.get первый элемент - количество if(!(jgroups.get(i) instanceof JSONObject)) continue; JSONObject jgroup = (JSONObject)jgroups.get(i); Group group = Group.parse(jgroup); groups.add(group); } return groups; } }
true
true
public static Group parse(JSONObject o) throws JSONException{ Group g=new Group(); g.gid = o.getLong("gid"); g.name = Api.unescape(o.getString("name")); g.photo = o.getString("photo"); g.photo_medium = o.optString("photo_medium"); g.photo_big = o.optString("photo_big"); String is_closed = o.optString("is_closed"); if(is_closed != null) g.is_closed = is_closed.equals("1"); String is_member = o.optString("is_member"); if(is_member != null) g.is_member = is_closed.equals("1"); //это новые поля, которых у нас пока нет в базе //g.screen_name=o.optString("screen_name"); //String is_admin=o.optString("is_admin"); //if(is_admin!=null) // g.is_admin=is_admin.equals("1"); //g.photo_medium = o.getString("photo_medium"); //g.photo_big = o.getString("photo_big"); return g; }
public static Group parse(JSONObject o) throws JSONException{ Group g=new Group(); g.gid = o.getLong("gid"); g.name = Api.unescape(o.getString("name")); g.photo = o.getString("photo"); g.photo_medium = o.optString("photo_medium"); g.photo_big = o.optString("photo_big"); String is_closed = o.optString("is_closed"); if(is_closed != null) g.is_closed = is_closed.equals("1"); String is_member = o.optString("is_member"); if(is_member != null) g.is_member = is_member.equals("1"); //это новые поля, которых у нас пока нет в базе //g.screen_name=o.optString("screen_name"); //String is_admin=o.optString("is_admin"); //if(is_admin!=null) // g.is_admin=is_admin.equals("1"); //g.photo_medium = o.getString("photo_medium"); //g.photo_big = o.getString("photo_big"); return g; }
diff --git a/GSP/GSPFramework/src/main/java/fr/prima/gsp/framework/CModuleFactory.java b/GSP/GSPFramework/src/main/java/fr/prima/gsp/framework/CModuleFactory.java index 0b953ed..1faa376 100644 --- a/GSP/GSPFramework/src/main/java/fr/prima/gsp/framework/CModuleFactory.java +++ b/GSP/GSPFramework/src/main/java/fr/prima/gsp/framework/CModuleFactory.java @@ -1,403 +1,403 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package fr.prima.gsp.framework; import com.sun.jna.Callback; import com.sun.jna.Function; import com.sun.jna.Native; import com.sun.jna.NativeLibrary; import com.sun.jna.Pointer; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; /** * * @author emonet */ public class CModuleFactory { { // code to avoid freeze in library loading (don't know why) // we just access to the Native class before anything else if (Native.POINTER_SIZE < 4) { System.err.println("This is quite strange"); } } Map<String, Bundle> bundles = new HashMap<String, Bundle>(); List<Module> modules = new LinkedList<Module>(); CModuleFactory() { } public Module createModule(String bundleName, String moduleTypeName) { //System.err.println("loading " + bundleName); Bundle bundle = getBundle(bundleName); if (bundle == null) { return null; } //System.err.println("creating "+bundleName+":"+moduleTypeName); CModule newModule = createCModule(bundleName, moduleTypeName); //System.err.println("done"); return newModule; } private Bundle getBundle(String bundleName) { Bundle bundle = bundles.get(bundleName); if (bundle == null) { NativeLibrary.addSearchPath(bundleName, "."); String module_path = System.getenv("GSP_MODULES_PATH"); - if(!module_path.isEmpty()) { + if( module_path!=null && !module_path.isEmpty()) { String delims = ":"; String[] tokens = module_path.split(delims); for (int i = 0; i < tokens.length; i++) { if(!tokens[i].isEmpty()) NativeLibrary.addSearchPath(bundleName, tokens[i]); } } try { bundle = new Bundle(NativeLibrary.getInstance(bundleName)); bundles.put(bundleName, bundle); } catch (Exception e) { // cannot load // TODO } } return bundle; } private CModule createCModule(String bundleName, String moduleTypeName) { Bundle bundle = bundles.get(bundleName); CModule module = new CModule(bundle, bundleName, moduleTypeName); if (module.that != Pointer.NULL) { // long moduleNumber = module.number; // String moduleId = bundleName + " " + moduleTypeName + " " + moduleNumber; modules.add(module); return module; } else { return null; } } public static String capFirst(String s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } public static String setter(String parameterName) { return "set" + capFirst(parameterName); } private static String sep = "__v__"; private static CppMangler mangler = new CppMangler(); private class Bundle { NativeLibrary library; private Bundle(NativeLibrary library) { this.library = library; } private Pointer createModule(String moduleTypeName, FrameworkCallback f) { Pointer res = f(moduleTypeName, "create").invokePointer(new Object[]{f}); if (res != Pointer.NULL) { fOpt(moduleTypeName, "created", res); } return res; } private void setModuleParameter(String moduleTypeName, Pointer that, String parameterName, Object value) { try { f(moduleTypeName, "set" + sep + parameterName).invoke(new Object[]{that, value}); } catch (UnsatisfiedLinkError err) { f(mangler.mangleVoidMethod(moduleTypeName, setter(parameterName), new Object[]{value})).invoke(new Object[]{that, value}); } } private void initModule(String moduleTypeName, Pointer that) { try { f(moduleTypeName, "init").invoke(new Object[]{that}); } catch (UnsatisfiedLinkError err) { try { f(mangler.mangleVoidMethod(moduleTypeName, "initModule", new Object[]{})).invoke(new Object[]{that}); } catch (UnsatisfiedLinkError err2) { // swallow exception } } } private void stopModule(String moduleTypeName, Pointer that) { try { f(moduleTypeName, "stop").invoke(new Object[]{that}); } catch (UnsatisfiedLinkError err) { try { f(mangler.mangleVoidMethod(moduleTypeName, "stopModule", new Object[]{})).invoke(new Object[]{that}); f(moduleTypeName, "delete").invoke(new Object[]{that}); } catch (UnsatisfiedLinkError err2) { // swallow exception } } } private void receiveEvent(String moduleTypeName, Pointer that, String portName, Event e) { Object[] information = e.getInformation(); Object[] allParams = new Object[information.length + 1]; System.arraycopy(information, 0, allParams, 1, information.length); allParams[0] = that; try { f(moduleTypeName, "event" + sep + portName).invoke(allParams); } catch (UnsatisfiedLinkError err) { f(mangler.mangleVoidMethod(moduleTypeName, portName, information, e.getAdditionalTypeInformation())).invoke(allParams); } } private Function f(String functionName) { return f(null, functionName); } private Function f(String prefix, String functionName) { return library.getFunction((prefix == null ? "" : prefix + sep) + functionName); } private void fOpt(String prefix, String functionName, Object... args) { try { f(prefix, functionName).invoke(args); } catch (UnsatisfiedLinkError err) { // swallow exception } } } private static interface FrameworkCallback extends Callback { void callback(String commandName, Pointer parameters); } private static class CModule extends BaseAbstractModule implements Module { Pointer that; FrameworkCallback framework; Bundle bundle; String bundleName; String moduleTypeName; Map<String, String> parameterTypes = new HashMap<String, String>(); private Set<String> nonParameters = new HashSet<String>() {{ add("id"); add("type"); }}; private CModule(Bundle bundle, String bundleName, String moduleTypeName) { this.bundle = bundle; this.bundleName = bundleName; this.moduleTypeName = moduleTypeName; this.framework = new FrameworkCallback() { public void callback(String commandName, Pointer parameters) { cCallback(commandName, parameters.getPointerArray(0)); } }; that = bundle.createModule(moduleTypeName, framework); if (that == Pointer.NULL) return; } public EventReceiver getEventReceiver(final String portName) { return new EventReceiver() { public void receiveEvent(Event e) { bundle.receiveEvent(moduleTypeName, that, portName, e); } }; } public void addConnector(String portName, EventReceiver eventReceiver) { listenersFor(portName).add(eventReceiver); } public void configure(Element conf) { NamedNodeMap attributes = conf.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Node node = attributes.item(i); String parameterName = node.getNodeName(); if (nonParameters.contains(parameterName)) { continue; } String text = node.getTextContent(); setParameter(parameterName, text); } } @Override protected void initModule() { bundle.initModule(moduleTypeName, that); } @Override protected void stopModule() { bundle.stopModule(moduleTypeName, that); } // callback from C private void cCallback(String commandName, Pointer[] parameters) { if ("param".equals(commandName)) { parameterTypes.put(parameters[1].getString(0), parameters[0].getString(0)); } else if ("emit".equals(commandName)) { Object[] eventParameters = new Object[parameters.length / 2]; String[] eventParametersTypes = new String[parameters.length / 2]; for (int i = 1; i < parameters.length; i += 2) { String type = patchReportedType(parameters[i].getString(0)); Object value = getValueFromNative(type, parameters[i + 1]); eventParameters[i / 2] = value; eventParametersTypes[i / 2] = type; } emitNamedEvent(parameters[0].getString(0), eventParameters, eventParametersTypes); } else { System.err.println("Unsupported callback type " + commandName); } } // used for xml parameter interpretation private static Object getNativeFromString(String type, String text) { // could find a way to reuse jna mapping but I didn't managed to :( try { return stringToNatives.get(type).toNative(text); } catch (NullPointerException ex) { System.err.println("problem with type '" + type + "' to interpret '" + text + "'"); throw ex; } } private void setParameter(String parameterName, String text) { String registeredType = parameterTypes.get(parameterName); if (registeredType != null) { Object value = getNativeFromString(registeredType, text); bundle.setModuleParameter(moduleTypeName, that, parameterName, value); } else { String type = mangler.findSingleParameterTypeForSingleVoidMethod(bundle.library, moduleTypeName, setter(parameterName)); System.err.println("TYPE is "+type); Object value = getNativeFromString(type, text); bundle.setModuleParameter(moduleTypeName, that, parameterName, value); // could cache here } } private Map<String, String> cTypeToTypeid = new HashMap<String, String>() {{ put("int", "i"); put("unsigned int", "j"); put("float", "f"); put("long", "l"); put("double", "d"); put("char", "c"); put("bool", "b"); }}; private String patchReportedType(String type) { boolean isPointer = true; if (type.startsWith("A")) { type = type.replaceFirst("A\\d+_", "P"); } else if (type.startsWith("P")) { type = type.substring(1); } else if (type.endsWith("*")) { type = type.substring(0, type.length() - 1); } else { isPointer = false; } type = type.trim(); String res = cTypeToTypeid.get(type); if (res != null) type = res; return isPointer ? "P" + type : type; } private static interface StringToNative { Object toNative(String text); } private static Map<String, StringToNative> stringToNatives = new HashMap<String, StringToNative>() { { put("char*", new StringToNative() { public Object toNative(String text) { return text; } }); put("float", new StringToNative() { public Object toNative(String text) { return Float.parseFloat(text); } }); put("double", new StringToNative() { public Object toNative(String text) { return Double.parseDouble(text); } }); put("int", new StringToNative() { public Object toNative(String text) { return Integer.parseInt(text); } }); put("long", new StringToNative() { public Object toNative(String text) { return Long.parseLong(text); } }); put("bool", new StringToNative() { public Object toNative(String text) { return Boolean.parseBoolean(text); } }); } }; private static interface NativeInterpreter { Object interpret(Pointer pointer); } private static Map<String, NativeInterpreter> nativeInterpreters = new HashMap<String, NativeInterpreter>() { { put("f", new NativeInterpreter() { public Object interpret(Pointer pointer) { return pointer.getFloat(0); } }); put("d", new NativeInterpreter() { public Object interpret(Pointer pointer) { return pointer.getDouble(0); } }); put("i", new NativeInterpreter() { public Object interpret(Pointer pointer) { return pointer.getInt(0); } }); put("j", new NativeInterpreter() { public Object interpret(Pointer pointer) { return pointer.getInt(0); } }); put("l", new NativeInterpreter() { public Object interpret(Pointer pointer) { return pointer.getLong(0); } }); } }; private static Object getValueFromNative(String type, Pointer pointer) { if (type.startsWith("P")) { return pointer.getPointer(0); } // could find a way to reuse jna mapping but I didn't managed to :( try { return nativeInterpreters.get(type).interpret(pointer); } catch (NullPointerException ex) { throw new RuntimeException("NPE while reading value for native type '" + type + "'", ex); } } } }
true
true
private Bundle getBundle(String bundleName) { Bundle bundle = bundles.get(bundleName); if (bundle == null) { NativeLibrary.addSearchPath(bundleName, "."); String module_path = System.getenv("GSP_MODULES_PATH"); if(!module_path.isEmpty()) { String delims = ":"; String[] tokens = module_path.split(delims); for (int i = 0; i < tokens.length; i++) { if(!tokens[i].isEmpty()) NativeLibrary.addSearchPath(bundleName, tokens[i]); } } try { bundle = new Bundle(NativeLibrary.getInstance(bundleName)); bundles.put(bundleName, bundle); } catch (Exception e) { // cannot load // TODO } } return bundle; }
private Bundle getBundle(String bundleName) { Bundle bundle = bundles.get(bundleName); if (bundle == null) { NativeLibrary.addSearchPath(bundleName, "."); String module_path = System.getenv("GSP_MODULES_PATH"); if( module_path!=null && !module_path.isEmpty()) { String delims = ":"; String[] tokens = module_path.split(delims); for (int i = 0; i < tokens.length; i++) { if(!tokens[i].isEmpty()) NativeLibrary.addSearchPath(bundleName, tokens[i]); } } try { bundle = new Bundle(NativeLibrary.getInstance(bundleName)); bundles.put(bundleName, bundle); } catch (Exception e) { // cannot load // TODO } } return bundle; }
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java index cdbda0fb..f57e0dd6 100644 --- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java +++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/decorators/GitDocument.java @@ -1,244 +1,244 @@ /******************************************************************************* * Copyright (C) 2008, 2009 Robin Rosenberg <[email protected]> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.egit.ui.internal.decorators; import java.io.IOException; import java.util.Map; import java.util.WeakHashMap; import org.eclipse.core.resources.IResource; import org.eclipse.egit.core.GitProvider; import org.eclipse.egit.core.project.RepositoryMapping; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.CompareUtils; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.jface.text.Document; import org.eclipse.jgit.events.ListenerHandle; import org.eclipse.jgit.events.RefsChangedEvent; import org.eclipse.jgit.events.RefsChangedListener; import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; import org.eclipse.jgit.lib.ObjectLoader; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.revwalk.RevCommit; import org.eclipse.jgit.revwalk.RevTree; import org.eclipse.jgit.revwalk.RevWalk; import org.eclipse.jgit.treewalk.TreeWalk; import org.eclipse.osgi.util.NLS; import org.eclipse.team.core.RepositoryProvider; class GitDocument extends Document implements RefsChangedListener { private final IResource resource; private ObjectId lastCommit; private ObjectId lastTree; private ObjectId lastBlob; private ListenerHandle myRefsChangedHandle; static Map<GitDocument, Repository> doc2repo = new WeakHashMap<GitDocument, Repository>(); static GitDocument create(final IResource resource) throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) create: " + resource); //$NON-NLS-1$ GitDocument ret = null; if (RepositoryProvider.getProvider(resource.getProject()) instanceof GitProvider) { ret = new GitDocument(resource); ret.populate(); final Repository repository = ret.getRepository(); if (repository != null) ret.myRefsChangedHandle = repository.getListenerList() .addRefsChangedListener(ret); } return ret; } private GitDocument(IResource resource) { this.resource = resource; GitDocument.doc2repo.put(this, getRepository()); } private void setResolved(final AnyObjectId commit, final AnyObjectId tree, final AnyObjectId blob, final String value) { lastCommit = commit != null ? commit.copy() : null; lastTree = tree != null ? tree.copy() : null; lastBlob = blob != null ? blob.copy() : null; set(value); if (blob != null) if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) resolved " + resource + " to " + lastBlob + " in " + lastCommit + "/" + lastTree); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ else if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) unresolved " + resource); //$NON-NLS-1$ } void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); if (tw == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { - treeId, baseline, resource, repository }); + treeId.getName(), baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { - treeId, baseline, resource, repository }); + treeId.getName(), baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } } void dispose() { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) dispose: " + resource); //$NON-NLS-1$ doc2repo.remove(this); if (myRefsChangedHandle != null) { myRefsChangedHandle.remove(); myRefsChangedHandle = null; } } public void onRefsChanged(final RefsChangedEvent e) { try { populate(); } catch (IOException e1) { Activator.logError(UIText.GitDocument_errorRefreshQuickdiff, e1); } } private Repository getRepository() { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); return (mapping != null) ? mapping.getRepository() : null; } /** * A change occurred to a repository. Update any GitDocument instances * referring to such repositories. * * @param repository * Repository which changed * @throws IOException */ static void refreshRelevant(final Repository repository) throws IOException { for (Map.Entry<GitDocument, Repository> i : doc2repo.entrySet()) { if (i.getValue() == repository) { i.getKey().populate(); } } } }
false
true
void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); if (tw == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId, baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId, baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } }
void populate() throws IOException { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.QUICKDIFF.getLocation(), resource); TreeWalk tw = null; RevWalk rw = null; try { RepositoryMapping mapping = RepositoryMapping.getMapping(resource); if (mapping == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ return; } final String gitPath = mapping.getRepoRelativePath(resource); final Repository repository = mapping.getRepository(); String baseline = GitQuickDiffProvider.baseline.get(repository); if (baseline == null) baseline = Constants.HEAD; ObjectId commitId = repository.resolve(baseline); if (commitId != null) { if (commitId.equals(lastCommit)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } } else { String msg = NLS.bind(UIText.GitDocument_errorResolveQuickdiff, new Object[] { baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } rw = new RevWalk(repository); RevCommit baselineCommit; try { baselineCommit = rw.parseCommit(commitId); } catch (IOException err) { String msg = NLS .bind(UIText.GitDocument_errorLoadCommit, new Object[] { commitId, baseline, resource, repository }); Activator.logError(msg, err); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } RevTree treeId = baselineCommit.getTree(); if (treeId.equals(lastTree)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ return; } tw = TreeWalk.forPath(repository, gitPath, treeId); if (tw == null) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId.getName(), baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } ObjectId id = tw.getObjectId(0); if (id.equals(ObjectId.zeroId())) { setResolved(null, null, null, ""); //$NON-NLS-1$ String msg = NLS .bind(UIText.GitDocument_errorLoadTree, new Object[] { treeId.getName(), baseline, resource, repository }); Activator.logError(msg, new Throwable()); setResolved(null, null, null, ""); //$NON-NLS-1$ return; } if (!id.equals(lastBlob)) { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) compareTo: " + baseline); //$NON-NLS-1$ ObjectLoader loader = repository.open(id, Constants.OBJ_BLOB); byte[] bytes = loader.getBytes(); String charset; charset = CompareUtils.getResourceEncoding(resource); // Finally we could consider validating the content with respect // to the content. We don't do that here. String s = new String(bytes, charset); setResolved(commitId, treeId, id, s); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation .getTrace() .trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) has reference doc, size=" + s.length() + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ } else { if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().trace( GitTraceLocation.QUICKDIFF.getLocation(), "(GitDocument) already resolved"); //$NON-NLS-1$ } } finally { if (tw != null) tw.release(); if (rw != null) rw.release(); if (GitTraceLocation.QUICKDIFF.isActive()) GitTraceLocation.getTrace().traceExit( GitTraceLocation.QUICKDIFF.getLocation()); } }
diff --git a/modules/dCache/diskCacheV111/pools/SpaceSweeper2.java b/modules/dCache/diskCacheV111/pools/SpaceSweeper2.java index 1852114615..80b396a5cb 100644 --- a/modules/dCache/diskCacheV111/pools/SpaceSweeper2.java +++ b/modules/dCache/diskCacheV111/pools/SpaceSweeper2.java @@ -1,412 +1,412 @@ // $Id: SpaceSweeper2.java,v 1.2 2007-10-08 08:00:29 behrmann Exp $ package diskCacheV111.pools; import diskCacheV111.repository.*; import diskCacheV111.util.*; import diskCacheV111.util.event.*; import diskCacheV111.vehicles.StorageInfo; import dmg.util.*; import dmg.cells.nucleus.*; import java.util.*; import java.text.SimpleDateFormat; import java.io.PrintWriter; public class SpaceSweeper2 implements SpaceSweeper, Runnable { private final CacheRepository _repository; private final CellAdapter _cell; private final Set<PnfsId> _list = new LinkedHashSet<PnfsId>(); private long _spaceNeeded = 0; private long _removableSpace = 0; private static SimpleDateFormat __format = new SimpleDateFormat("HH:mm-MM/dd"); public SpaceSweeper2(CellAdapter cell, PnfsHandler pnfs, CacheRepository repository) { _repository = repository; _cell = cell; _repository.addCacheRepositoryListener(this); _cell.getNucleus().newThread(this, "sweeper").start(); } public synchronized long getRemovableSpace() { return _removableSpace; } /** * Returns true if this file is removable. This is the case if the * file is not sticky and is cached (which under normal * circumstances implies that it is ready and not precious). */ private boolean isRemovable(CacheRepositoryEntry entry) { try { synchronized (entry) { return !entry.isReceivingFromClient() && !entry.isReceivingFromStore() && !entry.isPrecious() && !entry.isSticky() && entry.isCached(); } } catch (CacheException e) { esay("Failed to query state of entry: " + e.getMessage()); /* Returning false is the safe option. */ return false; } } /** * Add entry to the queue unless it is already on the queue. * * @throws IllegalArgumentException if entry is precious or not cached */ private synchronized void add(CacheRepositoryEntry entry) { if (!isRemovable(entry)) { throw new IllegalArgumentException("Cannot add a precious or un-cached file to the sweeper queue."); } PnfsId id = entry.getPnfsId(); try { if (_list.add(id)) { say("added " + id + " to list"); entry.touch(); _removableSpace += entry.getSize(); /* The sweeper thread may be waiting for more files to * delete. */ notifyAll(); } } catch (CacheException e) { esay("failed to add " + id.toString() + " to list: " + e); } } /** Remove entry from the queue. */ private synchronized boolean remove(CacheRepositoryEntry entry) { PnfsId id = entry.getPnfsId(); try { long size = entry.getSize(); if (_list.remove(id)) { say("removed " + id + " from list"); _removableSpace -= size; return true; } } catch (CacheException e) { esay("failed to remove " + id.toString() + " from list: " + e); } return false; } private synchronized PnfsId getLRUId() { if (_list.size() == 0) return null; return _list.iterator().next(); } public long getLRUSeconds() { try { PnfsId id = getLRUId(); if (id == null) return 0; CacheRepositoryEntry e = _repository.getEntry(id); return (System.currentTimeMillis() - e.getLastAccessTime()) / 1000L; } catch (CacheException e) { return 0L; } } public void actionPerformed(CacheEvent event) { /* forced by CacheRepositoryListener interface */ } public synchronized void precious(CacheRepositoryEvent event) { CacheRepositoryEntry entry = event.getRepositoryEntry(); say("precious: " + entry); remove(entry); } public synchronized void sticky(CacheRepositoryEvent event) { say("sticky: " + event); CacheRepositoryEntry entry = event.getRepositoryEntry(); if (isRemovable(entry)) { add(entry); } else { remove(entry); } } public void available(CacheRepositoryEvent event) { /* forced by CacheRepositoryListener interface */ } public void created(CacheRepositoryEvent event) { /* forced by CacheRepositoryListener interface */ } public void destroyed(CacheRepositoryEvent event) { /* forced by CacheRepositoryListener interface */ } public synchronized void touched(CacheRepositoryEvent event) { CacheRepositoryEntry entry = event.getRepositoryEntry(); PnfsId id = entry.getPnfsId(); if (_list.remove(id)) { say("touched : " + entry); try { entry.touch(); } catch (CacheException e) { say("failed to touch data file: " + e.getMessage()); } _list.add(id); } } public synchronized void removed(CacheRepositoryEvent event) { CacheRepositoryEntry entry = event.getRepositoryEntry(); remove(entry); } public synchronized void needSpace(CacheNeedSpaceEvent event) { long space = event.getRequiredSpace(); _spaceNeeded += space; say("needSpace event " + space + " -> " + _spaceNeeded); notifyAll(); } public synchronized void scanned(CacheRepositoryEvent event) { CacheRepositoryEntry entry = event.getRepositoryEntry(); say("scanned event : " + entry); if (isRemovable(entry)) { add(entry); } } public synchronized void cached(CacheRepositoryEvent event) { CacheRepositoryEntry entry = event.getRepositoryEntry(); PnfsId id = entry.getPnfsId(); say("cached event : " + entry); if (isRemovable(entry)) { add(entry); } } public String hh_sweeper_purge = "# Purges all removable files from pool"; public synchronized String ac_sweeper_purge(Args args) throws Exception { long toFree = getRemovableSpace(); _spaceNeeded += toFree; notifyAll(); return "" + toFree + " bytes added to reallocation queue"; } public String hh_sweeper_free = "<bytesToFree>"; public synchronized String ac_sweeper_free_$_1(Args args) throws NumberFormatException { long toFree = Long.parseLong(args.argv(0)); _spaceNeeded += toFree; notifyAll(); return "" + toFree + " bytes added to reallocation queue"; } public String hh_sweeper_ls = " [-l] [-s]"; public String ac_sweeper_ls(Args args) throws CacheException { StringBuilder sb = new StringBuilder(); boolean l = args.getOpt("l") != null; boolean s = args.getOpt("s") != null; List<PnfsId> list; synchronized (this) { list = new ArrayList<PnfsId>(_list); } int i = 0; for (PnfsId id : list) { CacheRepositoryEntry entry = _repository.getEntry(id); if (l) { sb.append(Formats.field(""+i,3,Formats.RIGHT)).append(" "); sb.append(id.toString()).append(" "); sb.append(entry.getState()).append(" "); sb.append(Formats.field(""+entry.getSize(), 11, Formats.RIGHT)); sb.append(" "); sb.append(__format.format(new Date(entry.getCreationTime()))).append(" "); sb.append(__format.format(new Date(entry.getLastAccessTime()))).append(" "); StorageInfo info = entry.getStorageInfo(); if ((info != null) && s) sb.append("\n ").append(info.toString()); sb.append("\n"); } else { sb.append(entry.toString()).append("\n"); } i++; } return sb.toString(); } private String getTimeString(long secin) { int sec = Math.max(0, (int)secin); int min = sec / 60; sec = sec % 60; int hour = min / 60; min = min % 60; int day = hour / 24; hour = hour % 24; String sS = Integer.toString(sec); String mS = Integer.toString(min); String hS = Integer.toString(hour); StringBuilder sb = new StringBuilder(); if (day > 0) sb.append(day).append(" d "); sb.append(hS.length() < 2 ? ( "0"+hS ) : hS).append(":"); sb.append(mS.length() < 2 ? ( "0"+mS ) : mS).append(":"); sb.append(sS.length() < 2 ? ( "0"+sS ) : sS); return sb.toString() ; } public String hh_sweeper_get_lru = "[-f] # return lru in seconds [-f means formatted]"; public String ac_sweeper_get_lru( Args args ) { long lru = getLRUSeconds(); boolean f = args.getOpt("f") != null; return f ? getTimeString(lru) : ("" + lru); } public void run() { long spaceNeeded = 0; say("started"); List<CacheRepositoryEntry> tmpList = new ArrayList<CacheRepositoryEntry>(); try { while (!Thread.interrupted()) { /* Take the needed space out of the 'queue'. */ synchronized (this) { - while (spaceNeeded + _spaceNeeded == 0) { + while (spaceNeeded + _spaceNeeded == 0 || _list.isEmpty()) { wait(); } spaceNeeded += _spaceNeeded; _spaceNeeded = 0; } say("request to remove : " + spaceNeeded); /* We copy the entries into a tmp list to avoid the * ConcurrentModificationException. */ try { Iterator<PnfsId> i = _list.iterator(); long minSpaceNeeded = spaceNeeded; while (i.hasNext() && minSpaceNeeded > 0) { PnfsId id = i.next(); try { CacheRepositoryEntry entry = _repository.getEntry(id); // // we are not allowed to remove the // file if // a) it is locked // b) it is still in use. // if (entry.isLocked()) { esay("file skipped by remove (locked) : " + entry); continue; } if (entry.getLinkCount() > 0) { esay("file skipped by remove (in use) : " + entry); continue; } if (!isRemovable(entry)) { esay("FATAL: file skipped by remove (not removable) : " + entry); continue; } long size = entry.getSize(); tmpList.add(entry); minSpaceNeeded -= size; say("adds to remove list : " + entry.getPnfsId() + " " + size + " -> " + spaceNeeded); } catch (CacheException e) { esay(e.getMessage()); } } } catch (ConcurrentModificationException e) { /* Loop exited, this is not an error. We are not * supposed to do exact space allocation. */ } /* Delete the files. */ for (CacheRepositoryEntry entry : tmpList) { try { long size = entry.getSize(); say("trying to remove " + entry.getPnfsId()); if (_repository.removeEntry(entry)) { spaceNeeded -= size; } else { say("locked (not removed) : " + entry.getPnfsId()); } } catch (CacheException e) { esay(e.toString()); } } spaceNeeded = Math.max(spaceNeeded, 0); tmpList.clear(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { _repository.removeCacheRepositoryListener(this); say("finished"); } } public void printSetup(PrintWriter pw) { pw.println("#\n# Nothing from the " + this.getClass().getName() + "#"); } private void say(String msg) { _cell.say("SWEEPER : " + msg); } private void esay(String msg) { _cell.esay("SWEEPER ERROR : " + msg); } }
true
true
public void run() { long spaceNeeded = 0; say("started"); List<CacheRepositoryEntry> tmpList = new ArrayList<CacheRepositoryEntry>(); try { while (!Thread.interrupted()) { /* Take the needed space out of the 'queue'. */ synchronized (this) { while (spaceNeeded + _spaceNeeded == 0) { wait(); } spaceNeeded += _spaceNeeded; _spaceNeeded = 0; } say("request to remove : " + spaceNeeded); /* We copy the entries into a tmp list to avoid the * ConcurrentModificationException. */ try { Iterator<PnfsId> i = _list.iterator(); long minSpaceNeeded = spaceNeeded; while (i.hasNext() && minSpaceNeeded > 0) { PnfsId id = i.next(); try { CacheRepositoryEntry entry = _repository.getEntry(id); // // we are not allowed to remove the // file if // a) it is locked // b) it is still in use. // if (entry.isLocked()) { esay("file skipped by remove (locked) : " + entry); continue; } if (entry.getLinkCount() > 0) { esay("file skipped by remove (in use) : " + entry); continue; } if (!isRemovable(entry)) { esay("FATAL: file skipped by remove (not removable) : " + entry); continue; } long size = entry.getSize(); tmpList.add(entry); minSpaceNeeded -= size; say("adds to remove list : " + entry.getPnfsId() + " " + size + " -> " + spaceNeeded); } catch (CacheException e) { esay(e.getMessage()); } } } catch (ConcurrentModificationException e) { /* Loop exited, this is not an error. We are not * supposed to do exact space allocation. */ } /* Delete the files. */ for (CacheRepositoryEntry entry : tmpList) { try { long size = entry.getSize(); say("trying to remove " + entry.getPnfsId()); if (_repository.removeEntry(entry)) { spaceNeeded -= size; } else { say("locked (not removed) : " + entry.getPnfsId()); } } catch (CacheException e) { esay(e.toString()); } } spaceNeeded = Math.max(spaceNeeded, 0); tmpList.clear(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { _repository.removeCacheRepositoryListener(this); say("finished"); } }
public void run() { long spaceNeeded = 0; say("started"); List<CacheRepositoryEntry> tmpList = new ArrayList<CacheRepositoryEntry>(); try { while (!Thread.interrupted()) { /* Take the needed space out of the 'queue'. */ synchronized (this) { while (spaceNeeded + _spaceNeeded == 0 || _list.isEmpty()) { wait(); } spaceNeeded += _spaceNeeded; _spaceNeeded = 0; } say("request to remove : " + spaceNeeded); /* We copy the entries into a tmp list to avoid the * ConcurrentModificationException. */ try { Iterator<PnfsId> i = _list.iterator(); long minSpaceNeeded = spaceNeeded; while (i.hasNext() && minSpaceNeeded > 0) { PnfsId id = i.next(); try { CacheRepositoryEntry entry = _repository.getEntry(id); // // we are not allowed to remove the // file if // a) it is locked // b) it is still in use. // if (entry.isLocked()) { esay("file skipped by remove (locked) : " + entry); continue; } if (entry.getLinkCount() > 0) { esay("file skipped by remove (in use) : " + entry); continue; } if (!isRemovable(entry)) { esay("FATAL: file skipped by remove (not removable) : " + entry); continue; } long size = entry.getSize(); tmpList.add(entry); minSpaceNeeded -= size; say("adds to remove list : " + entry.getPnfsId() + " " + size + " -> " + spaceNeeded); } catch (CacheException e) { esay(e.getMessage()); } } } catch (ConcurrentModificationException e) { /* Loop exited, this is not an error. We are not * supposed to do exact space allocation. */ } /* Delete the files. */ for (CacheRepositoryEntry entry : tmpList) { try { long size = entry.getSize(); say("trying to remove " + entry.getPnfsId()); if (_repository.removeEntry(entry)) { spaceNeeded -= size; } else { say("locked (not removed) : " + entry.getPnfsId()); } } catch (CacheException e) { esay(e.toString()); } } spaceNeeded = Math.max(spaceNeeded, 0); tmpList.clear(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { _repository.removeCacheRepositoryListener(this); say("finished"); } }
diff --git a/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java b/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java index 9525eb474..c0dd12237 100644 --- a/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java +++ b/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java @@ -1,132 +1,132 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.client.gui.panel; import java.util.logging.Logger; import javax.swing.JLabel; import net.sf.freecol.client.gui.Canvas; import net.sf.freecol.client.gui.i18n.Messages; import net.sf.freecol.common.model.GoodsType; import net.sf.freecol.common.model.IndianSettlement; import net.sf.freecol.common.model.Player; import net.sf.freecol.common.model.StringTemplate; import net.sf.freecol.common.model.Unit; import net.sf.freecol.common.model.UnitType; import net.miginfocom.swing.MigLayout; /** * This panel is used to show information about an Indian settlement. */ public final class IndianSettlementPanel extends FreeColPanel { @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(IndianSettlementPanel.class.getName()); /** * The constructor that will add the items to this panel. */ public IndianSettlementPanel(final Canvas canvas, IndianSettlement settlement) { super(canvas); setLayout(new MigLayout("wrap 2, gapx 20", "", "")); JLabel settlementLabel = new JLabel(canvas.getImageIcon(settlement, false)); Player indian = settlement.getOwner(); Player player = getMyPlayer(); - boolean visible = settlement.hasContactedSettlement(player); + boolean visited = settlement.hasBeenVisited(player); String text = Messages.message(settlement.getNameFor(player)) + ", " + Messages.message(StringTemplate.template(settlement.isCapital() ? "indianCapital" : "indianSettlement") .addStringTemplate("%nation%", indian.getNationName())); String messageId = settlement.getShortAlarmLevelMessageId(player); text += " (" + Messages.message(messageId) + ")"; settlementLabel.setText(text); add(settlementLabel); Unit missionary = settlement.getMissionary(); if (missionary != null) { String missionaryName = Messages.message(StringTemplate.template("model.unit.nationUnit") .addStringTemplate("%nation%", missionary.getOwner().getNationName()) .addStringTemplate("%unit%", missionary.getLabel())); add(new JLabel(missionaryName, canvas.getImageIcon(missionary, true), JLabel.CENTER)); } add(localizedLabel("indianSettlement.learnableSkill"), "newline"); UnitType skillType = settlement.getLearnableSkill(); - if (visible) { + if (visited) { if (skillType == null) { add(localizedLabel("indianSettlement.skillNone")); } else { add(new JLabel(Messages.message(skillType.getNameKey()), canvas.getImageIcon(skillType, true), JLabel.CENTER)); } } else { add(localizedLabel("indianSettlement.skillUnknown")); } GoodsType[] wantedGoods = settlement.getWantedGoods(); String sale; add(localizedLabel("indianSettlement.highlyWanted"), "newline"); - if (!visible || wantedGoods.length == 0 || wantedGoods[0] == null) { + if (!visited || wantedGoods.length == 0 || wantedGoods[0] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { sale = player.getLastSaleString(settlement, wantedGoods[0]); add(new JLabel(Messages.message(wantedGoods[0].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[0], false), JLabel.CENTER)); } add(localizedLabel("indianSettlement.otherWanted"), "newline"); - if (!visible || wantedGoods.length <= 1 || wantedGoods[1] == null) { + if (!visited || wantedGoods.length <= 1 || wantedGoods[1] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { int i, n = 1; for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) n++; } sale = player.getLastSaleString(settlement, wantedGoods[1]); add(new JLabel(Messages.message(wantedGoods[1].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[1], false), JLabel.CENTER), "split " + Integer.toString(n)); for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) { sale = player.getLastSaleString(settlement,wantedGoods[i]); add(new JLabel(Messages.message(wantedGoods[i].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[i], false), JLabel.CENTER)); } } } add(okButton, "newline 20, span, tag ok"); setSize(getPreferredSize()); } }
false
true
public IndianSettlementPanel(final Canvas canvas, IndianSettlement settlement) { super(canvas); setLayout(new MigLayout("wrap 2, gapx 20", "", "")); JLabel settlementLabel = new JLabel(canvas.getImageIcon(settlement, false)); Player indian = settlement.getOwner(); Player player = getMyPlayer(); boolean visible = settlement.hasContactedSettlement(player); String text = Messages.message(settlement.getNameFor(player)) + ", " + Messages.message(StringTemplate.template(settlement.isCapital() ? "indianCapital" : "indianSettlement") .addStringTemplate("%nation%", indian.getNationName())); String messageId = settlement.getShortAlarmLevelMessageId(player); text += " (" + Messages.message(messageId) + ")"; settlementLabel.setText(text); add(settlementLabel); Unit missionary = settlement.getMissionary(); if (missionary != null) { String missionaryName = Messages.message(StringTemplate.template("model.unit.nationUnit") .addStringTemplate("%nation%", missionary.getOwner().getNationName()) .addStringTemplate("%unit%", missionary.getLabel())); add(new JLabel(missionaryName, canvas.getImageIcon(missionary, true), JLabel.CENTER)); } add(localizedLabel("indianSettlement.learnableSkill"), "newline"); UnitType skillType = settlement.getLearnableSkill(); if (visible) { if (skillType == null) { add(localizedLabel("indianSettlement.skillNone")); } else { add(new JLabel(Messages.message(skillType.getNameKey()), canvas.getImageIcon(skillType, true), JLabel.CENTER)); } } else { add(localizedLabel("indianSettlement.skillUnknown")); } GoodsType[] wantedGoods = settlement.getWantedGoods(); String sale; add(localizedLabel("indianSettlement.highlyWanted"), "newline"); if (!visible || wantedGoods.length == 0 || wantedGoods[0] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { sale = player.getLastSaleString(settlement, wantedGoods[0]); add(new JLabel(Messages.message(wantedGoods[0].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[0], false), JLabel.CENTER)); } add(localizedLabel("indianSettlement.otherWanted"), "newline"); if (!visible || wantedGoods.length <= 1 || wantedGoods[1] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { int i, n = 1; for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) n++; } sale = player.getLastSaleString(settlement, wantedGoods[1]); add(new JLabel(Messages.message(wantedGoods[1].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[1], false), JLabel.CENTER), "split " + Integer.toString(n)); for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) { sale = player.getLastSaleString(settlement,wantedGoods[i]); add(new JLabel(Messages.message(wantedGoods[i].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[i], false), JLabel.CENTER)); } } } add(okButton, "newline 20, span, tag ok"); setSize(getPreferredSize()); }
public IndianSettlementPanel(final Canvas canvas, IndianSettlement settlement) { super(canvas); setLayout(new MigLayout("wrap 2, gapx 20", "", "")); JLabel settlementLabel = new JLabel(canvas.getImageIcon(settlement, false)); Player indian = settlement.getOwner(); Player player = getMyPlayer(); boolean visited = settlement.hasBeenVisited(player); String text = Messages.message(settlement.getNameFor(player)) + ", " + Messages.message(StringTemplate.template(settlement.isCapital() ? "indianCapital" : "indianSettlement") .addStringTemplate("%nation%", indian.getNationName())); String messageId = settlement.getShortAlarmLevelMessageId(player); text += " (" + Messages.message(messageId) + ")"; settlementLabel.setText(text); add(settlementLabel); Unit missionary = settlement.getMissionary(); if (missionary != null) { String missionaryName = Messages.message(StringTemplate.template("model.unit.nationUnit") .addStringTemplate("%nation%", missionary.getOwner().getNationName()) .addStringTemplate("%unit%", missionary.getLabel())); add(new JLabel(missionaryName, canvas.getImageIcon(missionary, true), JLabel.CENTER)); } add(localizedLabel("indianSettlement.learnableSkill"), "newline"); UnitType skillType = settlement.getLearnableSkill(); if (visited) { if (skillType == null) { add(localizedLabel("indianSettlement.skillNone")); } else { add(new JLabel(Messages.message(skillType.getNameKey()), canvas.getImageIcon(skillType, true), JLabel.CENTER)); } } else { add(localizedLabel("indianSettlement.skillUnknown")); } GoodsType[] wantedGoods = settlement.getWantedGoods(); String sale; add(localizedLabel("indianSettlement.highlyWanted"), "newline"); if (!visited || wantedGoods.length == 0 || wantedGoods[0] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { sale = player.getLastSaleString(settlement, wantedGoods[0]); add(new JLabel(Messages.message(wantedGoods[0].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[0], false), JLabel.CENTER)); } add(localizedLabel("indianSettlement.otherWanted"), "newline"); if (!visited || wantedGoods.length <= 1 || wantedGoods[1] == null) { add(localizedLabel("indianSettlement.wantedGoodsUnknown")); } else { int i, n = 1; for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) n++; } sale = player.getLastSaleString(settlement, wantedGoods[1]); add(new JLabel(Messages.message(wantedGoods[1].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[1], false), JLabel.CENTER), "split " + Integer.toString(n)); for (i = 2; i < wantedGoods.length; i++) { if (wantedGoods[i] != null) { sale = player.getLastSaleString(settlement,wantedGoods[i]); add(new JLabel(Messages.message(wantedGoods[i].getNameKey()) + ((sale == null) ? "" : " " + sale), canvas.getImageIcon(wantedGoods[i], false), JLabel.CENTER)); } } } add(okButton, "newline 20, span, tag ok"); setSize(getPreferredSize()); }
diff --git a/src/ch/idsia/tools/CmdLineOptions.java b/src/ch/idsia/tools/CmdLineOptions.java index 1b2fc82..3208d3d 100644 --- a/src/ch/idsia/tools/CmdLineOptions.java +++ b/src/ch/idsia/tools/CmdLineOptions.java @@ -1,68 +1,68 @@ package ch.idsia.tools; import ch.idsia.mario.engine.GlobalOptions; import ch.idsia.ai.agents.AgentsPool; import java.util.Map; /** * Created by IntelliJ IDEA. * User: Sergey Karakovskiy * Date: Apr 25, 2009 * Time: 9:05:20 AM * Package: ch.idsia.tools */ /** * The <code>CmdLineOptions</code> class handles the commandline options received from actual * command line or through TCP interface. It sets up parameters from command line if there are any. * Defaults are used otherwise. * * @author Sergey Karakovskiy * @version 1.0, Apr 25, 2009 * * @see ch.idsia.utils.ParameterContainer * @see ch.idsia.tools.EvaluationOptions * * @since iMario1.0 */ public class CmdLineOptions extends EvaluationOptions { // TODO: SK Move default options to xml, properties, beans, whatever.. //relevant? public CmdLineOptions(String[] args) { super(); - if (args.length > 1 && !args[0].startsWith("-") /*starts with a path to agent then*/) + if (args.length > 0 && !args[0].startsWith("-") /*starts with a path to agent then*/) { this.setAgent(args[0]); String[] shiftedargs = new String[args.length - 1]; System.arraycopy(args, 1, shiftedargs, 0, args.length - 1); this.setUpOptions(shiftedargs); } else this.setUpOptions(args); if (isEcho()) { System.out.println("\nOptions have been set to:"); for (Map.Entry<String,String> el : optionsHashMap.entrySet()) System.out.println(el.getKey() + ": " + el.getValue()); } GlobalOptions.GameVeiwerContinuousUpdatesOn = isGameViewerContinuousUpdates(); } public Boolean isToolsConfigurator() { return b(getParameterValue("-tc")); } public Boolean isGameViewer() { return b(getParameterValue("-gv")); } public Boolean isGameViewerContinuousUpdates() { return b(getParameterValue("-gvc")); } public Boolean isEcho() { return b(getParameterValue("-echo")); } }
true
true
public CmdLineOptions(String[] args) { super(); if (args.length > 1 && !args[0].startsWith("-") /*starts with a path to agent then*/) { this.setAgent(args[0]); String[] shiftedargs = new String[args.length - 1]; System.arraycopy(args, 1, shiftedargs, 0, args.length - 1); this.setUpOptions(shiftedargs); } else this.setUpOptions(args); if (isEcho()) { System.out.println("\nOptions have been set to:"); for (Map.Entry<String,String> el : optionsHashMap.entrySet()) System.out.println(el.getKey() + ": " + el.getValue()); } GlobalOptions.GameVeiwerContinuousUpdatesOn = isGameViewerContinuousUpdates(); }
public CmdLineOptions(String[] args) { super(); if (args.length > 0 && !args[0].startsWith("-") /*starts with a path to agent then*/) { this.setAgent(args[0]); String[] shiftedargs = new String[args.length - 1]; System.arraycopy(args, 1, shiftedargs, 0, args.length - 1); this.setUpOptions(shiftedargs); } else this.setUpOptions(args); if (isEcho()) { System.out.println("\nOptions have been set to:"); for (Map.Entry<String,String> el : optionsHashMap.entrySet()) System.out.println(el.getKey() + ": " + el.getValue()); } GlobalOptions.GameVeiwerContinuousUpdatesOn = isGameViewerContinuousUpdates(); }
diff --git a/loci/formats/in/IPWReader.java b/loci/formats/in/IPWReader.java index a8e143035..e1c994ca5 100644 --- a/loci/formats/in/IPWReader.java +++ b/loci/formats/in/IPWReader.java @@ -1,337 +1,337 @@ // // IPWReader.java // /* LOCI Bio-Formats package for reading and converting biological file formats. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden, Chris Allan, Eric Kjellman and Brian Loranger. This program is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.formats.in; import java.io.*; import java.text.*; import java.util.*; import loci.formats.*; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; /** * IPWReader is the file format reader for Image-Pro Workspace (IPW) files. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/loci/formats/in/IPWReader.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/loci/formats/in/IPWReader.java">SVN</a></dd></dl> * * @author Melissa Linkert linkert at wisc.edu */ public class IPWReader extends FormatReader { // -- Fields -- private Vector imageFiles; private POITools poi; // -- Constructor -- /** Constructs a new IPW reader. */ public IPWReader() { super("Image-Pro Workspace", "ipw"); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(byte[]) */ public boolean isThisType(byte[] block) { // all of our samples begin with 0xd0cf11e0 return block[0] == 0xd0 && block[1] == 0xcf && block[2] == 0x11 && block[3] == 0xe0; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); RandomAccessStream stream = poi.getDocumentStream((String) imageFiles.get(0)); Hashtable[] ifds = TiffTools.getIFDs(stream); int[] bits = TiffTools.getBitsPerSample(ifds[0]); if (bits[0] <= 8) { int[] colorMap = (int[]) TiffTools.getIFDValue(ifds[0], TiffTools.COLOR_MAP); if (colorMap == null) return null; byte[][] table = new byte[3][colorMap.length / 3]; int next = 0; for (int j=0; j<table.length; j++) { for (int i=0; i<table[0].length; i++) { table[j][i] = (byte) (colorMap[next++] >> 8); } } return table; } return null; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); FormatTools.checkPlaneNumber(this, no); FormatTools.checkBufferSize(this, buf.length, w, h); RandomAccessStream stream = poi.getDocumentStream((String) imageFiles.get(no)); Hashtable[] ifds = TiffTools.getIFDs(stream); TiffTools.getSamples(ifds[0], stream, buf, x, y, w, h); stream.close(); if (core.pixelType[0] == FormatTools.UINT16 || core.pixelType[0] == FormatTools.INT16) { for (int i=0; i<buf.length; i+=2) { byte b = buf[i]; buf[i] = buf[i + 1]; buf[i + 1] = b; } } else if (core.pixelType[0] == FormatTools.UINT32 || core.pixelType[0] == FormatTools.INT32) { for (int i=0; i<buf.length; i+=4) { byte b = buf[i]; buf[i] = buf[i + 3]; buf[i + 3] = b; b = buf[i + 1]; buf[i + 1] = buf[i + 2]; buf[i + 2] = b; } } return buf; } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); if (poi != null) poi.close(); poi = null; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (debug) debug("IPWReader.initFile(" + id + ")"); currentId = id; metadata = new Hashtable(); core = new CoreMetadata(1); Arrays.fill(core.orderCertain, true); getMetadataStore().createRoot(); in = new RandomAccessStream(id); poi = new POITools(currentId); imageFiles = new Vector(); Vector fileList = poi.getDocumentList(); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); store.setImageName("", 0); for (int i=0; i<fileList.size(); i++) { String name = (String) fileList.get(i); String relativePath = name.substring(name.lastIndexOf(File.separator) + 1); if (relativePath.equals("CONTENTS")) { addMeta("Version", new String(poi.getDocumentBytes(name)).trim()); } else if (relativePath.equals("FrameRate")) { byte[] b = poi.getDocumentBytes(name, 4); addMeta("Frame Rate", new Integer(DataTools.bytesToInt(b, true))); } else if (relativePath.equals("FrameInfo")) { byte[] b = poi.getDocumentBytes(name); for (int q=0; q<b.length/2; q++) { addMeta("FrameInfo " + q, new Short(DataTools.bytesToShort(b, q*2, 2, true))); } } else if (relativePath.equals("ImageInfo")) { String description = new String(poi.getDocumentBytes(name)).trim(); addMeta("Image Description", description); String timestamp = null; // parse the description to get channels/slices/times where applicable // basically the same as in SEQReader if (description != null) { StringTokenizer tokenizer = new StringTokenizer(description, "\n"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); String label = "Timestamp"; String data; if (token.indexOf("=") != -1) { label = token.substring(0, token.indexOf("=")).trim(); data = token.substring(token.indexOf("=") + 1).trim(); } else data = token.trim(); addMeta(label, data); if (label.equals("frames")) core.sizeZ[0] = Integer.parseInt(data); else if (label.equals("slices")) { core.sizeT[0] = Integer.parseInt(data); } else if (label.equals("channels")) { core.sizeC[0] = Integer.parseInt(data); } else if (label.equals("Timestamp")) timestamp = data; } } store.setImageDescription(description, 0); if (timestamp != null) { if (timestamp.length() > 26) { timestamp = timestamp.substring(timestamp.length() - 26); } SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS aa"); Date d = fmt.parse(timestamp, new ParsePosition(0)); fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(d), 0); } else { store.setImageCreationDate(DataTools.convertDate( System.currentTimeMillis(), DataTools.UNIX), 0); } } else if (relativePath.equals("ImageTIFF")) { // pixel data String idx = "0"; if (!name.substring(0, name.lastIndexOf(File.separator)).equals("Root Entry")) { idx = name.substring(21, name.indexOf(File.separator, 22)); } int n = Integer.parseInt(idx); if (n < imageFiles.size()) imageFiles.setElementAt(name, n); else { int diff = n - imageFiles.size(); for (int q=0; q<diff; q++) { imageFiles.add(""); } imageFiles.add(name); } core.imageCount[0]++; } } status("Populating metadata"); RandomAccessStream stream = poi.getDocumentStream((String) imageFiles.get(0)); Hashtable[] ifds = TiffTools.getIFDs(stream); stream.close(); core.rgb[0] = (TiffTools.getIFDIntValue(ifds[0], TiffTools.SAMPLES_PER_PIXEL, false, 1) > 1); if (!core.rgb[0]) { core.indexed[0] = TiffTools.getIFDIntValue(ifds[0], TiffTools.PHOTOMETRIC_INTERPRETATION, false, 1) == TiffTools.RGB_PALETTE; } if (core.indexed[0]) { core.sizeC[0] = 1; core.rgb[0] = false; } core.littleEndian[0] = TiffTools.isLittleEndian(ifds[0]); // default values addMeta("slices", "1"); addMeta("channels", "1"); addMeta("frames", new Integer(getImageCount())); Hashtable h = ifds[0]; core.sizeX[0] = TiffTools.getIFDIntValue(h, TiffTools.IMAGE_WIDTH); core.sizeY[0] = TiffTools.getIFDIntValue(h, TiffTools.IMAGE_LENGTH); core.currentOrder[0] = core.rgb[0] ? "XYCTZ" : "XYTCZ"; if (core.sizeZ[0] == 0) core.sizeZ[0] = 1; if (core.sizeC[0] == 0) core.sizeC[0] = 1; if (core.sizeT[0] == 0) core.sizeT[0] = 1; - if (core.sizeZ[0] * getRGBChannelCount() * core.sizeT[0] < - core.imageCount[0]) + if (core.sizeZ[0] * core.sizeC[0] * core.sizeT[0] == 1 && + core.imageCount[0] != 1) { core.sizeZ[0] = core.imageCount[0]; } if (core.rgb[0]) core.sizeC[0] *= 3; int bitsPerSample = TiffTools.getIFDIntValue(ifds[0], TiffTools.BITS_PER_SAMPLE); int bitFormat = TiffTools.getIFDIntValue(ifds[0], TiffTools.SAMPLE_FORMAT); while (bitsPerSample % 8 != 0) bitsPerSample++; if (bitsPerSample == 24 || bitsPerSample == 48) bitsPerSample /= 3; core.pixelType[0] = FormatTools.UINT8; if (bitFormat == 3) core.pixelType[0] = FormatTools.FLOAT; else if (bitFormat == 2) { switch (bitsPerSample) { case 8: core.pixelType[0] = FormatTools.INT8; break; case 16: core.pixelType[0] = FormatTools.INT16; break; case 32: core.pixelType[0] = FormatTools.INT32; break; } } else { switch (bitsPerSample) { case 8: core.pixelType[0] = FormatTools.UINT8; break; case 16: core.pixelType[0] = FormatTools.UINT16; break; case 32: core.pixelType[0] = FormatTools.UINT32; break; } } MetadataTools.populatePixels(store, this); } }
true
true
protected void initFile(String id) throws FormatException, IOException { if (debug) debug("IPWReader.initFile(" + id + ")"); currentId = id; metadata = new Hashtable(); core = new CoreMetadata(1); Arrays.fill(core.orderCertain, true); getMetadataStore().createRoot(); in = new RandomAccessStream(id); poi = new POITools(currentId); imageFiles = new Vector(); Vector fileList = poi.getDocumentList(); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); store.setImageName("", 0); for (int i=0; i<fileList.size(); i++) { String name = (String) fileList.get(i); String relativePath = name.substring(name.lastIndexOf(File.separator) + 1); if (relativePath.equals("CONTENTS")) { addMeta("Version", new String(poi.getDocumentBytes(name)).trim()); } else if (relativePath.equals("FrameRate")) { byte[] b = poi.getDocumentBytes(name, 4); addMeta("Frame Rate", new Integer(DataTools.bytesToInt(b, true))); } else if (relativePath.equals("FrameInfo")) { byte[] b = poi.getDocumentBytes(name); for (int q=0; q<b.length/2; q++) { addMeta("FrameInfo " + q, new Short(DataTools.bytesToShort(b, q*2, 2, true))); } } else if (relativePath.equals("ImageInfo")) { String description = new String(poi.getDocumentBytes(name)).trim(); addMeta("Image Description", description); String timestamp = null; // parse the description to get channels/slices/times where applicable // basically the same as in SEQReader if (description != null) { StringTokenizer tokenizer = new StringTokenizer(description, "\n"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); String label = "Timestamp"; String data; if (token.indexOf("=") != -1) { label = token.substring(0, token.indexOf("=")).trim(); data = token.substring(token.indexOf("=") + 1).trim(); } else data = token.trim(); addMeta(label, data); if (label.equals("frames")) core.sizeZ[0] = Integer.parseInt(data); else if (label.equals("slices")) { core.sizeT[0] = Integer.parseInt(data); } else if (label.equals("channels")) { core.sizeC[0] = Integer.parseInt(data); } else if (label.equals("Timestamp")) timestamp = data; } } store.setImageDescription(description, 0); if (timestamp != null) { if (timestamp.length() > 26) { timestamp = timestamp.substring(timestamp.length() - 26); } SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS aa"); Date d = fmt.parse(timestamp, new ParsePosition(0)); fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(d), 0); } else { store.setImageCreationDate(DataTools.convertDate( System.currentTimeMillis(), DataTools.UNIX), 0); } } else if (relativePath.equals("ImageTIFF")) { // pixel data String idx = "0"; if (!name.substring(0, name.lastIndexOf(File.separator)).equals("Root Entry")) { idx = name.substring(21, name.indexOf(File.separator, 22)); } int n = Integer.parseInt(idx); if (n < imageFiles.size()) imageFiles.setElementAt(name, n); else { int diff = n - imageFiles.size(); for (int q=0; q<diff; q++) { imageFiles.add(""); } imageFiles.add(name); } core.imageCount[0]++; } } status("Populating metadata"); RandomAccessStream stream = poi.getDocumentStream((String) imageFiles.get(0)); Hashtable[] ifds = TiffTools.getIFDs(stream); stream.close(); core.rgb[0] = (TiffTools.getIFDIntValue(ifds[0], TiffTools.SAMPLES_PER_PIXEL, false, 1) > 1); if (!core.rgb[0]) { core.indexed[0] = TiffTools.getIFDIntValue(ifds[0], TiffTools.PHOTOMETRIC_INTERPRETATION, false, 1) == TiffTools.RGB_PALETTE; } if (core.indexed[0]) { core.sizeC[0] = 1; core.rgb[0] = false; } core.littleEndian[0] = TiffTools.isLittleEndian(ifds[0]); // default values addMeta("slices", "1"); addMeta("channels", "1"); addMeta("frames", new Integer(getImageCount())); Hashtable h = ifds[0]; core.sizeX[0] = TiffTools.getIFDIntValue(h, TiffTools.IMAGE_WIDTH); core.sizeY[0] = TiffTools.getIFDIntValue(h, TiffTools.IMAGE_LENGTH); core.currentOrder[0] = core.rgb[0] ? "XYCTZ" : "XYTCZ"; if (core.sizeZ[0] == 0) core.sizeZ[0] = 1; if (core.sizeC[0] == 0) core.sizeC[0] = 1; if (core.sizeT[0] == 0) core.sizeT[0] = 1; if (core.sizeZ[0] * getRGBChannelCount() * core.sizeT[0] < core.imageCount[0]) { core.sizeZ[0] = core.imageCount[0]; } if (core.rgb[0]) core.sizeC[0] *= 3; int bitsPerSample = TiffTools.getIFDIntValue(ifds[0], TiffTools.BITS_PER_SAMPLE); int bitFormat = TiffTools.getIFDIntValue(ifds[0], TiffTools.SAMPLE_FORMAT); while (bitsPerSample % 8 != 0) bitsPerSample++; if (bitsPerSample == 24 || bitsPerSample == 48) bitsPerSample /= 3; core.pixelType[0] = FormatTools.UINT8; if (bitFormat == 3) core.pixelType[0] = FormatTools.FLOAT; else if (bitFormat == 2) { switch (bitsPerSample) { case 8: core.pixelType[0] = FormatTools.INT8; break; case 16: core.pixelType[0] = FormatTools.INT16; break; case 32: core.pixelType[0] = FormatTools.INT32; break; } } else { switch (bitsPerSample) { case 8: core.pixelType[0] = FormatTools.UINT8; break; case 16: core.pixelType[0] = FormatTools.UINT16; break; case 32: core.pixelType[0] = FormatTools.UINT32; break; } } MetadataTools.populatePixels(store, this); }
protected void initFile(String id) throws FormatException, IOException { if (debug) debug("IPWReader.initFile(" + id + ")"); currentId = id; metadata = new Hashtable(); core = new CoreMetadata(1); Arrays.fill(core.orderCertain, true); getMetadataStore().createRoot(); in = new RandomAccessStream(id); poi = new POITools(currentId); imageFiles = new Vector(); Vector fileList = poi.getDocumentList(); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); store.setImageName("", 0); for (int i=0; i<fileList.size(); i++) { String name = (String) fileList.get(i); String relativePath = name.substring(name.lastIndexOf(File.separator) + 1); if (relativePath.equals("CONTENTS")) { addMeta("Version", new String(poi.getDocumentBytes(name)).trim()); } else if (relativePath.equals("FrameRate")) { byte[] b = poi.getDocumentBytes(name, 4); addMeta("Frame Rate", new Integer(DataTools.bytesToInt(b, true))); } else if (relativePath.equals("FrameInfo")) { byte[] b = poi.getDocumentBytes(name); for (int q=0; q<b.length/2; q++) { addMeta("FrameInfo " + q, new Short(DataTools.bytesToShort(b, q*2, 2, true))); } } else if (relativePath.equals("ImageInfo")) { String description = new String(poi.getDocumentBytes(name)).trim(); addMeta("Image Description", description); String timestamp = null; // parse the description to get channels/slices/times where applicable // basically the same as in SEQReader if (description != null) { StringTokenizer tokenizer = new StringTokenizer(description, "\n"); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); String label = "Timestamp"; String data; if (token.indexOf("=") != -1) { label = token.substring(0, token.indexOf("=")).trim(); data = token.substring(token.indexOf("=") + 1).trim(); } else data = token.trim(); addMeta(label, data); if (label.equals("frames")) core.sizeZ[0] = Integer.parseInt(data); else if (label.equals("slices")) { core.sizeT[0] = Integer.parseInt(data); } else if (label.equals("channels")) { core.sizeC[0] = Integer.parseInt(data); } else if (label.equals("Timestamp")) timestamp = data; } } store.setImageDescription(description, 0); if (timestamp != null) { if (timestamp.length() > 26) { timestamp = timestamp.substring(timestamp.length() - 26); } SimpleDateFormat fmt = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS aa"); Date d = fmt.parse(timestamp, new ParsePosition(0)); fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); store.setImageCreationDate(fmt.format(d), 0); } else { store.setImageCreationDate(DataTools.convertDate( System.currentTimeMillis(), DataTools.UNIX), 0); } } else if (relativePath.equals("ImageTIFF")) { // pixel data String idx = "0"; if (!name.substring(0, name.lastIndexOf(File.separator)).equals("Root Entry")) { idx = name.substring(21, name.indexOf(File.separator, 22)); } int n = Integer.parseInt(idx); if (n < imageFiles.size()) imageFiles.setElementAt(name, n); else { int diff = n - imageFiles.size(); for (int q=0; q<diff; q++) { imageFiles.add(""); } imageFiles.add(name); } core.imageCount[0]++; } } status("Populating metadata"); RandomAccessStream stream = poi.getDocumentStream((String) imageFiles.get(0)); Hashtable[] ifds = TiffTools.getIFDs(stream); stream.close(); core.rgb[0] = (TiffTools.getIFDIntValue(ifds[0], TiffTools.SAMPLES_PER_PIXEL, false, 1) > 1); if (!core.rgb[0]) { core.indexed[0] = TiffTools.getIFDIntValue(ifds[0], TiffTools.PHOTOMETRIC_INTERPRETATION, false, 1) == TiffTools.RGB_PALETTE; } if (core.indexed[0]) { core.sizeC[0] = 1; core.rgb[0] = false; } core.littleEndian[0] = TiffTools.isLittleEndian(ifds[0]); // default values addMeta("slices", "1"); addMeta("channels", "1"); addMeta("frames", new Integer(getImageCount())); Hashtable h = ifds[0]; core.sizeX[0] = TiffTools.getIFDIntValue(h, TiffTools.IMAGE_WIDTH); core.sizeY[0] = TiffTools.getIFDIntValue(h, TiffTools.IMAGE_LENGTH); core.currentOrder[0] = core.rgb[0] ? "XYCTZ" : "XYTCZ"; if (core.sizeZ[0] == 0) core.sizeZ[0] = 1; if (core.sizeC[0] == 0) core.sizeC[0] = 1; if (core.sizeT[0] == 0) core.sizeT[0] = 1; if (core.sizeZ[0] * core.sizeC[0] * core.sizeT[0] == 1 && core.imageCount[0] != 1) { core.sizeZ[0] = core.imageCount[0]; } if (core.rgb[0]) core.sizeC[0] *= 3; int bitsPerSample = TiffTools.getIFDIntValue(ifds[0], TiffTools.BITS_PER_SAMPLE); int bitFormat = TiffTools.getIFDIntValue(ifds[0], TiffTools.SAMPLE_FORMAT); while (bitsPerSample % 8 != 0) bitsPerSample++; if (bitsPerSample == 24 || bitsPerSample == 48) bitsPerSample /= 3; core.pixelType[0] = FormatTools.UINT8; if (bitFormat == 3) core.pixelType[0] = FormatTools.FLOAT; else if (bitFormat == 2) { switch (bitsPerSample) { case 8: core.pixelType[0] = FormatTools.INT8; break; case 16: core.pixelType[0] = FormatTools.INT16; break; case 32: core.pixelType[0] = FormatTools.INT32; break; } } else { switch (bitsPerSample) { case 8: core.pixelType[0] = FormatTools.UINT8; break; case 16: core.pixelType[0] = FormatTools.UINT16; break; case 32: core.pixelType[0] = FormatTools.UINT32; break; } } MetadataTools.populatePixels(store, this); }
diff --git a/src/com/dmdirc/parser/ProcessNick.java b/src/com/dmdirc/parser/ProcessNick.java index 2fc1729fe..9ba8c1b05 100644 --- a/src/com/dmdirc/parser/ProcessNick.java +++ b/src/com/dmdirc/parser/ProcessNick.java @@ -1,132 +1,133 @@ /* * Copyright (c) 2006-2008 Chris Smith, Shane Mc Cormack, Gregory Holmes * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * SVN: $Id$ */ package com.dmdirc.parser; import com.dmdirc.parser.callbacks.CallbackOnChannelNickChanged; import com.dmdirc.parser.callbacks.CallbackOnNickChanged; /** * Process a Nick change. */ public class ProcessNick extends IRCProcessor { /** * Process a Nick change. * * @param sParam Type of line to process ("NICK") * @param token IRCTokenised line to process */ @Override public void process(String sParam, String[] token) { ClientInfo iClient; ChannelClientInfo iChannelClient; String oldNickname; iClient = getClientInfo(token[0]); if (iClient != null) { oldNickname = myParser.toLowerCase(iClient.getNickname()); // Remove the client from the known clients list final boolean isSameNick = myParser.equalsIgnoreCase(oldNickname, token[token.length-1]); if (!isSameNick) { myParser.forceRemoveClient(getClientInfo(oldNickname)); } // Change the nickame iClient.setUserBits(token[token.length-1],true); // Readd the client if (!isSameNick && myParser.getClientInfo(iClient.getNickname()) != null) { - myParser.onPostErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine()), false); +// myParser.onPostErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine()), false); + myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine())); } else { if (!isSameNick) { myParser.addClient(iClient); } for (ChannelInfo iChannel : myParser.getChannels()) { // Find the user (using the old nickname) iChannelClient = iChannel.getUser(oldNickname); if (iChannelClient != null) { // Rename them. This uses the old nickname (the key in the hashtable) // and the channelClient object has access to the new nickname (by way // of the ClientInfo object we updated above) if (!isSameNick) { iChannel.renameClient(oldNickname, iChannelClient); } callChannelNickChanged(iChannel,iChannelClient,ClientInfo.parseHost(token[0])); } } callNickChanged(iClient, ClientInfo.parseHost(token[0])); } } } /** * Callback to all objects implementing the ChannelNickChanged Callback. * * @see IChannelNickChanged * @param cChannel One of the channels that the user is on * @param cChannelClient Client changing nickname * @param sOldNick Nickname before change * @return true if a method was called, false otherwise */ protected boolean callChannelNickChanged(ChannelInfo cChannel, ChannelClientInfo cChannelClient, String sOldNick) { return ((CallbackOnChannelNickChanged) getCallbackManager() .getCallbackType("OnChannelNickChanged")).call(cChannel, cChannelClient, sOldNick); } /** * Callback to all objects implementing the NickChanged Callback. * * @see INickChanged * @param cClient Client changing nickname * @param sOldNick Nickname before change * @return true if a method was called, false otherwise */ protected boolean callNickChanged(ClientInfo cClient, String sOldNick) { return ((CallbackOnNickChanged) getCallbackManager() .getCallbackType("OnNickChanged")).call(cClient, sOldNick); } /** * What does this IRCProcessor handle. * * @return String[] with the names of the tokens we handle. */ @Override public String[] handles() { String[] iHandle = new String[1]; iHandle[0] = "NICK"; return iHandle; } /** * Create a new instance of the IRCProcessor Object. * * @param parser IRCParser That owns this IRCProcessor * @param manager ProcessingManager that is in charge of this IRCProcessor */ protected ProcessNick (IRCParser parser, ProcessingManager manager) { super(parser, manager); } }
true
true
public void process(String sParam, String[] token) { ClientInfo iClient; ChannelClientInfo iChannelClient; String oldNickname; iClient = getClientInfo(token[0]); if (iClient != null) { oldNickname = myParser.toLowerCase(iClient.getNickname()); // Remove the client from the known clients list final boolean isSameNick = myParser.equalsIgnoreCase(oldNickname, token[token.length-1]); if (!isSameNick) { myParser.forceRemoveClient(getClientInfo(oldNickname)); } // Change the nickame iClient.setUserBits(token[token.length-1],true); // Readd the client if (!isSameNick && myParser.getClientInfo(iClient.getNickname()) != null) { myParser.onPostErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine()), false); } else { if (!isSameNick) { myParser.addClient(iClient); } for (ChannelInfo iChannel : myParser.getChannels()) { // Find the user (using the old nickname) iChannelClient = iChannel.getUser(oldNickname); if (iChannelClient != null) { // Rename them. This uses the old nickname (the key in the hashtable) // and the channelClient object has access to the new nickname (by way // of the ClientInfo object we updated above) if (!isSameNick) { iChannel.renameClient(oldNickname, iChannelClient); } callChannelNickChanged(iChannel,iChannelClient,ClientInfo.parseHost(token[0])); } } callNickChanged(iClient, ClientInfo.parseHost(token[0])); } } }
public void process(String sParam, String[] token) { ClientInfo iClient; ChannelClientInfo iChannelClient; String oldNickname; iClient = getClientInfo(token[0]); if (iClient != null) { oldNickname = myParser.toLowerCase(iClient.getNickname()); // Remove the client from the known clients list final boolean isSameNick = myParser.equalsIgnoreCase(oldNickname, token[token.length-1]); if (!isSameNick) { myParser.forceRemoveClient(getClientInfo(oldNickname)); } // Change the nickame iClient.setUserBits(token[token.length-1],true); // Readd the client if (!isSameNick && myParser.getClientInfo(iClient.getNickname()) != null) { // myParser.onPostErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine()), false); myParser.callErrorInfo(new ParserError(ParserError.ERROR_FATAL, "Nick change would overwrite existing client", myParser.getLastLine())); } else { if (!isSameNick) { myParser.addClient(iClient); } for (ChannelInfo iChannel : myParser.getChannels()) { // Find the user (using the old nickname) iChannelClient = iChannel.getUser(oldNickname); if (iChannelClient != null) { // Rename them. This uses the old nickname (the key in the hashtable) // and the channelClient object has access to the new nickname (by way // of the ClientInfo object we updated above) if (!isSameNick) { iChannel.renameClient(oldNickname, iChannelClient); } callChannelNickChanged(iChannel,iChannelClient,ClientInfo.parseHost(token[0])); } } callNickChanged(iClient, ClientInfo.parseHost(token[0])); } } }
diff --git a/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java b/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java index a297e774..5ab6303f 100644 --- a/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java +++ b/src/org/liberty/android/fantastischmemo/cardscreen/EditScreen.java @@ -1,662 +1,665 @@ /* Copyright (C) 2010 Haowen Ning This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.liberty.android.fantastischmemo.cardscreen; import org.liberty.android.fantastischmemo.*; import org.liberty.android.fantastischmemo.tts.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Date; import java.util.List; import android.graphics.Color; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; import android.os.Environment; import android.content.Context; import android.preference.PreferenceManager; import android.text.Html; import android.view.Gravity; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.ContextMenu; import android.view.MotionEvent; import android.view.View; import android.view.Display; import android.view.WindowManager; import android.view.LayoutInflater; import android.widget.Button; import android.widget.ImageButton; import android.os.Handler; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.EditText; import android.widget.Toast; import android.util.Log; import android.os.SystemClock; import android.net.Uri; import android.database.SQLException; import android.gesture.Gesture; import android.gesture.GestureLibraries; import android.gesture.GestureLibrary; import android.gesture.GestureOverlayView; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.gesture.Prediction; import android.gesture.GestureOverlayView.OnGesturePerformedListener; public class EditScreen extends AMActivity{ private final static String TAG = "org.liberty.android.fantastischmemo.cardscreen.EditScreen"; private AnyMemoTTS questionTTS = null; private AnyMemoTTS answerTTS = null; private boolean searchInflated = false; private final int DIALOG_LOADING_PROGRESS = 100; private final int ACTIVITY_FILTER = 10; private final int ACTIVITY_EDIT = 11; private final int ACTIVITY_CARD_TOOLBOX = 12; private final int ACTIVITY_DB_TOOLBOX = 13; private final int ACTIVITY_GOTO_PREV = 14; private final int ACTIVITY_SETTINGS = 15; private final int ACTIVITY_LIST = 16; private final int ACTIVITY_MERGE = 17; Handler mHandler; Item currentItem = null; Item savedItem = null; Item prevItem = null; String dbPath = ""; String dbName = ""; String activeFilter = ""; FlashcardDisplay flashcardDisplay; SettingManager settingManager; ControlButtons controlButtons; DatabaseUtility databaseUtility; private GestureDetector gestureDetector; ItemManager itemManager; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.memo_screen_layout); mHandler = new Handler(); Bundle extras = getIntent().getExtras(); int currentId = 1; if (extras != null) { dbPath = extras.getString("dbpath"); dbName = extras.getString("dbname"); activeFilter = extras.getString("filter"); currentId = extras.getInt("id", 1); } try{ settingManager = new SettingManager(this, dbPath, dbName); flashcardDisplay = new FlashcardDisplay(this, settingManager); controlButtons = new EditScreenButtons(this); /* databaseUtility is for global db operations */ databaseUtility = new DatabaseUtility(this, dbPath, dbName); itemManager = new ItemManager.Builder(this, dbPath, dbName) .setFilter(activeFilter) .build(); initTTS(); composeViews(); currentItem = itemManager.getItem(currentId); if(currentItem == null){ itemManager.getItem(1); } flashcardDisplay.updateView(currentItem); updateTitle(); setButtonListeners(); gestureDetector= new GestureDetector(EditScreen.this, gestureListener); flashcardDisplay.setScreenOnTouchListener(viewTouchListener); registerForContextMenu(flashcardDisplay.getView()); } catch(Exception e){ Log.e(TAG, "Error in the onCreate()", e); AMGUIUtility.displayError(this, getString(R.string.open_database_error_title), getString(R.string.open_database_error_message), e); } /* * Currently always set the result to OK * to assume there are always some changes. * This may be changed in the future to reflect the * real changes */ setResult(Activity.RESULT_OK); } @Override public void onDestroy(){ if(itemManager != null){ itemManager.close(); } if(settingManager != null){ settingManager.close(); } if(questionTTS != null){ questionTTS.shutdown(); } if(answerTTS != null){ answerTTS.shutdown(); } super.onDestroy(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data){ super.onActivityResult(requestCode, resultCode, data); if(resultCode ==Activity.RESULT_CANCELED){ return; } /* Refresh the activity according to activities */ switch(requestCode){ case ACTIVITY_EDIT: { Bundle extras = data.getExtras(); Item item = extras.getParcelable("item"); if(item != null){ currentItem = item; } restartActivity(); break; } case ACTIVITY_FILTER: { Bundle extras = data.getExtras(); activeFilter = extras.getString("filter"); restartActivity(); break; } case ACTIVITY_SETTINGS: { restartActivity(); break; } case ACTIVITY_LIST: { Bundle extras = data.getExtras(); currentItem = extras.getParcelable("item"); restartActivity(); break; } case ACTIVITY_MERGE: { restartActivity(); break; } } } @Override public boolean onCreateOptionsMenu(Menu menu){ MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.edit_screen_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menuspeakquestion: { if(questionTTS != null && currentItem != null){ questionTTS.sayText(currentItem.getQuestion()); } return true; } case R.id.menuspeakanswer: { if(answerTTS != null && currentItem != null){ answerTTS.sayText(currentItem.getAnswer()); } return true; } case R.id.editmenu_settings_id: { Intent myIntent = new Intent(this, SettingsScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_SETTINGS); return true; } case R.id.editmenu_delete_id: { deleteCurrent(); return true; } case R.id.editmenu_detail_id: { if(currentItem != null){ Intent myIntent = new Intent(this, DetailScreen.class); myIntent.putExtra("dbname", this.dbName); myIntent.putExtra("dbpath", this.dbPath); myIntent.putExtra("itemid", currentItem.getId()); startActivityForResult(myIntent, 2); } return true; } case R.id.editmenu_list_id: { Intent myIntent = new Intent(this, SettingsScreen.class); myIntent.setClass(this, ListEditScreen.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); if(currentItem != null){ myIntent.putExtra("openid", currentItem.getId()); } startActivityForResult(myIntent, ACTIVITY_LIST); return true; } case R.id.menu_edit_filter: { Intent myIntent = new Intent(this, Filter.class); myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); startActivityForResult(myIntent, ACTIVITY_FILTER); return true; } case R.id.editmenu_search_id: { createSearchOverlay(); } } return false; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){ super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.editscreen_context_menu, menu); menu.setHeaderTitle(R.string.menu_text); } @Override public boolean onContextItemSelected(MenuItem menuitem) { switch(menuitem.getItemId()) { case R.id.menu_context_copy: { if(currentItem != null){ savedItem = new Item.Builder() .setId(currentItem.getId()) .setQuestion(currentItem.getQuestion()) .setAnswer(currentItem.getAnswer()) .setCategory(currentItem.getCategory()) .build(); } return true; } case R.id.menu_context_paste: { if(savedItem != null){ itemManager.insert(savedItem, currentItem.getId()); - currentItem = savedItem; + /* Set the Id to the current one */ + currentItem = new Item.Builder(savedItem) + .setId(currentItem.getId() + 1) + .build(); flashcardDisplay.updateView(currentItem); updateTitle(); } return true; } case R.id.menu_context_swap_current: { if(currentItem != null){ databaseUtility.swapSingelItem(currentItem); } return true; } case R.id.menu_context_reset_current: { if(currentItem != null){ databaseUtility.resetCurrentLearningData(currentItem); } return true; } case R.id.menu_context_wipe: { databaseUtility.wipeLearningData(); return true; } case R.id.menu_context_swap: { databaseUtility.swapAllQA(); return true; } case R.id.menu_context_remove_dup: { databaseUtility.removeDuplicates(); return true; } case R.id.menu_context_merge_db: { Intent myIntent = new Intent(this, DatabaseMerger.class); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("dbname", dbName); startActivityForResult(myIntent, ACTIVITY_MERGE); return true; } case R.id.menu_context_shuffle: { databaseUtility.shuffleDatabase(); return true; } default: { return super.onContextItemSelected(menuitem); } } } private void initTTS(){ String audioDir = Environment.getExternalStorageDirectory().getAbsolutePath() + getString(R.string.default_audio_dir); Locale ql = settingManager.getQuestionAudioLocale(); Locale al = settingManager.getAnswerAudioLocale(); if(settingManager.getQuestionUserAudio()){ questionTTS = new AudioFileTTS(audioDir, dbName); } else if(ql != null){ questionTTS = new AnyMemoTTSPlatform(this, ql); } else{ questionTTS = null; } if(settingManager.getAnswerUserAudio()){ answerTTS = new AudioFileTTS(audioDir, dbName); } else if(al != null){ answerTTS = new AnyMemoTTSPlatform(this, al); } else{ answerTTS = null; } } @Override public void restartActivity(){ Intent myIntent = new Intent(this, EditScreen.class); if(currentItem != null){ myIntent.putExtra("id", currentItem.getId()); } myIntent.putExtra("dbname", dbName); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("filter", activeFilter); finish(); startActivity(myIntent); } private void composeViews(){ LinearLayout memoRoot = (LinearLayout)findViewById(R.id.memo_screen_root); LinearLayout flashcardDisplayView = (LinearLayout)flashcardDisplay.getView(); LinearLayout controlButtonsView = (LinearLayout)controlButtons.getView(); /* This li is make the background of buttons the same as answer */ LinearLayout li = new LinearLayout(this); li.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.FILL_PARENT)); List<Integer> colors = settingManager.getColors(); if(colors != null){ li.setBackgroundColor(settingManager.getColors().get(3)); } /* * -1: Match parent -2: Wrap content * This is necessary or the view will not be * stetched */ memoRoot.addView(flashcardDisplayView, -1, -1); li.addView(controlButtonsView, -1, -2); memoRoot.addView(li, -1, -2); flashcardDisplayView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1.0f)); } void setButtonListeners(){ Map<String, Button> bm = controlButtons.getButtons(); Button newButton = bm.get("new"); Button editButton = bm.get("edit"); Button prevButton = bm.get("prev"); Button nextButton = bm.get("next"); newButton.setOnClickListener(newButtonListener); editButton.setOnClickListener(editButtonListener); prevButton.setOnClickListener(prevButtonListener); nextButton.setOnClickListener(nextButtonListener); } private View.OnClickListener newButtonListener = new View.OnClickListener(){ public void onClick(View v){ Intent myIntent = new Intent(EditScreen.this, CardEditor.class); myIntent.putExtra("item", currentItem); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("dbname", dbName); myIntent.putExtra("new", true); startActivityForResult(myIntent, ACTIVITY_EDIT); } }; private View.OnClickListener editButtonListener = new View.OnClickListener(){ public void onClick(View v){ Intent myIntent = new Intent(EditScreen.this, CardEditor.class); myIntent.putExtra("item", currentItem); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("dbname", dbName); myIntent.putExtra("new", false); startActivityForResult(myIntent, ACTIVITY_EDIT); } }; private void updateTitle(){ if(currentItem != null){ int total = itemManager.getStatInfo()[0]; String titleString = getString(R.string.stat_total) + total + " " + getString(R.string.memo_current_id) + " " + currentItem.getId(); if(currentItem != null && currentItem.getCategory() != null){ titleString += " " + currentItem.getCategory(); } setTitle(titleString); } } private void gotoNext(){ currentItem = itemManager.getNextItem(currentItem); flashcardDisplay.updateView(currentItem); updateTitle(); } private void deleteCurrent(){ if(currentItem != null){ new AlertDialog.Builder(EditScreen.this) .setTitle(getString(R.string.detail_delete)) .setMessage(getString(R.string.delete_warning)) .setPositiveButton(getString(R.string.yes_text), new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { currentItem = itemManager.deleteItem(currentItem); restartActivity(); } }) .setNegativeButton(getString(R.string.no_text), null) .create() .show(); } } private void gotoPrev(){ currentItem = itemManager.getPreviousItem(currentItem); flashcardDisplay.updateView(currentItem); updateTitle(); } private void createSearchOverlay(){ if(searchInflated == false){ LinearLayout root = (LinearLayout)findViewById(R.id.memo_screen_root); LayoutInflater.from(this).inflate(R.layout.search_overlay, root); ImageButton close = (ImageButton)findViewById(R.id.search_close_btn); close.setOnClickListener(closeSearchButtonListener); ImageButton prev = (ImageButton)findViewById(R.id.search_previous_btn); prev.setOnClickListener(searchPrevButtonListener); ImageButton next = (ImageButton)findViewById(R.id.search_next_btn); next.setOnClickListener(searchNextButtonListener); EditText editEntry = (EditText)findViewById(R.id.search_entry); editEntry.requestFocus(); searchInflated = true; } else{ LinearLayout layout = (LinearLayout)findViewById(R.id.search_root); layout.setVisibility(View.VISIBLE); } } private void dismissSearchOverlay(){ if(searchInflated == true){ LinearLayout layout = (LinearLayout)findViewById(R.id.search_root); layout.setVisibility(View.GONE); } } private View.OnClickListener prevButtonListener = new View.OnClickListener(){ public void onClick(View v){ gotoPrev(); } }; private View.OnClickListener nextButtonListener = new View.OnClickListener(){ public void onClick(View v){ gotoNext(); } }; private View.OnClickListener closeSearchButtonListener = new View.OnClickListener(){ public void onClick(View v){ dismissSearchOverlay(); } }; private View.OnClickListener searchNextButtonListener = new View.OnClickListener(){ public void onClick(View v){ EditText editEntry = (EditText)findViewById(R.id.search_entry); String text = editEntry.getText().toString(); Item item = itemManager.search(text, true, currentItem); if(item != null){ currentItem = item; flashcardDisplay.updateView(currentItem); updateTitle(); } } }; private View.OnClickListener searchPrevButtonListener = new View.OnClickListener(){ public void onClick(View v){ EditText editEntry = (EditText)findViewById(R.id.search_entry); String text = editEntry.getText().toString(); Item item = itemManager.search(text, false, currentItem); if(item != null){ currentItem = item; flashcardDisplay.updateView(currentItem); updateTitle(); } } }; private View.OnTouchListener viewTouchListener = new View.OnTouchListener(){ @Override public boolean onTouch(View v, MotionEvent event){ return gestureDetector.onTouchEvent(event); } }; private GestureDetector.OnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener(){ private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; @Override public boolean onDown(MotionEvent e){ /* Trick: Prevent the menu to popup twice */ return true; } @Override public void onLongPress(MotionEvent e){ closeContextMenu(); EditScreen.this.openContextMenu(flashcardDisplay.getView()); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) return false; if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { /* Swipe Right to Left event */ gotoNext(); } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { /* Swipe Left to Right event */ gotoPrev(); } } catch (Exception e) { Log.e(TAG, "Error handling gesture left/right event", e); } return false; } }; }
true
true
public boolean onContextItemSelected(MenuItem menuitem) { switch(menuitem.getItemId()) { case R.id.menu_context_copy: { if(currentItem != null){ savedItem = new Item.Builder() .setId(currentItem.getId()) .setQuestion(currentItem.getQuestion()) .setAnswer(currentItem.getAnswer()) .setCategory(currentItem.getCategory()) .build(); } return true; } case R.id.menu_context_paste: { if(savedItem != null){ itemManager.insert(savedItem, currentItem.getId()); currentItem = savedItem; flashcardDisplay.updateView(currentItem); updateTitle(); } return true; } case R.id.menu_context_swap_current: { if(currentItem != null){ databaseUtility.swapSingelItem(currentItem); } return true; } case R.id.menu_context_reset_current: { if(currentItem != null){ databaseUtility.resetCurrentLearningData(currentItem); } return true; } case R.id.menu_context_wipe: { databaseUtility.wipeLearningData(); return true; } case R.id.menu_context_swap: { databaseUtility.swapAllQA(); return true; } case R.id.menu_context_remove_dup: { databaseUtility.removeDuplicates(); return true; } case R.id.menu_context_merge_db: { Intent myIntent = new Intent(this, DatabaseMerger.class); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("dbname", dbName); startActivityForResult(myIntent, ACTIVITY_MERGE); return true; } case R.id.menu_context_shuffle: { databaseUtility.shuffleDatabase(); return true; } default: { return super.onContextItemSelected(menuitem); } } }
public boolean onContextItemSelected(MenuItem menuitem) { switch(menuitem.getItemId()) { case R.id.menu_context_copy: { if(currentItem != null){ savedItem = new Item.Builder() .setId(currentItem.getId()) .setQuestion(currentItem.getQuestion()) .setAnswer(currentItem.getAnswer()) .setCategory(currentItem.getCategory()) .build(); } return true; } case R.id.menu_context_paste: { if(savedItem != null){ itemManager.insert(savedItem, currentItem.getId()); /* Set the Id to the current one */ currentItem = new Item.Builder(savedItem) .setId(currentItem.getId() + 1) .build(); flashcardDisplay.updateView(currentItem); updateTitle(); } return true; } case R.id.menu_context_swap_current: { if(currentItem != null){ databaseUtility.swapSingelItem(currentItem); } return true; } case R.id.menu_context_reset_current: { if(currentItem != null){ databaseUtility.resetCurrentLearningData(currentItem); } return true; } case R.id.menu_context_wipe: { databaseUtility.wipeLearningData(); return true; } case R.id.menu_context_swap: { databaseUtility.swapAllQA(); return true; } case R.id.menu_context_remove_dup: { databaseUtility.removeDuplicates(); return true; } case R.id.menu_context_merge_db: { Intent myIntent = new Intent(this, DatabaseMerger.class); myIntent.putExtra("dbpath", dbPath); myIntent.putExtra("dbname", dbName); startActivityForResult(myIntent, ACTIVITY_MERGE); return true; } case R.id.menu_context_shuffle: { databaseUtility.shuffleDatabase(); return true; } default: { return super.onContextItemSelected(menuitem); } } }
diff --git a/bin/jku/se/tetris/coco/Parser.java b/bin/jku/se/tetris/coco/Parser.java index db44e8a..4418be4 100644 --- a/bin/jku/se/tetris/coco/Parser.java +++ b/bin/jku/se/tetris/coco/Parser.java @@ -1,362 +1,362 @@ package bin.jku.se.tetris.coco; public class Parser { public static final int _EOF = 0; public static final int _integer = 1; public static final int _float = 2; public static final int _word = 3; public static final int maxT = 13; static final boolean T = true; static final boolean x = false; static final int minErrDist = 2; public Token t; // last recognized token public Token la; // lookahead token int errDist = minErrDist; public Scanner scanner; public Errors errors; public Parser(Scanner scanner) { this.scanner = scanner; errors = new Errors(); } void SynErr (int n) { if (errDist >= minErrDist) errors.SynErr(la.line, la.col, n); errDist = 0; } public void SemErr (String msg) { if (errDist >= minErrDist) errors.SemErr(t.line, t.col, msg); errDist = 0; } void Get () { for (;;) { t = la; la = scanner.Scan(); if (la.kind <= maxT) { ++errDist; break; } la = t; } } void Expect (int n) { if (la.kind==n) Get(); else { SynErr(n); } } boolean StartOf (int s) { return set[s][la.kind]; } void ExpectWeak (int n, int follow) { if (la.kind == n) Get(); else { SynErr(n); while (!StartOf(follow)) Get(); } } boolean WeakSeparator (int n, int syFol, int repFol) { int kind = la.kind; if (kind == n) { Get(); return true; } else if (StartOf(repFol)) return false; else { SynErr(n); while (!(set[syFol][kind] || set[repFol][kind] || set[0][kind])) { Get(); kind = la.kind; } return StartOf(syFol); } } void TetrisStatistics() { int gameCount = 0, sumScore = 0, maxScore = 0, pScore = 0, fileErrors = 0; boolean dateValid = false, timeValid = false; String bestPlayer = "", pName = "Max Mustermann"; Expect(4); dateValid = Date(); timeValid = Time(); while (la.kind == 5) { String entry; entry = Entry(); gameCount++; // Java does not support multiple return values -> use concatenated string as workaround if (entry != null) { int delPos = entry.indexOf("#"); int score = Integer.parseInt(entry.substring(delPos + 1)); String player = entry.substring(0, delPos); // Sum Score sumScore += score; // Best Player if (score > maxScore) { maxScore = score; bestPlayer = player; } // Highest Score of specified player if (player.equals(pName)) { if (score > pScore) { pScore = score; } } } else { fileErrors++; } } if (!dateValid || !timeValid) { - System.out.println("-- aborted because the header is invalid"); + System.out.println("-- aborted because the file header is invalid"); } else if (fileErrors == 0) { System.out.println("Tetris Statistics"); System.out.println(); System.out.println("Games Played:\t" + gameCount); System.out.println("Average Score:\t" + (float)sumScore / gameCount); System.out.println("Best Player:\t" + bestPlayer); System.out.println("---"); System.out.println("Highest Score of '" + pName + "': " + pScore); System.out.println(); } else { System.out.println("-- aborted because " + fileErrors + " entr" + (fileErrors == 1 ? "y is" : "ies are") + " invalid"); } } boolean Date() { boolean valid; int day, month, year = 0; day = Day(); Expect(6); month = Month(); Expect(6); year = Year(); valid = day >= 1 && day <= 31; valid = valid && month >= 1 && month <= 12; valid = valid && year >= 1970; return valid; } boolean Time() { boolean valid; int hour, minute, second = 0; hour = Hour(); Expect(8); minute = Minute(); Expect(8); second = Second(); valid = hour >= 0 && hour < 24; valid = valid && minute >= 0 && minute < 60; valid = valid && second >= 0 && second < 60; return valid; } String Entry() { String entry; String name; int score = 0; boolean validDate=false; boolean validTime = false; name = Name(); Mail(); validDate = Date(); validTime = Time(); score = Score(); if (la.kind == 5) { Comment(); } Platform(); if (validDate && validTime) { entry = name + "#" + score; } else { entry = null; } return entry; } String Name() { String name; Expect(5); Expect(3); name = t.val; while (la.kind == 3) { Get(); name += " " + t.val; } Expect(5); return name; } void Mail() { Expect(3); while (la.kind == 6) { Get(); Expect(3); } Expect(7); Expect(3); Expect(6); Expect(3); } int Score() { int score; Expect(1); score = Integer.parseInt(t.val); return score; } void Comment() { Expect(5); while (la.kind == 3) { Get(); } Expect(5); } void Platform() { if (la.kind == 9) { Get(); } else if (la.kind == 10) { Get(); } else if (la.kind == 11) { Get(); } else if (la.kind == 12) { Get(); } else SynErr(14); } int Day() { int day; Expect(1); day = Integer.parseInt(t.val); return day; } int Month() { int month; Expect(1); month = Integer.parseInt(t.val); return month; } int Year() { int year; Expect(1); year = Integer.parseInt(t.val); return year; } int Hour() { int hour; Expect(1); hour = Integer.parseInt(t.val); return hour; } int Minute() { int minute; Expect(1); minute = Integer.parseInt(t.val); return minute; } int Second() { int second; Expect(1); second = Integer.parseInt(t.val); return second; } public void Parse() { la = new Token(); la.val = ""; Get(); TetrisStatistics(); Expect(0); } private static final boolean[][] set = { {T,x,x,x, x,x,x,x, x,x,x,x, x,x,x} }; } // end Parser class Errors { public int count = 0; // number of errors detected public java.io.PrintStream errorStream = System.out; // error messages go to this stream public String errMsgFormat = "-- line {0} col {1}: {2}"; // 0=line, 1=column, 2=text protected void printMsg(int line, int column, String msg) { StringBuffer b = new StringBuffer(errMsgFormat); int pos = b.indexOf("{0}"); if (pos >= 0) { b.delete(pos, pos+3); b.insert(pos, line); } pos = b.indexOf("{1}"); if (pos >= 0) { b.delete(pos, pos+3); b.insert(pos, column); } pos = b.indexOf("{2}"); if (pos >= 0) b.replace(pos, pos+3, msg); errorStream.println(b.toString()); } public void SynErr (int line, int col, int n) { String s; switch (n) { case 0: s = "EOF expected"; break; case 1: s = "integer expected"; break; case 2: s = "float expected"; break; case 3: s = "word expected"; break; case 4: s = "\"TetrisStatistics\" expected"; break; case 5: s = "\"#\" expected"; break; case 6: s = "\".\" expected"; break; case 7: s = "\"@\" expected"; break; case 8: s = "\":\" expected"; break; case 9: s = "\"PC\" expected"; break; case 10: s = "\"Android\" expected"; break; case 11: s = "\"iPhone\" expected"; break; case 12: s = "\"Playstation\" expected"; break; case 13: s = "??? expected"; break; case 14: s = "invalid Platform"; break; default: s = "error " + n; break; } printMsg(line, col, s); count++; } public void SemErr (int line, int col, String s) { printMsg(line, col, s); count++; } public void SemErr (String s) { errorStream.println(s); count++; } public void Warning (int line, int col, String s) { printMsg(line, col, s); } public void Warning (String s) { errorStream.println(s); } } // Errors class FatalError extends RuntimeException { public static final long serialVersionUID = 1L; public FatalError(String s) { super(s); } }
true
true
void TetrisStatistics() { int gameCount = 0, sumScore = 0, maxScore = 0, pScore = 0, fileErrors = 0; boolean dateValid = false, timeValid = false; String bestPlayer = "", pName = "Max Mustermann"; Expect(4); dateValid = Date(); timeValid = Time(); while (la.kind == 5) { String entry; entry = Entry(); gameCount++; // Java does not support multiple return values -> use concatenated string as workaround if (entry != null) { int delPos = entry.indexOf("#"); int score = Integer.parseInt(entry.substring(delPos + 1)); String player = entry.substring(0, delPos); // Sum Score sumScore += score; // Best Player if (score > maxScore) { maxScore = score; bestPlayer = player; } // Highest Score of specified player if (player.equals(pName)) { if (score > pScore) { pScore = score; } } } else { fileErrors++; } } if (!dateValid || !timeValid) { System.out.println("-- aborted because the header is invalid"); } else if (fileErrors == 0) { System.out.println("Tetris Statistics"); System.out.println(); System.out.println("Games Played:\t" + gameCount); System.out.println("Average Score:\t" + (float)sumScore / gameCount); System.out.println("Best Player:\t" + bestPlayer); System.out.println("---"); System.out.println("Highest Score of '" + pName + "': " + pScore); System.out.println(); } else { System.out.println("-- aborted because " + fileErrors + " entr" + (fileErrors == 1 ? "y is" : "ies are") + " invalid"); } }
void TetrisStatistics() { int gameCount = 0, sumScore = 0, maxScore = 0, pScore = 0, fileErrors = 0; boolean dateValid = false, timeValid = false; String bestPlayer = "", pName = "Max Mustermann"; Expect(4); dateValid = Date(); timeValid = Time(); while (la.kind == 5) { String entry; entry = Entry(); gameCount++; // Java does not support multiple return values -> use concatenated string as workaround if (entry != null) { int delPos = entry.indexOf("#"); int score = Integer.parseInt(entry.substring(delPos + 1)); String player = entry.substring(0, delPos); // Sum Score sumScore += score; // Best Player if (score > maxScore) { maxScore = score; bestPlayer = player; } // Highest Score of specified player if (player.equals(pName)) { if (score > pScore) { pScore = score; } } } else { fileErrors++; } } if (!dateValid || !timeValid) { System.out.println("-- aborted because the file header is invalid"); } else if (fileErrors == 0) { System.out.println("Tetris Statistics"); System.out.println(); System.out.println("Games Played:\t" + gameCount); System.out.println("Average Score:\t" + (float)sumScore / gameCount); System.out.println("Best Player:\t" + bestPlayer); System.out.println("---"); System.out.println("Highest Score of '" + pName + "': " + pScore); System.out.println(); } else { System.out.println("-- aborted because " + fileErrors + " entr" + (fileErrors == 1 ? "y is" : "ies are") + " invalid"); } }
diff --git a/components/loci-plugins/src/loci/plugins/importer/Importer.java b/components/loci-plugins/src/loci/plugins/importer/Importer.java index d9f68ce70..0c4496f7c 100644 --- a/components/loci-plugins/src/loci/plugins/importer/Importer.java +++ b/components/loci-plugins/src/loci/plugins/importer/Importer.java @@ -1,1102 +1,1102 @@ // // Importer.java // /* LOCI Plugins for ImageJ: a collection of ImageJ plugins including the Bio-Formats Importer, Bio-Formats Exporter, Bio-Formats Macro Extensions, Data Browser, Stack Colorizer and Stack Slicer. Copyright (C) 2005-@year@ Melissa Linkert, Curtis Rueden and Christopher Peterson. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.plugins.importer; import ij.*; import ij.io.FileInfo; import ij.plugin.filter.PlugInFilterRunner; import ij.process.*; import java.awt.Rectangle; import java.awt.image.IndexColorModel; import java.io.*; import java.util.*; import loci.common.*; import loci.formats.*; import loci.formats.gui.XMLWindow; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataRetrieve; import loci.plugins.Colorizer; import loci.plugins.Updater; import loci.plugins.util.*; /** * Core logic for the Bio-Formats Importer ImageJ plugin. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="https://skyking.microscopy.wisc.edu/trac/java/browser/trunk/components/loci-plugins/src/loci/plugins/importer/Importer.java">Trac</a>, * <a href="https://skyking.microscopy.wisc.edu/svn/java/trunk/components/loci-plugins/src/loci/plugins/importer/Importer.java">SVN</a></dd></dl> * * @author Curtis Rueden ctrueden at wisc.edu * @author Melissa Linkert linkert at wisc.edu */ public class Importer { // -- Fields -- /** * A handle to the plugin wrapper, for toggling * the canceled and success flags. */ private LociImporter plugin; private Vector imps = new Vector(); private String stackOrder = null; private IndexColorModel[] colorModels; // -- Constructor -- public Importer(LociImporter plugin) { this.plugin = plugin; } // -- Importer API methods -- /** Executes the plugin. */ public void run(String arg) { // -- Step 0: parse core options -- debug("parse core options"); ImporterOptions options = new ImporterOptions(); options.loadPreferences(); options.parseArg(arg); // -- Step 1: check if new version is available -- if (options.doUpgradeCheck()) { debug("check if new version is available"); IJ.showStatus("Checking for new version..."); if (Updater.newVersionAvailable()) { boolean doUpgrade = IJ.showMessageWithCancel("", "A new stable version of Bio-Formats is available.\n" + "Click 'OK' to upgrade."); if (doUpgrade) { Updater.install(Updater.STABLE_BUILD); } } } else debug("skipping new version check"); // -- Step 2: construct reader and check id -- debug("construct reader and check id"); int status = options.promptLocation(); if (!statusOk(status)) return; status = options.promptId(); if (!statusOk(status)) return; String id = options.getId(); boolean quiet = options.isQuiet(); Location idLoc = options.getIdLocation(); String idName = options.getIdName(); String idType = options.getIdType(); IFormatReader r = null; if (options.isLocal() || options.isHTTP()) { IJ.showStatus("Identifying " + idName); ImageReader reader = Util.makeImageReader(); try { r = reader.getReader(id); } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was an error reading the file."); return; } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was a I/O problem reading the file."); return; } } else if (options.isOMERO()) { // NB: avoid dependencies on optional loci.ome.io package try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.ome.io.OMEROReader"); r = (IFormatReader) ru.exec("new OMEROReader()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the OMERO I/O engine"); return; } } else if (options.isOME()) { // NB: avoid dependencies on optional loci.ome.io package try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.ome.io.OMEReader"); r = (IFormatReader) ru.exec("new OMEReader()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the OME I/O engine"); return; } } else { reportException(null, options.isQuiet(), "Sorry, there has been an internal error: unknown data source"); } IMetadata omexmlMeta = MetadataTools.createOMEXMLMetadata(); r.setMetadataStore(omexmlMeta); IJ.showStatus(""); r.addStatusListener(new StatusEchoer()); // -- Step 3: get parameter values -- debug("get parameter values"); boolean windowless = options.isWindowless() || Util.isWindowless(r); if (!windowless) status = options.promptOptions(); if (!statusOk(status)) return; boolean mergeChannels = options.isMergeChannels(); boolean colorize = options.isColorize(); boolean showMetadata = options.isShowMetadata(); boolean showOMEXML = options.isShowOMEXML(); boolean groupFiles = options.isGroupFiles(); boolean concatenate = options.isConcatenate(); boolean specifyRanges = options.isSpecifyRanges(); boolean cropOnImport = options.doCrop(); boolean swapDimensions = options.isSwapDimensions(); // save options as new defaults options.savePreferences(); // -- Step 4: analyze and read from data source -- debug("analyze and read from data source"); // 'id' contains the user's password if we are opening from OME/OMERO String a = id; if (options.isOME() || options.isOMERO()) a = "..."; IJ.showStatus("Analyzing " + a); try { r.setMetadataFiltered(true); r.setNormalized(true); r.setId(id); int pixelType = r.getPixelType(); String currentFile = r.getCurrentFile(); // -- Step 4a: prompt for the file pattern, if necessary -- if (groupFiles) { debug("prompt for the file pattern"); status = options.promptFilePattern(); if (!statusOk(status)) return; id = options.getId(); if (id == null) id = currentFile; } else debug("no need to prompt for file pattern"); if (groupFiles) r = new FileStitcher(r, true); // NB: VirtualReader extends DimensionSwapper r = new VirtualReader(new ChannelSeparator(r)); r.setId(id); // -- Step 4b: prompt for which series to import, if necessary -- // populate series-related variables int seriesCount = r.getSeriesCount(); int[] num = new int[seriesCount]; int[] sizeC = new int[seriesCount]; int[] sizeZ = new int[seriesCount]; int[] sizeT = new int[seriesCount]; boolean[] certain = new boolean[seriesCount]; int[] cBegin = new int[seriesCount]; int[] cEnd = new int[seriesCount]; int[] cStep = new int[seriesCount]; int[] zBegin = new int[seriesCount]; int[] zEnd = new int[seriesCount]; int[] zStep = new int[seriesCount]; int[] tBegin = new int[seriesCount]; int[] tEnd = new int[seriesCount]; int[] tStep = new int[seriesCount]; boolean[] series = new boolean[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); num[i] = r.getImageCount(); sizeC[i] = r.getEffectiveSizeC(); sizeZ[i] = r.getSizeZ(); sizeT[i] = r.getSizeT(); certain[i] = r.isOrderCertain(); cBegin[i] = zBegin[i] = tBegin[i] = 0; //cEnd[i] = certain[i] ? sizeC[i] - 1 : num[i] - 1; cEnd[i] = sizeC[i] - 1; zEnd[i] = sizeZ[i] - 1; tEnd[i] = sizeT[i] - 1; cStep[i] = zStep[i] = tStep[i] = 1; } series[0] = true; // build descriptive label for each series String[] seriesLabels = new String[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); StringBuffer sb = new StringBuffer(); String name = omexmlMeta.getImageName(i); if (name != null && name.length() > 0) { sb.append(name); sb.append(": "); } sb.append(r.getSizeX()); sb.append(" x "); sb.append(r.getSizeY()); sb.append("; "); sb.append(num[i]); sb.append(" plane"); if (num[i] > 1) { sb.append("s"); if (certain[i]) { sb.append(" ("); boolean first = true; if (sizeC[i] > 1) { sb.append(sizeC[i]); sb.append("C"); first = false; } if (sizeZ[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeZ[i]); sb.append("Z"); first = false; } if (sizeT[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeT[i]); sb.append("T"); first = false; } sb.append(")"); } } seriesLabels[i] = sb.toString(); seriesLabels[i] = seriesLabels[i].replaceAll(" ", "_"); } if (seriesCount > 1 && !options.openAllSeries() && !options.isViewNone()) { debug("prompt for which series to import"); status = options.promptSeries(r, seriesLabels, series); if (!statusOk(status)) return; } else debug("no need to prompt for series"); if (options.openAllSeries() || options.isViewNone()) { Arrays.fill(series, true); } // -- Step 4c: prompt for dimension swapping parameters, if necessary -- if (swapDimensions) { debug("prompt for dimension swapping parameters"); options.promptSwap((DimensionSwapper) r, series); for (int i=0; i<seriesCount; i++) { r.setSeries(i); num[i] = r.getImageCount(); sizeC[i] = r.getEffectiveSizeC(); sizeZ[i] = r.getSizeZ(); sizeT[i] = r.getSizeT(); certain[i] = r.isOrderCertain(); cBegin[i] = zBegin[i] = tBegin[i] = 0; cEnd[i] = sizeC[i] - 1; zEnd[i] = sizeZ[i] - 1; tEnd[i] = sizeT[i] - 1; cStep[i] = zStep[i] = tStep[i] = 1; } } else debug("no need to prompt for dimension swapping"); // -- Step 4d: prompt for the range of planes to import, if necessary -- if (specifyRanges) { boolean needRange = false; for (int i=0; i<seriesCount; i++) { if (series[i] && num[i] > 1) needRange = true; } if (needRange) { debug("prompt for planar ranges"); IJ.showStatus(""); status = options.promptRange(r, series, seriesLabels, cBegin, cEnd, cStep, zBegin, zEnd, zStep, tBegin, tEnd, tStep); if (!statusOk(status)) return; } else debug("no need to prompt for planar ranges"); } else debug("open all planes"); int[] cCount = new int[seriesCount]; int[] zCount = new int[seriesCount]; int[] tCount = new int[seriesCount]; for (int i=0; i<seriesCount; i++) { cCount[i] = (cEnd[i] - cBegin[i] + cStep[i]) / cStep[i]; zCount[i] = (zEnd[i] - zBegin[i] + zStep[i]) / zStep[i]; tCount[i] = (tEnd[i] - tBegin[i] + tStep[i]) / tStep[i]; } Rectangle[] cropOptions = new Rectangle[seriesCount]; for (int i=0; i<cropOptions.length; i++) { if (series[i] && cropOnImport) cropOptions[i] = new Rectangle(); } if (cropOnImport) { status = options.promptCropSize(r, seriesLabels, series, cropOptions); if (!statusOk(status)) return; } // -- Step 4e: display metadata, if appropriate -- if (showMetadata) { debug("display metadata"); IJ.showStatus("Populating metadata"); // display standard metadata in a table in its own window Hashtable meta = r.getMetadata(); //if (seriesCount == 1) meta = r.getMetadata(); meta.put(idType, currentFile); int digits = digits(seriesCount); for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); //meta.putAll(r.getCoreMetadata().seriesMetadata[i]); String s = omexmlMeta.getImageName(i); if ((s == null || s.trim().length() == 0) && seriesCount > 1) { StringBuffer sb = new StringBuffer(); sb.append("Series "); int zeroes = digits - digits(i + 1); for (int j=0; j<zeroes; j++) sb.append(0); sb.append(i + 1); sb.append(" "); s = sb.toString(); } else s += " "; final String pad = " "; // puts core values first when alphabetizing meta.put(pad + s + "SizeX", new Integer(r.getSizeX())); meta.put(pad + s + "SizeY", new Integer(r.getSizeY())); meta.put(pad + s + "SizeZ", new Integer(r.getSizeZ())); meta.put(pad + s + "SizeT", new Integer(r.getSizeT())); meta.put(pad + s + "SizeC", new Integer(r.getSizeC())); meta.put(pad + s + "IsRGB", new Boolean(r.isRGB())); meta.put(pad + s + "PixelType", FormatTools.getPixelTypeString(r.getPixelType())); meta.put(pad + s + "LittleEndian", new Boolean(r.isLittleEndian())); meta.put(pad + s + "DimensionOrder", r.getDimensionOrder()); meta.put(pad + s + "IsInterleaved", new Boolean(r.isInterleaved())); } // sort metadata keys String metaString = getMetadataString(meta, "\t"); SearchableWindow w = new SearchableWindow("Original Metadata - " + id, "Key\tValue", metaString, 400, 400); w.setVisible(true); } else debug("skip metadata"); if (showOMEXML) { debug("show OME-XML"); if (options.isViewBrowser()) { // NB: Data Browser has its own internal OME-XML metadata window, // which we'll trigger once we have created a Data Browser. // So there is no need to pop up a separate OME-XML here. } else { XMLWindow metaWindow = new XMLWindow("OME Metadata - " + id); try { metaWindow.setXML(MetadataTools.getOMEXML(omexmlMeta)); Util.placeWindow(metaWindow); metaWindow.setVisible(true); } catch (javax.xml.parsers.ParserConfigurationException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem displaying the OME metadata"); } catch (org.xml.sax.SAXException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem displaying the OME metadata"); } } } else debug("skip OME-XML"); // -- Step 4f: read pixel data -- if (options.isViewNone()) return; debug("read pixel data"); IJ.showStatus("Reading " + currentFile); if (options.isVirtual()) { int totalSeries = 0; for (int i=0; i<seriesCount; i++) { if (series[i]) totalSeries++; } ((VirtualReader) r).setRefCount(totalSeries); } for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); boolean[] load = new boolean[num[i]]; if (!options.isViewNone()) { for (int c=cBegin[i]; c<=cEnd[i]; c+=cStep[i]) { for (int z=zBegin[i]; z<=zEnd[i]; z+=zStep[i]) { for (int t=tBegin[i]; t<=tEnd[i]; t+=tStep[i]) { //int index = r.isOrderCertain() ? r.getIndex(z, c, t) : c; int index = r.getIndex(z, c, t); load[index] = true; } } } } int total = 0; for (int j=0; j<num[i]; j++) if (load[j]) total++; FileInfo fi = new FileInfo(); // populate other common FileInfo fields String idDir = idLoc == null ? null : idLoc.getParent(); if (idDir != null && !idDir.endsWith(File.separator)) { idDir += File.separator; } fi.fileName = idName; fi.directory = idDir; // place metadata key/value pairs in ImageJ's info field String metadata = getMetadataString(r.getMetadata(), " = "); long startTime = System.currentTimeMillis(); long time = startTime; ImageStack stackB = null; // for byte images (8-bit) ImageStack stackS = null; // for short images (16-bit) ImageStack stackF = null; // for floating point images (32-bit) ImageStack stackO = null; // for all other images (24-bit RGB) int w = cropOnImport ? cropOptions[i].width : r.getSizeX(); int h = cropOnImport ? cropOptions[i].height : r.getSizeY(); int c = r.getRGBChannelCount(); int type = r.getPixelType(); int q = 0; stackOrder = options.getStackOrder(); if (stackOrder.equals(ImporterOptions.ORDER_DEFAULT)) { stackOrder = r.getDimensionOrder(); } ((DimensionSwapper) r).setOutputOrder(stackOrder); omexmlMeta.setPixelsDimensionOrder(stackOrder, i, 0); // dump OME-XML to ImageJ's description field, if available fi.description = MetadataTools.getOMEXML(omexmlMeta); if (options.isVirtual()) { int cSize = r.getSizeC(); int pt = r.getPixelType(); boolean doMerge = options.isMergeChannels(); boolean eight = pt != FormatTools.UINT8 && pt != FormatTools.INT8; boolean needComposite = doMerge && (cSize > 3 || eight); int merge = (needComposite || !doMerge) ? 1 : cSize; // NB: BFVirtualStack extends VirtualStack, which only exists in // ImageJ v1.39+. We avoid referencing it directly to keep the // class loader happy for earlier versions of ImageJ. try { ReflectedUniverse ru = new ReflectedUniverse(); - ru.exec("import loci.plugins.BFVirtualStack"); + ru.exec("import loci.plugins.util.BFVirtualStack"); ru.setVar("id", id); ru.setVar("r", r); ru.setVar("colorize", colorize); ru.setVar("merge", doMerge); ru.setVar("record", options.isRecord()); stackB = (ImageStack) ru.exec("stackB = new BFVirtualStack(id, " + "r, colorize, merge, record)"); if (doMerge) { cCount[i] = 1; for (int j=0; j<num[i]; j++) { int[] pos = r.getZCTCoords(j); if (pos[1] > 0) continue; String label = constructSliceLabel( new ChannelMerger(r).getIndex(pos[0], pos[1], pos[2]), r, omexmlMeta, i, zCount, cCount, tCount); ru.setVar("label", label); ru.exec("stackB.addSlice(label)"); } } else { for (int j=0; j<num[i]; j++) { String label = constructSliceLabel(j, r, omexmlMeta, i, zCount, cCount, tCount); ru.setVar("label", label); ru.exec("stackB.addSlice(label)"); } } } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the virtual stack"); return; } } else { if (r.isIndexed()) colorModels = new IndexColorModel[r.getSizeC()]; for (int j=0; j<num[i]; j++) { if (!load[j]) continue; // limit message update rate long clock = System.currentTimeMillis(); if (clock - time >= 100) { IJ.showStatus("Reading " + (seriesCount > 1 ? ("series " + (i + 1) + ", ") : "") + "plane " + (j + 1) + "/" + num[i]); time = clock; } IJ.showProgress((double) q++ / total); int ndx = j; String label = constructSliceLabel(ndx, r, omexmlMeta, i, zCount, cCount, tCount); // get image processor for jth plane ImageProcessor ip = Util.openProcessors(r, ndx, cropOptions[i])[0]; if (ip == null) { plugin.canceled = true; return; } int channel = r.getZCTCoords(ndx)[1]; if (colorModels != null) { colorModels[channel] = (IndexColorModel) ip.getColorModel(); } // add plane to image stack if (ip instanceof ByteProcessor) { if (stackB == null) stackB = new ImageStack(w, h); stackB.addSlice(label, ip); } else if (ip instanceof ShortProcessor) { if (stackS == null) stackS = new ImageStack(w, h); stackS.addSlice(label, ip); } else if (ip instanceof FloatProcessor) { // merge image plane into existing stack if possible if (stackB != null) { ip = ip.convertToByte(true); stackB.addSlice(label, ip); } else if (stackS != null) { ip = ip.convertToShort(true); stackS.addSlice(label, ip); } else { if (stackF == null) stackF = new ImageStack(w, h); stackF.addSlice(label, ip); } } else if (ip instanceof ColorProcessor) { if (stackO == null) stackO = new ImageStack(w, h); stackO.addSlice(label, ip); } } } IJ.showStatus("Creating image"); IJ.showProgress(1); String seriesName = omexmlMeta.getImageName(i); showStack(stackB, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackS, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackF, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackO, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); long endTime = System.currentTimeMillis(); double elapsed = (endTime - startTime) / 1000.0; if (num[i] == 1) { IJ.showStatus("Bio-Formats: " + elapsed + " seconds"); } else { long average = (endTime - startTime) / num[i]; IJ.showStatus("Bio-Formats: " + elapsed + " seconds (" + average + " ms per plane)"); } } if (concatenate) { Vector widths = new Vector(); Vector heights = new Vector(); Vector types = new Vector(); Vector newImps = new Vector(); for (int j=0; j<imps.size(); j++) { ImagePlus imp = (ImagePlus) imps.get(j); int wj = imp.getWidth(); int hj = imp.getHeight(); int tj = imp.getBitDepth(); boolean append = false; for (int k=0; k<widths.size(); k++) { int wk = ((Integer) widths.get(k)).intValue(); int hk = ((Integer) heights.get(k)).intValue(); int tk = ((Integer) types.get(k)).intValue(); if (wj == wk && hj == hk && tj == tk) { ImagePlus oldImp = (ImagePlus) newImps.get(k); ImageStack is = oldImp.getStack(); ImageStack newStack = imp.getStack(); for (int s=0; s<newStack.getSize(); s++) { is.addSlice(newStack.getSliceLabel(s + 1), newStack.getProcessor(s + 1)); } oldImp.setStack(oldImp.getTitle(), is); newImps.setElementAt(oldImp, k); append = true; k = widths.size(); } } if (!append) { widths.add(new Integer(wj)); heights.add(new Integer(hj)); types.add(new Integer(tj)); newImps.add(imp); } } boolean splitC = options.isSplitChannels(); boolean splitZ = options.isSplitFocalPlanes(); boolean splitT = options.isSplitTimepoints(); for (int j=0; j<newImps.size(); j++) { ImagePlus imp = (ImagePlus) newImps.get(j); imp.show(); if (splitC || splitZ || splitT) { IJ.runPlugIn("loci.plugins.Slicer", "slice_z=" + splitZ + " slice_c=" + splitC + " slice_t=" + splitT + " stack_order=" + stackOrder + " keep_original=false " + "hyper_stack=" + options.isViewHyperstack() + " "); } } } // display ROIs, if necessary if (options.showROIs()) { debug("display ROIs"); ROIHandler.openROIs(omexmlMeta, (ImagePlus[]) imps.toArray(new ImagePlus[0])); } else debug("skip ROIs"); // -- Step 5: finish up -- debug("finish up"); try { if (!options.isVirtual()) r.close(); } catch (IOException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem closing the file"); } plugin.success = true; } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was a problem reading the data."); } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was an I/O problem reading the data."); } } // -- Helper methods -- /** * Displays the given image stack according to * the specified parameters and import options. */ private void showStack(ImageStack stack, String file, String series, MetadataRetrieve retrieve, int cCount, int zCount, int tCount, int sizeZ, int sizeC, int sizeT, FileInfo fi, final IFormatReader r, final ImporterOptions options, String metadata, boolean windowless) throws FormatException, IOException { if (stack == null) return; String title = getTitle(r, file, series, options.isGroupFiles()); ImagePlus imp = null; if (options.isVirtual()) { imp = new VirtualImagePlus(title, stack); ((VirtualImagePlus) imp).setReader(r); } else imp = new ImagePlus(title, stack); imp.setProperty("Info", metadata); // retrieve the spatial calibration information, if available Util.applyCalibration(retrieve, imp, r.getSeries()); imp.setFileInfo(fi); imp.setDimensions(cCount, zCount, tCount); displayStack(imp, r, options, windowless); } /** Displays the image stack using the appropriate plugin. */ private void displayStack(ImagePlus imp, IFormatReader r, ImporterOptions options, boolean windowless) { boolean mergeChannels = options.isMergeChannels(); boolean colorize = options.isColorize(); boolean customColorize = options.isCustomColorize(); boolean concatenate = options.isConcatenate(); int nChannels = imp.getNChannels(); int nSlices = imp.getNSlices(); int nFrames = imp.getNFrames(); if (options.isAutoscale() && !options.isVirtual()) { Util.adjustColorRange(imp); } boolean splitC = options.isSplitChannels(); boolean splitZ = options.isSplitFocalPlanes(); boolean splitT = options.isSplitTimepoints(); int z = r.getSizeZ(); int c = r.getSizeC(); int t = r.getSizeT(); if (!concatenate && mergeChannels) imp.show(); if (!options.isVirtual()) { if (mergeChannels && windowless) { IJ.runPlugIn("loci.plugins.Colorizer", "stack_order=" + stackOrder + " merge=true merge_option=[" + options.getMergeOption() + "] " + "series=" + r.getSeries() + " hyper_stack=" + options.isViewHyperstack() + " "); } else if (mergeChannels) { IJ.runPlugIn("loci.plugins.Colorizer", "stack_order=" + stackOrder + " merge=true series=" + r.getSeries() + " hyper_stack=" + options.isViewHyperstack() + " "); } } imp.setDimensions(imp.getStackSize() / (nSlices * nFrames), nSlices, nFrames); if (options.isViewVisBio()) { ReflectedUniverse ru = new ReflectedUniverse(); try { ru.exec("import loci.visbio.data.Dataset"); //ru.setVar("name", name); //ru.setVar("pattern", pattern); ru.exec("dataset = new Dataset(name, pattern)"); // CTR TODO finish VisBio logic } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem interfacing with VisBio"); return; } } if (options.isViewImage5D()) { ReflectedUniverse ru = new ReflectedUniverse(); try { ru.exec("import i5d.Image5D"); ru.setVar("title", imp.getTitle()); ru.setVar("stack", imp.getStack()); ru.setVar("sizeC", c); ru.setVar("sizeZ", z); ru.setVar("sizeT", t); ru.exec("i5d = new Image5D(title, stack, sizeC, sizeZ, sizeT)"); ru.setVar("cal", imp.getCalibration()); ru.setVar("fi", imp.getOriginalFileInfo()); ru.exec("i5d.setCalibration(cal)"); ru.exec("i5d.setFileInfo(fi)"); //ru.exec("i5d.setDimensions(sizeC, sizeZ, sizeT)"); ru.exec("i5d.show()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem interfacing with Image5D"); return; } } else if (options.isViewView5D()) { WindowManager.setTempCurrentImage(imp); IJ.run("View5D ", ""); } else if (!options.isViewNone()) { if (IJ.getVersion().compareTo("1.39l") >= 0) { boolean hyper = options.isViewHyperstack() || options.isViewBrowser(); imp.setOpenAsHyperStack(hyper); } if (!concatenate) { if (options.isViewBrowser()) { DataBrowser dataBrowser = new DataBrowser(imp, null, r.getChannelDimTypes(), r.getChannelDimLengths()); if (options.isShowOMEXML()) dataBrowser.showMetadataWindow(); } else imp.show(); boolean virtual = options.isViewBrowser() || options.isVirtual(); if ((colorize || customColorize) && !virtual) { IJ.runPlugIn("loci.plugins.Colorizer", "stack_order=" + stackOrder + " merge=false colorize=true ndx=" + (customColorize ? "-1" : "0") + " series=" + r.getSeries() + " hyper_stack=" + options.isViewHyperstack() + " "); } else if (colorModels != null && !virtual) { Colorizer colorizer = new Colorizer(); String arg = "stack_order=" + stackOrder + " merge=false " + "colorize=true series=" + r.getSeries() + " hyper_stack=" + options.isViewHyperstack() + " "; colorizer.setup(arg, imp); for (int channel=0; channel<colorModels.length; channel++) { byte[][] lut = new byte[3][256]; colorModels[channel].getReds(lut[0]); colorModels[channel].getGreens(lut[1]); colorModels[channel].getBlues(lut[2]); colorizer.setLookupTable(lut, channel); } new PlugInFilterRunner(colorizer, "", arg); } if ((splitC || splitZ || splitT) && !virtual) { IJ.runPlugIn("loci.plugins.Slicer", "slice_z=" + splitZ + " slice_c=" + splitC + " slice_t=" + splitT + " stack_order=" + stackOrder + " keep_original=false " + "hyper_stack=" + options.isViewHyperstack() + " "); } } imps.add(imp); } } /** Computes the given value's number of digits. */ private int digits(int value) { int digits = 0; while (value > 0) { value /= 10; digits++; } return digits; } /** Get an appropriate stack title, given the file name. */ private String getTitle(IFormatReader r, String file, String series, boolean groupFiles) { String[] used = r.getUsedFiles(); String title = file.substring(file.lastIndexOf(File.separator) + 1); if (used.length > 1 && groupFiles) { FilePattern fp = new FilePattern(new Location(file)); if (fp != null) { title = fp.getPattern(); if (title == null) { title = file; if (title.indexOf(".") != -1) { title = title.substring(0, title.lastIndexOf(".")); } } title = title.substring(title.lastIndexOf(File.separator) + 1); } } if (series != null && !file.endsWith(series) && r.getSeriesCount() > 1) { title += " - " + series; } if (title.length() > 128) { String a = title.substring(0, 62); String b = title.substring(title.length() - 62); title = a + "..." + b; } return title; } /** Constructs slice label. */ private String constructSliceLabel(int ndx, IFormatReader r, MetadataRetrieve retrieve, int series, int[] zCount, int[] cCount, int[] tCount) { r.setSeries(series); int[] zct = r.getZCTCoords(ndx); int[] subC = r.getChannelDimLengths(); String[] subCTypes = r.getChannelDimTypes(); StringBuffer sb = new StringBuffer(); boolean first = true; if (cCount[series] > 1) { if (first) first = false; else sb.append("; "); int[] subCPos = FormatTools.rasterToPosition(subC, zct[1]); for (int i=0; i<subC.length; i++) { boolean ch = subCTypes[i].equals(FormatTools.CHANNEL); sb.append(ch ? "c" : subCTypes[i]); sb.append(":"); sb.append(subCPos[i] + 1); sb.append("/"); sb.append(subC[i]); if (i < subC.length - 1) sb.append(", "); } } if (zCount[series] > 1) { if (first) first = false; else sb.append("; "); sb.append("z:"); sb.append(zct[0] + 1); sb.append("/"); sb.append(r.getSizeZ()); } if (tCount[series] > 1) { if (first) first = false; else sb.append("; "); sb.append("t:"); sb.append(zct[2] + 1); sb.append("/"); sb.append(r.getSizeT()); } // put image name at the end, in case it is long String imageName = retrieve.getImageName(series); if (imageName != null && !imageName.trim().equals("")) { sb.append(" - "); sb.append(imageName); } return sb.toString(); } /** Verifies that the given status result is OK. */ private boolean statusOk(int status) { if (status == ImporterOptions.STATUS_CANCELED) plugin.canceled = true; return status == ImporterOptions.STATUS_OK; } /** Reports the given exception with stack trace in an ImageJ error dialog. */ private void reportException(Throwable t, boolean quiet, String msg) { IJ.showStatus(""); if (!quiet) { if (t != null) { ByteArrayOutputStream buf = new ByteArrayOutputStream(); t.printStackTrace(new PrintStream(buf)); String s = new String(buf.toByteArray()); StringTokenizer st = new StringTokenizer(s, "\n\r"); while (st.hasMoreTokens()) IJ.write(st.nextToken()); } IJ.error("Bio-Formats Importer", msg); } } /** Returns a string with each key/value pair on its own line. */ private String getMetadataString(Hashtable meta, String separator) { Enumeration e = meta.keys(); Vector v = new Vector(); while (e.hasMoreElements()) v.add(e.nextElement()); String[] keys = new String[v.size()]; v.copyInto(keys); Arrays.sort(keys); StringBuffer sb = new StringBuffer(); for (int i=0; i<keys.length; i++) { sb.append(keys[i]); sb.append(separator); sb.append(meta.get(keys[i])); sb.append("\n"); } return sb.toString(); } /** Prints a debugging message to the ImageJ log if debug mode is set. */ private void debug(String msg) { if (IJ.debugMode) IJ.log("Bio-Formats Importer: " + msg); } // -- Main method -- /** Main method, for testing. */ public static void main(String[] args) { new ImageJ(null); StringBuffer sb = new StringBuffer(); for (int i=0; i<args.length; i++) { if (i > 0) sb.append(" "); sb.append(args[i]); } new LociImporter().run(sb.toString()); } // -- Helper classes -- /** Used to echo status messages to the ImageJ status bar. */ private static class StatusEchoer implements StatusListener { public void statusUpdated(StatusEvent e) { IJ.showStatus(e.getStatusMessage()); } } private class VirtualReader extends DimensionSwapper { private int refCount; // -- Constructor -- public VirtualReader(IFormatReader r) { super(r); refCount = 0; } // -- VirtualReader API methods -- public void setRefCount(int refCount) { this.refCount = refCount; } // -- IFormatReader API methods -- public void close() throws IOException { if (refCount > 0) refCount--; if (refCount == 0) super.close(); } } }
true
true
public void run(String arg) { // -- Step 0: parse core options -- debug("parse core options"); ImporterOptions options = new ImporterOptions(); options.loadPreferences(); options.parseArg(arg); // -- Step 1: check if new version is available -- if (options.doUpgradeCheck()) { debug("check if new version is available"); IJ.showStatus("Checking for new version..."); if (Updater.newVersionAvailable()) { boolean doUpgrade = IJ.showMessageWithCancel("", "A new stable version of Bio-Formats is available.\n" + "Click 'OK' to upgrade."); if (doUpgrade) { Updater.install(Updater.STABLE_BUILD); } } } else debug("skipping new version check"); // -- Step 2: construct reader and check id -- debug("construct reader and check id"); int status = options.promptLocation(); if (!statusOk(status)) return; status = options.promptId(); if (!statusOk(status)) return; String id = options.getId(); boolean quiet = options.isQuiet(); Location idLoc = options.getIdLocation(); String idName = options.getIdName(); String idType = options.getIdType(); IFormatReader r = null; if (options.isLocal() || options.isHTTP()) { IJ.showStatus("Identifying " + idName); ImageReader reader = Util.makeImageReader(); try { r = reader.getReader(id); } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was an error reading the file."); return; } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was a I/O problem reading the file."); return; } } else if (options.isOMERO()) { // NB: avoid dependencies on optional loci.ome.io package try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.ome.io.OMEROReader"); r = (IFormatReader) ru.exec("new OMEROReader()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the OMERO I/O engine"); return; } } else if (options.isOME()) { // NB: avoid dependencies on optional loci.ome.io package try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.ome.io.OMEReader"); r = (IFormatReader) ru.exec("new OMEReader()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the OME I/O engine"); return; } } else { reportException(null, options.isQuiet(), "Sorry, there has been an internal error: unknown data source"); } IMetadata omexmlMeta = MetadataTools.createOMEXMLMetadata(); r.setMetadataStore(omexmlMeta); IJ.showStatus(""); r.addStatusListener(new StatusEchoer()); // -- Step 3: get parameter values -- debug("get parameter values"); boolean windowless = options.isWindowless() || Util.isWindowless(r); if (!windowless) status = options.promptOptions(); if (!statusOk(status)) return; boolean mergeChannels = options.isMergeChannels(); boolean colorize = options.isColorize(); boolean showMetadata = options.isShowMetadata(); boolean showOMEXML = options.isShowOMEXML(); boolean groupFiles = options.isGroupFiles(); boolean concatenate = options.isConcatenate(); boolean specifyRanges = options.isSpecifyRanges(); boolean cropOnImport = options.doCrop(); boolean swapDimensions = options.isSwapDimensions(); // save options as new defaults options.savePreferences(); // -- Step 4: analyze and read from data source -- debug("analyze and read from data source"); // 'id' contains the user's password if we are opening from OME/OMERO String a = id; if (options.isOME() || options.isOMERO()) a = "..."; IJ.showStatus("Analyzing " + a); try { r.setMetadataFiltered(true); r.setNormalized(true); r.setId(id); int pixelType = r.getPixelType(); String currentFile = r.getCurrentFile(); // -- Step 4a: prompt for the file pattern, if necessary -- if (groupFiles) { debug("prompt for the file pattern"); status = options.promptFilePattern(); if (!statusOk(status)) return; id = options.getId(); if (id == null) id = currentFile; } else debug("no need to prompt for file pattern"); if (groupFiles) r = new FileStitcher(r, true); // NB: VirtualReader extends DimensionSwapper r = new VirtualReader(new ChannelSeparator(r)); r.setId(id); // -- Step 4b: prompt for which series to import, if necessary -- // populate series-related variables int seriesCount = r.getSeriesCount(); int[] num = new int[seriesCount]; int[] sizeC = new int[seriesCount]; int[] sizeZ = new int[seriesCount]; int[] sizeT = new int[seriesCount]; boolean[] certain = new boolean[seriesCount]; int[] cBegin = new int[seriesCount]; int[] cEnd = new int[seriesCount]; int[] cStep = new int[seriesCount]; int[] zBegin = new int[seriesCount]; int[] zEnd = new int[seriesCount]; int[] zStep = new int[seriesCount]; int[] tBegin = new int[seriesCount]; int[] tEnd = new int[seriesCount]; int[] tStep = new int[seriesCount]; boolean[] series = new boolean[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); num[i] = r.getImageCount(); sizeC[i] = r.getEffectiveSizeC(); sizeZ[i] = r.getSizeZ(); sizeT[i] = r.getSizeT(); certain[i] = r.isOrderCertain(); cBegin[i] = zBegin[i] = tBegin[i] = 0; //cEnd[i] = certain[i] ? sizeC[i] - 1 : num[i] - 1; cEnd[i] = sizeC[i] - 1; zEnd[i] = sizeZ[i] - 1; tEnd[i] = sizeT[i] - 1; cStep[i] = zStep[i] = tStep[i] = 1; } series[0] = true; // build descriptive label for each series String[] seriesLabels = new String[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); StringBuffer sb = new StringBuffer(); String name = omexmlMeta.getImageName(i); if (name != null && name.length() > 0) { sb.append(name); sb.append(": "); } sb.append(r.getSizeX()); sb.append(" x "); sb.append(r.getSizeY()); sb.append("; "); sb.append(num[i]); sb.append(" plane"); if (num[i] > 1) { sb.append("s"); if (certain[i]) { sb.append(" ("); boolean first = true; if (sizeC[i] > 1) { sb.append(sizeC[i]); sb.append("C"); first = false; } if (sizeZ[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeZ[i]); sb.append("Z"); first = false; } if (sizeT[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeT[i]); sb.append("T"); first = false; } sb.append(")"); } } seriesLabels[i] = sb.toString(); seriesLabels[i] = seriesLabels[i].replaceAll(" ", "_"); } if (seriesCount > 1 && !options.openAllSeries() && !options.isViewNone()) { debug("prompt for which series to import"); status = options.promptSeries(r, seriesLabels, series); if (!statusOk(status)) return; } else debug("no need to prompt for series"); if (options.openAllSeries() || options.isViewNone()) { Arrays.fill(series, true); } // -- Step 4c: prompt for dimension swapping parameters, if necessary -- if (swapDimensions) { debug("prompt for dimension swapping parameters"); options.promptSwap((DimensionSwapper) r, series); for (int i=0; i<seriesCount; i++) { r.setSeries(i); num[i] = r.getImageCount(); sizeC[i] = r.getEffectiveSizeC(); sizeZ[i] = r.getSizeZ(); sizeT[i] = r.getSizeT(); certain[i] = r.isOrderCertain(); cBegin[i] = zBegin[i] = tBegin[i] = 0; cEnd[i] = sizeC[i] - 1; zEnd[i] = sizeZ[i] - 1; tEnd[i] = sizeT[i] - 1; cStep[i] = zStep[i] = tStep[i] = 1; } } else debug("no need to prompt for dimension swapping"); // -- Step 4d: prompt for the range of planes to import, if necessary -- if (specifyRanges) { boolean needRange = false; for (int i=0; i<seriesCount; i++) { if (series[i] && num[i] > 1) needRange = true; } if (needRange) { debug("prompt for planar ranges"); IJ.showStatus(""); status = options.promptRange(r, series, seriesLabels, cBegin, cEnd, cStep, zBegin, zEnd, zStep, tBegin, tEnd, tStep); if (!statusOk(status)) return; } else debug("no need to prompt for planar ranges"); } else debug("open all planes"); int[] cCount = new int[seriesCount]; int[] zCount = new int[seriesCount]; int[] tCount = new int[seriesCount]; for (int i=0; i<seriesCount; i++) { cCount[i] = (cEnd[i] - cBegin[i] + cStep[i]) / cStep[i]; zCount[i] = (zEnd[i] - zBegin[i] + zStep[i]) / zStep[i]; tCount[i] = (tEnd[i] - tBegin[i] + tStep[i]) / tStep[i]; } Rectangle[] cropOptions = new Rectangle[seriesCount]; for (int i=0; i<cropOptions.length; i++) { if (series[i] && cropOnImport) cropOptions[i] = new Rectangle(); } if (cropOnImport) { status = options.promptCropSize(r, seriesLabels, series, cropOptions); if (!statusOk(status)) return; } // -- Step 4e: display metadata, if appropriate -- if (showMetadata) { debug("display metadata"); IJ.showStatus("Populating metadata"); // display standard metadata in a table in its own window Hashtable meta = r.getMetadata(); //if (seriesCount == 1) meta = r.getMetadata(); meta.put(idType, currentFile); int digits = digits(seriesCount); for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); //meta.putAll(r.getCoreMetadata().seriesMetadata[i]); String s = omexmlMeta.getImageName(i); if ((s == null || s.trim().length() == 0) && seriesCount > 1) { StringBuffer sb = new StringBuffer(); sb.append("Series "); int zeroes = digits - digits(i + 1); for (int j=0; j<zeroes; j++) sb.append(0); sb.append(i + 1); sb.append(" "); s = sb.toString(); } else s += " "; final String pad = " "; // puts core values first when alphabetizing meta.put(pad + s + "SizeX", new Integer(r.getSizeX())); meta.put(pad + s + "SizeY", new Integer(r.getSizeY())); meta.put(pad + s + "SizeZ", new Integer(r.getSizeZ())); meta.put(pad + s + "SizeT", new Integer(r.getSizeT())); meta.put(pad + s + "SizeC", new Integer(r.getSizeC())); meta.put(pad + s + "IsRGB", new Boolean(r.isRGB())); meta.put(pad + s + "PixelType", FormatTools.getPixelTypeString(r.getPixelType())); meta.put(pad + s + "LittleEndian", new Boolean(r.isLittleEndian())); meta.put(pad + s + "DimensionOrder", r.getDimensionOrder()); meta.put(pad + s + "IsInterleaved", new Boolean(r.isInterleaved())); } // sort metadata keys String metaString = getMetadataString(meta, "\t"); SearchableWindow w = new SearchableWindow("Original Metadata - " + id, "Key\tValue", metaString, 400, 400); w.setVisible(true); } else debug("skip metadata"); if (showOMEXML) { debug("show OME-XML"); if (options.isViewBrowser()) { // NB: Data Browser has its own internal OME-XML metadata window, // which we'll trigger once we have created a Data Browser. // So there is no need to pop up a separate OME-XML here. } else { XMLWindow metaWindow = new XMLWindow("OME Metadata - " + id); try { metaWindow.setXML(MetadataTools.getOMEXML(omexmlMeta)); Util.placeWindow(metaWindow); metaWindow.setVisible(true); } catch (javax.xml.parsers.ParserConfigurationException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem displaying the OME metadata"); } catch (org.xml.sax.SAXException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem displaying the OME metadata"); } } } else debug("skip OME-XML"); // -- Step 4f: read pixel data -- if (options.isViewNone()) return; debug("read pixel data"); IJ.showStatus("Reading " + currentFile); if (options.isVirtual()) { int totalSeries = 0; for (int i=0; i<seriesCount; i++) { if (series[i]) totalSeries++; } ((VirtualReader) r).setRefCount(totalSeries); } for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); boolean[] load = new boolean[num[i]]; if (!options.isViewNone()) { for (int c=cBegin[i]; c<=cEnd[i]; c+=cStep[i]) { for (int z=zBegin[i]; z<=zEnd[i]; z+=zStep[i]) { for (int t=tBegin[i]; t<=tEnd[i]; t+=tStep[i]) { //int index = r.isOrderCertain() ? r.getIndex(z, c, t) : c; int index = r.getIndex(z, c, t); load[index] = true; } } } } int total = 0; for (int j=0; j<num[i]; j++) if (load[j]) total++; FileInfo fi = new FileInfo(); // populate other common FileInfo fields String idDir = idLoc == null ? null : idLoc.getParent(); if (idDir != null && !idDir.endsWith(File.separator)) { idDir += File.separator; } fi.fileName = idName; fi.directory = idDir; // place metadata key/value pairs in ImageJ's info field String metadata = getMetadataString(r.getMetadata(), " = "); long startTime = System.currentTimeMillis(); long time = startTime; ImageStack stackB = null; // for byte images (8-bit) ImageStack stackS = null; // for short images (16-bit) ImageStack stackF = null; // for floating point images (32-bit) ImageStack stackO = null; // for all other images (24-bit RGB) int w = cropOnImport ? cropOptions[i].width : r.getSizeX(); int h = cropOnImport ? cropOptions[i].height : r.getSizeY(); int c = r.getRGBChannelCount(); int type = r.getPixelType(); int q = 0; stackOrder = options.getStackOrder(); if (stackOrder.equals(ImporterOptions.ORDER_DEFAULT)) { stackOrder = r.getDimensionOrder(); } ((DimensionSwapper) r).setOutputOrder(stackOrder); omexmlMeta.setPixelsDimensionOrder(stackOrder, i, 0); // dump OME-XML to ImageJ's description field, if available fi.description = MetadataTools.getOMEXML(omexmlMeta); if (options.isVirtual()) { int cSize = r.getSizeC(); int pt = r.getPixelType(); boolean doMerge = options.isMergeChannels(); boolean eight = pt != FormatTools.UINT8 && pt != FormatTools.INT8; boolean needComposite = doMerge && (cSize > 3 || eight); int merge = (needComposite || !doMerge) ? 1 : cSize; // NB: BFVirtualStack extends VirtualStack, which only exists in // ImageJ v1.39+. We avoid referencing it directly to keep the // class loader happy for earlier versions of ImageJ. try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.plugins.BFVirtualStack"); ru.setVar("id", id); ru.setVar("r", r); ru.setVar("colorize", colorize); ru.setVar("merge", doMerge); ru.setVar("record", options.isRecord()); stackB = (ImageStack) ru.exec("stackB = new BFVirtualStack(id, " + "r, colorize, merge, record)"); if (doMerge) { cCount[i] = 1; for (int j=0; j<num[i]; j++) { int[] pos = r.getZCTCoords(j); if (pos[1] > 0) continue; String label = constructSliceLabel( new ChannelMerger(r).getIndex(pos[0], pos[1], pos[2]), r, omexmlMeta, i, zCount, cCount, tCount); ru.setVar("label", label); ru.exec("stackB.addSlice(label)"); } } else { for (int j=0; j<num[i]; j++) { String label = constructSliceLabel(j, r, omexmlMeta, i, zCount, cCount, tCount); ru.setVar("label", label); ru.exec("stackB.addSlice(label)"); } } } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the virtual stack"); return; } } else { if (r.isIndexed()) colorModels = new IndexColorModel[r.getSizeC()]; for (int j=0; j<num[i]; j++) { if (!load[j]) continue; // limit message update rate long clock = System.currentTimeMillis(); if (clock - time >= 100) { IJ.showStatus("Reading " + (seriesCount > 1 ? ("series " + (i + 1) + ", ") : "") + "plane " + (j + 1) + "/" + num[i]); time = clock; } IJ.showProgress((double) q++ / total); int ndx = j; String label = constructSliceLabel(ndx, r, omexmlMeta, i, zCount, cCount, tCount); // get image processor for jth plane ImageProcessor ip = Util.openProcessors(r, ndx, cropOptions[i])[0]; if (ip == null) { plugin.canceled = true; return; } int channel = r.getZCTCoords(ndx)[1]; if (colorModels != null) { colorModels[channel] = (IndexColorModel) ip.getColorModel(); } // add plane to image stack if (ip instanceof ByteProcessor) { if (stackB == null) stackB = new ImageStack(w, h); stackB.addSlice(label, ip); } else if (ip instanceof ShortProcessor) { if (stackS == null) stackS = new ImageStack(w, h); stackS.addSlice(label, ip); } else if (ip instanceof FloatProcessor) { // merge image plane into existing stack if possible if (stackB != null) { ip = ip.convertToByte(true); stackB.addSlice(label, ip); } else if (stackS != null) { ip = ip.convertToShort(true); stackS.addSlice(label, ip); } else { if (stackF == null) stackF = new ImageStack(w, h); stackF.addSlice(label, ip); } } else if (ip instanceof ColorProcessor) { if (stackO == null) stackO = new ImageStack(w, h); stackO.addSlice(label, ip); } } } IJ.showStatus("Creating image"); IJ.showProgress(1); String seriesName = omexmlMeta.getImageName(i); showStack(stackB, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackS, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackF, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackO, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); long endTime = System.currentTimeMillis(); double elapsed = (endTime - startTime) / 1000.0; if (num[i] == 1) { IJ.showStatus("Bio-Formats: " + elapsed + " seconds"); } else { long average = (endTime - startTime) / num[i]; IJ.showStatus("Bio-Formats: " + elapsed + " seconds (" + average + " ms per plane)"); } } if (concatenate) { Vector widths = new Vector(); Vector heights = new Vector(); Vector types = new Vector(); Vector newImps = new Vector(); for (int j=0; j<imps.size(); j++) { ImagePlus imp = (ImagePlus) imps.get(j); int wj = imp.getWidth(); int hj = imp.getHeight(); int tj = imp.getBitDepth(); boolean append = false; for (int k=0; k<widths.size(); k++) { int wk = ((Integer) widths.get(k)).intValue(); int hk = ((Integer) heights.get(k)).intValue(); int tk = ((Integer) types.get(k)).intValue(); if (wj == wk && hj == hk && tj == tk) { ImagePlus oldImp = (ImagePlus) newImps.get(k); ImageStack is = oldImp.getStack(); ImageStack newStack = imp.getStack(); for (int s=0; s<newStack.getSize(); s++) { is.addSlice(newStack.getSliceLabel(s + 1), newStack.getProcessor(s + 1)); } oldImp.setStack(oldImp.getTitle(), is); newImps.setElementAt(oldImp, k); append = true; k = widths.size(); } } if (!append) { widths.add(new Integer(wj)); heights.add(new Integer(hj)); types.add(new Integer(tj)); newImps.add(imp); } } boolean splitC = options.isSplitChannels(); boolean splitZ = options.isSplitFocalPlanes(); boolean splitT = options.isSplitTimepoints(); for (int j=0; j<newImps.size(); j++) { ImagePlus imp = (ImagePlus) newImps.get(j); imp.show(); if (splitC || splitZ || splitT) { IJ.runPlugIn("loci.plugins.Slicer", "slice_z=" + splitZ + " slice_c=" + splitC + " slice_t=" + splitT + " stack_order=" + stackOrder + " keep_original=false " + "hyper_stack=" + options.isViewHyperstack() + " "); } } } // display ROIs, if necessary if (options.showROIs()) { debug("display ROIs"); ROIHandler.openROIs(omexmlMeta, (ImagePlus[]) imps.toArray(new ImagePlus[0])); } else debug("skip ROIs"); // -- Step 5: finish up -- debug("finish up"); try { if (!options.isVirtual()) r.close(); } catch (IOException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem closing the file"); } plugin.success = true; } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was a problem reading the data."); } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was an I/O problem reading the data."); } }
public void run(String arg) { // -- Step 0: parse core options -- debug("parse core options"); ImporterOptions options = new ImporterOptions(); options.loadPreferences(); options.parseArg(arg); // -- Step 1: check if new version is available -- if (options.doUpgradeCheck()) { debug("check if new version is available"); IJ.showStatus("Checking for new version..."); if (Updater.newVersionAvailable()) { boolean doUpgrade = IJ.showMessageWithCancel("", "A new stable version of Bio-Formats is available.\n" + "Click 'OK' to upgrade."); if (doUpgrade) { Updater.install(Updater.STABLE_BUILD); } } } else debug("skipping new version check"); // -- Step 2: construct reader and check id -- debug("construct reader and check id"); int status = options.promptLocation(); if (!statusOk(status)) return; status = options.promptId(); if (!statusOk(status)) return; String id = options.getId(); boolean quiet = options.isQuiet(); Location idLoc = options.getIdLocation(); String idName = options.getIdName(); String idType = options.getIdType(); IFormatReader r = null; if (options.isLocal() || options.isHTTP()) { IJ.showStatus("Identifying " + idName); ImageReader reader = Util.makeImageReader(); try { r = reader.getReader(id); } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was an error reading the file."); return; } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was a I/O problem reading the file."); return; } } else if (options.isOMERO()) { // NB: avoid dependencies on optional loci.ome.io package try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.ome.io.OMEROReader"); r = (IFormatReader) ru.exec("new OMEROReader()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the OMERO I/O engine"); return; } } else if (options.isOME()) { // NB: avoid dependencies on optional loci.ome.io package try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.ome.io.OMEReader"); r = (IFormatReader) ru.exec("new OMEReader()"); } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the OME I/O engine"); return; } } else { reportException(null, options.isQuiet(), "Sorry, there has been an internal error: unknown data source"); } IMetadata omexmlMeta = MetadataTools.createOMEXMLMetadata(); r.setMetadataStore(omexmlMeta); IJ.showStatus(""); r.addStatusListener(new StatusEchoer()); // -- Step 3: get parameter values -- debug("get parameter values"); boolean windowless = options.isWindowless() || Util.isWindowless(r); if (!windowless) status = options.promptOptions(); if (!statusOk(status)) return; boolean mergeChannels = options.isMergeChannels(); boolean colorize = options.isColorize(); boolean showMetadata = options.isShowMetadata(); boolean showOMEXML = options.isShowOMEXML(); boolean groupFiles = options.isGroupFiles(); boolean concatenate = options.isConcatenate(); boolean specifyRanges = options.isSpecifyRanges(); boolean cropOnImport = options.doCrop(); boolean swapDimensions = options.isSwapDimensions(); // save options as new defaults options.savePreferences(); // -- Step 4: analyze and read from data source -- debug("analyze and read from data source"); // 'id' contains the user's password if we are opening from OME/OMERO String a = id; if (options.isOME() || options.isOMERO()) a = "..."; IJ.showStatus("Analyzing " + a); try { r.setMetadataFiltered(true); r.setNormalized(true); r.setId(id); int pixelType = r.getPixelType(); String currentFile = r.getCurrentFile(); // -- Step 4a: prompt for the file pattern, if necessary -- if (groupFiles) { debug("prompt for the file pattern"); status = options.promptFilePattern(); if (!statusOk(status)) return; id = options.getId(); if (id == null) id = currentFile; } else debug("no need to prompt for file pattern"); if (groupFiles) r = new FileStitcher(r, true); // NB: VirtualReader extends DimensionSwapper r = new VirtualReader(new ChannelSeparator(r)); r.setId(id); // -- Step 4b: prompt for which series to import, if necessary -- // populate series-related variables int seriesCount = r.getSeriesCount(); int[] num = new int[seriesCount]; int[] sizeC = new int[seriesCount]; int[] sizeZ = new int[seriesCount]; int[] sizeT = new int[seriesCount]; boolean[] certain = new boolean[seriesCount]; int[] cBegin = new int[seriesCount]; int[] cEnd = new int[seriesCount]; int[] cStep = new int[seriesCount]; int[] zBegin = new int[seriesCount]; int[] zEnd = new int[seriesCount]; int[] zStep = new int[seriesCount]; int[] tBegin = new int[seriesCount]; int[] tEnd = new int[seriesCount]; int[] tStep = new int[seriesCount]; boolean[] series = new boolean[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); num[i] = r.getImageCount(); sizeC[i] = r.getEffectiveSizeC(); sizeZ[i] = r.getSizeZ(); sizeT[i] = r.getSizeT(); certain[i] = r.isOrderCertain(); cBegin[i] = zBegin[i] = tBegin[i] = 0; //cEnd[i] = certain[i] ? sizeC[i] - 1 : num[i] - 1; cEnd[i] = sizeC[i] - 1; zEnd[i] = sizeZ[i] - 1; tEnd[i] = sizeT[i] - 1; cStep[i] = zStep[i] = tStep[i] = 1; } series[0] = true; // build descriptive label for each series String[] seriesLabels = new String[seriesCount]; for (int i=0; i<seriesCount; i++) { r.setSeries(i); StringBuffer sb = new StringBuffer(); String name = omexmlMeta.getImageName(i); if (name != null && name.length() > 0) { sb.append(name); sb.append(": "); } sb.append(r.getSizeX()); sb.append(" x "); sb.append(r.getSizeY()); sb.append("; "); sb.append(num[i]); sb.append(" plane"); if (num[i] > 1) { sb.append("s"); if (certain[i]) { sb.append(" ("); boolean first = true; if (sizeC[i] > 1) { sb.append(sizeC[i]); sb.append("C"); first = false; } if (sizeZ[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeZ[i]); sb.append("Z"); first = false; } if (sizeT[i] > 1) { if (!first) sb.append(" x "); sb.append(sizeT[i]); sb.append("T"); first = false; } sb.append(")"); } } seriesLabels[i] = sb.toString(); seriesLabels[i] = seriesLabels[i].replaceAll(" ", "_"); } if (seriesCount > 1 && !options.openAllSeries() && !options.isViewNone()) { debug("prompt for which series to import"); status = options.promptSeries(r, seriesLabels, series); if (!statusOk(status)) return; } else debug("no need to prompt for series"); if (options.openAllSeries() || options.isViewNone()) { Arrays.fill(series, true); } // -- Step 4c: prompt for dimension swapping parameters, if necessary -- if (swapDimensions) { debug("prompt for dimension swapping parameters"); options.promptSwap((DimensionSwapper) r, series); for (int i=0; i<seriesCount; i++) { r.setSeries(i); num[i] = r.getImageCount(); sizeC[i] = r.getEffectiveSizeC(); sizeZ[i] = r.getSizeZ(); sizeT[i] = r.getSizeT(); certain[i] = r.isOrderCertain(); cBegin[i] = zBegin[i] = tBegin[i] = 0; cEnd[i] = sizeC[i] - 1; zEnd[i] = sizeZ[i] - 1; tEnd[i] = sizeT[i] - 1; cStep[i] = zStep[i] = tStep[i] = 1; } } else debug("no need to prompt for dimension swapping"); // -- Step 4d: prompt for the range of planes to import, if necessary -- if (specifyRanges) { boolean needRange = false; for (int i=0; i<seriesCount; i++) { if (series[i] && num[i] > 1) needRange = true; } if (needRange) { debug("prompt for planar ranges"); IJ.showStatus(""); status = options.promptRange(r, series, seriesLabels, cBegin, cEnd, cStep, zBegin, zEnd, zStep, tBegin, tEnd, tStep); if (!statusOk(status)) return; } else debug("no need to prompt for planar ranges"); } else debug("open all planes"); int[] cCount = new int[seriesCount]; int[] zCount = new int[seriesCount]; int[] tCount = new int[seriesCount]; for (int i=0; i<seriesCount; i++) { cCount[i] = (cEnd[i] - cBegin[i] + cStep[i]) / cStep[i]; zCount[i] = (zEnd[i] - zBegin[i] + zStep[i]) / zStep[i]; tCount[i] = (tEnd[i] - tBegin[i] + tStep[i]) / tStep[i]; } Rectangle[] cropOptions = new Rectangle[seriesCount]; for (int i=0; i<cropOptions.length; i++) { if (series[i] && cropOnImport) cropOptions[i] = new Rectangle(); } if (cropOnImport) { status = options.promptCropSize(r, seriesLabels, series, cropOptions); if (!statusOk(status)) return; } // -- Step 4e: display metadata, if appropriate -- if (showMetadata) { debug("display metadata"); IJ.showStatus("Populating metadata"); // display standard metadata in a table in its own window Hashtable meta = r.getMetadata(); //if (seriesCount == 1) meta = r.getMetadata(); meta.put(idType, currentFile); int digits = digits(seriesCount); for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); //meta.putAll(r.getCoreMetadata().seriesMetadata[i]); String s = omexmlMeta.getImageName(i); if ((s == null || s.trim().length() == 0) && seriesCount > 1) { StringBuffer sb = new StringBuffer(); sb.append("Series "); int zeroes = digits - digits(i + 1); for (int j=0; j<zeroes; j++) sb.append(0); sb.append(i + 1); sb.append(" "); s = sb.toString(); } else s += " "; final String pad = " "; // puts core values first when alphabetizing meta.put(pad + s + "SizeX", new Integer(r.getSizeX())); meta.put(pad + s + "SizeY", new Integer(r.getSizeY())); meta.put(pad + s + "SizeZ", new Integer(r.getSizeZ())); meta.put(pad + s + "SizeT", new Integer(r.getSizeT())); meta.put(pad + s + "SizeC", new Integer(r.getSizeC())); meta.put(pad + s + "IsRGB", new Boolean(r.isRGB())); meta.put(pad + s + "PixelType", FormatTools.getPixelTypeString(r.getPixelType())); meta.put(pad + s + "LittleEndian", new Boolean(r.isLittleEndian())); meta.put(pad + s + "DimensionOrder", r.getDimensionOrder()); meta.put(pad + s + "IsInterleaved", new Boolean(r.isInterleaved())); } // sort metadata keys String metaString = getMetadataString(meta, "\t"); SearchableWindow w = new SearchableWindow("Original Metadata - " + id, "Key\tValue", metaString, 400, 400); w.setVisible(true); } else debug("skip metadata"); if (showOMEXML) { debug("show OME-XML"); if (options.isViewBrowser()) { // NB: Data Browser has its own internal OME-XML metadata window, // which we'll trigger once we have created a Data Browser. // So there is no need to pop up a separate OME-XML here. } else { XMLWindow metaWindow = new XMLWindow("OME Metadata - " + id); try { metaWindow.setXML(MetadataTools.getOMEXML(omexmlMeta)); Util.placeWindow(metaWindow); metaWindow.setVisible(true); } catch (javax.xml.parsers.ParserConfigurationException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem displaying the OME metadata"); } catch (org.xml.sax.SAXException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem displaying the OME metadata"); } } } else debug("skip OME-XML"); // -- Step 4f: read pixel data -- if (options.isViewNone()) return; debug("read pixel data"); IJ.showStatus("Reading " + currentFile); if (options.isVirtual()) { int totalSeries = 0; for (int i=0; i<seriesCount; i++) { if (series[i]) totalSeries++; } ((VirtualReader) r).setRefCount(totalSeries); } for (int i=0; i<seriesCount; i++) { if (!series[i]) continue; r.setSeries(i); boolean[] load = new boolean[num[i]]; if (!options.isViewNone()) { for (int c=cBegin[i]; c<=cEnd[i]; c+=cStep[i]) { for (int z=zBegin[i]; z<=zEnd[i]; z+=zStep[i]) { for (int t=tBegin[i]; t<=tEnd[i]; t+=tStep[i]) { //int index = r.isOrderCertain() ? r.getIndex(z, c, t) : c; int index = r.getIndex(z, c, t); load[index] = true; } } } } int total = 0; for (int j=0; j<num[i]; j++) if (load[j]) total++; FileInfo fi = new FileInfo(); // populate other common FileInfo fields String idDir = idLoc == null ? null : idLoc.getParent(); if (idDir != null && !idDir.endsWith(File.separator)) { idDir += File.separator; } fi.fileName = idName; fi.directory = idDir; // place metadata key/value pairs in ImageJ's info field String metadata = getMetadataString(r.getMetadata(), " = "); long startTime = System.currentTimeMillis(); long time = startTime; ImageStack stackB = null; // for byte images (8-bit) ImageStack stackS = null; // for short images (16-bit) ImageStack stackF = null; // for floating point images (32-bit) ImageStack stackO = null; // for all other images (24-bit RGB) int w = cropOnImport ? cropOptions[i].width : r.getSizeX(); int h = cropOnImport ? cropOptions[i].height : r.getSizeY(); int c = r.getRGBChannelCount(); int type = r.getPixelType(); int q = 0; stackOrder = options.getStackOrder(); if (stackOrder.equals(ImporterOptions.ORDER_DEFAULT)) { stackOrder = r.getDimensionOrder(); } ((DimensionSwapper) r).setOutputOrder(stackOrder); omexmlMeta.setPixelsDimensionOrder(stackOrder, i, 0); // dump OME-XML to ImageJ's description field, if available fi.description = MetadataTools.getOMEXML(omexmlMeta); if (options.isVirtual()) { int cSize = r.getSizeC(); int pt = r.getPixelType(); boolean doMerge = options.isMergeChannels(); boolean eight = pt != FormatTools.UINT8 && pt != FormatTools.INT8; boolean needComposite = doMerge && (cSize > 3 || eight); int merge = (needComposite || !doMerge) ? 1 : cSize; // NB: BFVirtualStack extends VirtualStack, which only exists in // ImageJ v1.39+. We avoid referencing it directly to keep the // class loader happy for earlier versions of ImageJ. try { ReflectedUniverse ru = new ReflectedUniverse(); ru.exec("import loci.plugins.util.BFVirtualStack"); ru.setVar("id", id); ru.setVar("r", r); ru.setVar("colorize", colorize); ru.setVar("merge", doMerge); ru.setVar("record", options.isRecord()); stackB = (ImageStack) ru.exec("stackB = new BFVirtualStack(id, " + "r, colorize, merge, record)"); if (doMerge) { cCount[i] = 1; for (int j=0; j<num[i]; j++) { int[] pos = r.getZCTCoords(j); if (pos[1] > 0) continue; String label = constructSliceLabel( new ChannelMerger(r).getIndex(pos[0], pos[1], pos[2]), r, omexmlMeta, i, zCount, cCount, tCount); ru.setVar("label", label); ru.exec("stackB.addSlice(label)"); } } else { for (int j=0; j<num[i]; j++) { String label = constructSliceLabel(j, r, omexmlMeta, i, zCount, cCount, tCount); ru.setVar("label", label); ru.exec("stackB.addSlice(label)"); } } } catch (ReflectException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem constructing the virtual stack"); return; } } else { if (r.isIndexed()) colorModels = new IndexColorModel[r.getSizeC()]; for (int j=0; j<num[i]; j++) { if (!load[j]) continue; // limit message update rate long clock = System.currentTimeMillis(); if (clock - time >= 100) { IJ.showStatus("Reading " + (seriesCount > 1 ? ("series " + (i + 1) + ", ") : "") + "plane " + (j + 1) + "/" + num[i]); time = clock; } IJ.showProgress((double) q++ / total); int ndx = j; String label = constructSliceLabel(ndx, r, omexmlMeta, i, zCount, cCount, tCount); // get image processor for jth plane ImageProcessor ip = Util.openProcessors(r, ndx, cropOptions[i])[0]; if (ip == null) { plugin.canceled = true; return; } int channel = r.getZCTCoords(ndx)[1]; if (colorModels != null) { colorModels[channel] = (IndexColorModel) ip.getColorModel(); } // add plane to image stack if (ip instanceof ByteProcessor) { if (stackB == null) stackB = new ImageStack(w, h); stackB.addSlice(label, ip); } else if (ip instanceof ShortProcessor) { if (stackS == null) stackS = new ImageStack(w, h); stackS.addSlice(label, ip); } else if (ip instanceof FloatProcessor) { // merge image plane into existing stack if possible if (stackB != null) { ip = ip.convertToByte(true); stackB.addSlice(label, ip); } else if (stackS != null) { ip = ip.convertToShort(true); stackS.addSlice(label, ip); } else { if (stackF == null) stackF = new ImageStack(w, h); stackF.addSlice(label, ip); } } else if (ip instanceof ColorProcessor) { if (stackO == null) stackO = new ImageStack(w, h); stackO.addSlice(label, ip); } } } IJ.showStatus("Creating image"); IJ.showProgress(1); String seriesName = omexmlMeta.getImageName(i); showStack(stackB, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackS, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackF, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); showStack(stackO, currentFile, seriesName, omexmlMeta, cCount[i], zCount[i], tCount[i], sizeZ[i], sizeC[i], sizeT[i], fi, r, options, metadata, windowless); long endTime = System.currentTimeMillis(); double elapsed = (endTime - startTime) / 1000.0; if (num[i] == 1) { IJ.showStatus("Bio-Formats: " + elapsed + " seconds"); } else { long average = (endTime - startTime) / num[i]; IJ.showStatus("Bio-Formats: " + elapsed + " seconds (" + average + " ms per plane)"); } } if (concatenate) { Vector widths = new Vector(); Vector heights = new Vector(); Vector types = new Vector(); Vector newImps = new Vector(); for (int j=0; j<imps.size(); j++) { ImagePlus imp = (ImagePlus) imps.get(j); int wj = imp.getWidth(); int hj = imp.getHeight(); int tj = imp.getBitDepth(); boolean append = false; for (int k=0; k<widths.size(); k++) { int wk = ((Integer) widths.get(k)).intValue(); int hk = ((Integer) heights.get(k)).intValue(); int tk = ((Integer) types.get(k)).intValue(); if (wj == wk && hj == hk && tj == tk) { ImagePlus oldImp = (ImagePlus) newImps.get(k); ImageStack is = oldImp.getStack(); ImageStack newStack = imp.getStack(); for (int s=0; s<newStack.getSize(); s++) { is.addSlice(newStack.getSliceLabel(s + 1), newStack.getProcessor(s + 1)); } oldImp.setStack(oldImp.getTitle(), is); newImps.setElementAt(oldImp, k); append = true; k = widths.size(); } } if (!append) { widths.add(new Integer(wj)); heights.add(new Integer(hj)); types.add(new Integer(tj)); newImps.add(imp); } } boolean splitC = options.isSplitChannels(); boolean splitZ = options.isSplitFocalPlanes(); boolean splitT = options.isSplitTimepoints(); for (int j=0; j<newImps.size(); j++) { ImagePlus imp = (ImagePlus) newImps.get(j); imp.show(); if (splitC || splitZ || splitT) { IJ.runPlugIn("loci.plugins.Slicer", "slice_z=" + splitZ + " slice_c=" + splitC + " slice_t=" + splitT + " stack_order=" + stackOrder + " keep_original=false " + "hyper_stack=" + options.isViewHyperstack() + " "); } } } // display ROIs, if necessary if (options.showROIs()) { debug("display ROIs"); ROIHandler.openROIs(omexmlMeta, (ImagePlus[]) imps.toArray(new ImagePlus[0])); } else debug("skip ROIs"); // -- Step 5: finish up -- debug("finish up"); try { if (!options.isVirtual()) r.close(); } catch (IOException exc) { reportException(exc, options.isQuiet(), "Sorry, there was a problem closing the file"); } plugin.success = true; } catch (FormatException exc) { reportException(exc, quiet, "Sorry, there was a problem reading the data."); } catch (IOException exc) { reportException(exc, quiet, "Sorry, there was an I/O problem reading the data."); } }
diff --git a/src/fi/helsinki/cs/scheduler3000/cli/NewEvent.java b/src/fi/helsinki/cs/scheduler3000/cli/NewEvent.java index 8e047f5..f9e7ce3 100644 --- a/src/fi/helsinki/cs/scheduler3000/cli/NewEvent.java +++ b/src/fi/helsinki/cs/scheduler3000/cli/NewEvent.java @@ -1,74 +1,78 @@ package fi.helsinki.cs.scheduler3000.cli; import fi.helsinki.cs.scheduler3000.model.Event; import fi.helsinki.cs.scheduler3000.model.Schedule; import fi.helsinki.cs.scheduler3000.model.Weekday.Day; public class NewEvent extends CliCommand { NewEvent(Schedule schedule) { this.schedule = schedule; } void run() { newEventDialog(); } private void newEventDialog() { int startTime = -1; int endTime = -1; String location, title, eventDayTemp; Day eventDay = null; // validate user input in place while( eventDay == null ) { System.out.println("Which day is the event?"); Helpers.printDates(); printPrompt(); eventDayTemp = input.nextLine(); if (eventDayTemp.equals(endCommand)){ return; } - eventDay = Helpers.getDay(eventDayTemp); + try { + eventDay = Helpers.getDay(eventDayTemp); + } catch (Exception e) { + System.out.println("Invalid date. Try again, please"); + } } while( !Event.isValidStartTime( startTime ) ) { System.out.println("What is the start time?"); printPrompt(); startTime = Integer.parseInt( input.nextLine() ); } while( !Event.isValidEndTime( startTime, endTime ) ) { System.out.println("What is the end time?"); printPrompt(); endTime = Integer.parseInt( input.nextLine() ); } System.out.println("What this event should be named as?"); System.out.println("(just press enter to skip this)"); printPrompt(); title = input.nextLine(); System.out.println("Where this event is held?"); System.out.println("(just press enter to skip this)"); printPrompt(); location = input.nextLine(); System.out.print("Adding event to schedule..."); this.execute(eventDay, title, location, startTime, endTime); System.out.println("ok!"); } private void execute(Day day, String title, String location, int startTime, int endTime) { Event event = new Event(day, title, location, startTime, endTime); schedule.addEvent(event); } }
true
true
private void newEventDialog() { int startTime = -1; int endTime = -1; String location, title, eventDayTemp; Day eventDay = null; // validate user input in place while( eventDay == null ) { System.out.println("Which day is the event?"); Helpers.printDates(); printPrompt(); eventDayTemp = input.nextLine(); if (eventDayTemp.equals(endCommand)){ return; } eventDay = Helpers.getDay(eventDayTemp); } while( !Event.isValidStartTime( startTime ) ) { System.out.println("What is the start time?"); printPrompt(); startTime = Integer.parseInt( input.nextLine() ); } while( !Event.isValidEndTime( startTime, endTime ) ) { System.out.println("What is the end time?"); printPrompt(); endTime = Integer.parseInt( input.nextLine() ); } System.out.println("What this event should be named as?"); System.out.println("(just press enter to skip this)"); printPrompt(); title = input.nextLine(); System.out.println("Where this event is held?"); System.out.println("(just press enter to skip this)"); printPrompt(); location = input.nextLine(); System.out.print("Adding event to schedule..."); this.execute(eventDay, title, location, startTime, endTime); System.out.println("ok!"); }
private void newEventDialog() { int startTime = -1; int endTime = -1; String location, title, eventDayTemp; Day eventDay = null; // validate user input in place while( eventDay == null ) { System.out.println("Which day is the event?"); Helpers.printDates(); printPrompt(); eventDayTemp = input.nextLine(); if (eventDayTemp.equals(endCommand)){ return; } try { eventDay = Helpers.getDay(eventDayTemp); } catch (Exception e) { System.out.println("Invalid date. Try again, please"); } } while( !Event.isValidStartTime( startTime ) ) { System.out.println("What is the start time?"); printPrompt(); startTime = Integer.parseInt( input.nextLine() ); } while( !Event.isValidEndTime( startTime, endTime ) ) { System.out.println("What is the end time?"); printPrompt(); endTime = Integer.parseInt( input.nextLine() ); } System.out.println("What this event should be named as?"); System.out.println("(just press enter to skip this)"); printPrompt(); title = input.nextLine(); System.out.println("Where this event is held?"); System.out.println("(just press enter to skip this)"); printPrompt(); location = input.nextLine(); System.out.print("Adding event to schedule..."); this.execute(eventDay, title, location, startTime, endTime); System.out.println("ok!"); }