repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/ExternalDependentResource.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/ExternalDependentResource.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; public class ExternalDependentResource extends KubernetesDependentResource<External, Third> { public ExternalDependentResource() { super(External.class); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/DuplicatedBundleNameWithoutSharedCSVMetadata1.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/DuplicatedBundleNameWithoutSharedCSVMetadata1.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.openshift.api.model.Role; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; @CSVMetadata(bundleName = "illegal") public class DuplicatedBundleNameWithoutSharedCSVMetadata1 implements Reconciler<Role> { @Override public UpdateControl<Role> reconcile(Role role, Context<Role> context) { return null; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/DuplicatedBundleNameWithoutSharedCSVMetadata2.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/DuplicatedBundleNameWithoutSharedCSVMetadata2.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.openshift.api.model.RoleBinding; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; @CSVMetadata(bundleName = "illegal") public class DuplicatedBundleNameWithoutSharedCSVMetadata2 implements Reconciler<RoleBinding> { @Override public UpdateControl<RoleBinding> reconcile(RoleBinding roleBinding, Context<RoleBinding> context) { return null; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/ReconcilerWithNoCsvMetadata.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/ReconcilerWithNoCsvMetadata.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; public class ReconcilerWithNoCsvMetadata implements Reconciler<First> { @Override public UpdateControl<First> reconcile(First request, Context<First> context) { return UpdateControl.noUpdate(); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/AReconciler.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/AReconciler.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.kubernetes.api.model.ConfigMap; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; import io.quarkiverse.operatorsdk.annotations.SharedCSVMetadata; @CSVMetadata(bundleName = AReconciler.SHARED, version = AReconciler.SHARED_VERSION) public class AReconciler implements Reconciler<ConfigMap>, SharedCSVMetadata { public static final String SHARED_VERSION = "0.0.1"; public static final String SHARED = "shared"; @Override public UpdateControl<ConfigMap> reconcile(ConfigMap configMap, Context<ConfigMap> context) { return null; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/SecondExternal.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/SecondExternal.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Kind; import io.fabric8.kubernetes.model.annotation.Version; @Group(SecondExternal.GROUP) @Version(SecondExternal.VERSION) @Kind(SecondExternal.KIND) public class SecondExternal extends CustomResource<Void, Void> { public static final String GROUP = "halkyon.io"; public static final String VERSION = "v1alpha1"; public static final String KIND = "ExternalAgain"; }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/External.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/External.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Version; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; @Group("halkyon.io") @Version("v1alpha1") @CSVMetadata(displayName = External.DISPLAY_NAME, description = External.DESCRIPTION) public class External extends CustomResource<Void, Void> { public static final String DISPLAY_NAME = "External display name"; public static final String DESCRIPTION = "External description"; }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/PodDependentResource.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/PodDependentResource.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.kubernetes.api.model.Pod; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; public class PodDependentResource extends KubernetesDependentResource<Pod, Third> { public PodDependentResource() { super(Pod.class); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/CReconciler.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/CReconciler.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; public class CReconciler implements Reconciler<ServiceAccount> { @Override public UpdateControl<ServiceAccount> reconcile(ServiceAccount serviceAccount, Context<ServiceAccount> context) throws Exception { return null; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/First.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/First.java
package io.quarkiverse.operatorsdk.bundle.sources; import com.fasterxml.jackson.annotation.JsonInclude; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Version; @Group("samples.javaoperatorsdk.io") @Version("v1alpha1") @JsonInclude(JsonInclude.Include.NON_NULL) public class First extends CustomResource<Void, Void> implements Namespaced { public First() { } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/Third.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/Third.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Version; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; @Group("samples.javaoperatorsdk.io") @Version("v1alpha1") @CSVMetadata(displayName = Third.DISPLAY, description = Third.DESCRIPTION) public class Third extends CustomResource<Void, Void> implements Namespaced { public static final String DESCRIPTION = "Third description"; public static final String DISPLAY = "Third display"; }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/OptionalImplicitNativeDependent.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/OptionalImplicitNativeDependent.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.kubernetes.api.model.Secret; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.dependent.DependentResource; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.javaoperatorsdk.operator.processing.dependent.workflow.CRDPresentActivationCondition; public class OptionalImplicitNativeDependent extends KubernetesDependentResource<Secret, Third> { public static class ActivationCondition extends CRDPresentActivationCondition<Secret, Third> { @Override public boolean isMet(DependentResource<Secret, Third> dependentResource, Third primary, Context<Third> context) { return false; } } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/FirstReconciler.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/FirstReconciler.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; @CSVMetadata(bundleName = "first-operator", version = FirstReconciler.VERSION) public class FirstReconciler implements Reconciler<First> { public static final String VERSION = "first-version"; public static final String REPLACES = "first-replaces"; @Override public UpdateControl<First> reconcile(First request, Context<First> context) { return UpdateControl.noUpdate(); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/Second.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/Second.java
package io.quarkiverse.operatorsdk.bundle.sources; import com.fasterxml.jackson.annotation.JsonInclude; import io.fabric8.kubernetes.api.model.Namespaced; import io.fabric8.kubernetes.client.CustomResource; import io.fabric8.kubernetes.model.annotation.Group; import io.fabric8.kubernetes.model.annotation.Version; @Group("samples.javaoperatorsdk.io") @Version("v1alpha1") @JsonInclude(JsonInclude.Include.NON_NULL) public class Second extends CustomResource<Void, Void> implements Namespaced { public Second() { } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/OptionalExplicitNativeDependent.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/OptionalExplicitNativeDependent.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.fabric8.openshift.api.model.monitoring.v1.ServiceMonitor; import io.javaoperatorsdk.operator.processing.dependent.kubernetes.KubernetesDependentResource; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; @CSVMetadata.Optional public class OptionalExplicitNativeDependent extends KubernetesDependentResource<ServiceMonitor, Third> { }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/ReconcilerWithExternalCR.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/ReconcilerWithExternalCR.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.javaoperatorsdk.operator.api.reconciler.Workflow; import io.javaoperatorsdk.operator.api.reconciler.dependent.Dependent; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; @Workflow(dependents = @Dependent(type = ExternalDependentResource.class)) @CSVMetadata(requiredCRDs = @CSVMetadata.RequiredCRD(kind = V1Beta1CRD.KIND, name = V1Beta1CRD.CR_NAME, version = V1Beta1CRD.VERSION)) public class ReconcilerWithExternalCR implements Reconciler<First> { @Override public UpdateControl<First> reconcile(First first, Context<First> context) throws Exception { return null; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/SecondReconciler.java
bundle-generator/deployment/src/test/java/io/quarkiverse/operatorsdk/bundle/sources/SecondReconciler.java
package io.quarkiverse.operatorsdk.bundle.sources; import io.javaoperatorsdk.operator.api.config.informer.Informer; import io.javaoperatorsdk.operator.api.reconciler.Context; import io.javaoperatorsdk.operator.api.reconciler.ControllerConfiguration; import io.javaoperatorsdk.operator.api.reconciler.Reconciler; import io.javaoperatorsdk.operator.api.reconciler.UpdateControl; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; import io.quarkiverse.operatorsdk.annotations.RBACRule; @CSVMetadata(bundleName = "second-operator") @RBACRule(apiGroups = SecondReconciler.RBAC_RULE_GROUP, resources = SecondReconciler.RBAC_RULE_RES, verbs = SecondReconciler.RBAC_RULE_VERBS) @ControllerConfiguration(informer = @Informer(namespaces = "foo")) public class SecondReconciler implements Reconciler<Second> { public static final String RBAC_RULE_GROUP = "halkyon.io"; public static final String RBAC_RULE_RES = "SomeResource"; public static final String RBAC_RULE_VERBS = "write"; @Override public UpdateControl<Second> reconcile(Second request, Context<Second> context) { return UpdateControl.noUpdate(); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/GeneratedBundleBuildItem.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/GeneratedBundleBuildItem.java
package io.quarkiverse.operatorsdk.bundle.deployment; import io.quarkus.builder.item.SimpleBuildItem; public final class GeneratedBundleBuildItem extends SimpleBuildItem { }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/BundleProcessor.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/BundleProcessor.java
package io.quarkiverse.operatorsdk.bundle.deployment; import static io.quarkiverse.operatorsdk.annotations.RBACVerbs.ALL_COMMON_VERBS; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.BooleanSupplier; import org.jboss.jandex.AnnotationInstance; import org.jboss.jandex.AnnotationValue; import org.jboss.jandex.DotName; import org.jboss.jandex.IndexView; import org.jboss.logging.Logger; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.rbac.ClusterRole; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.quarkiverse.operatorsdk.annotations.CSVMetadata; import io.quarkiverse.operatorsdk.annotations.SharedCSVMetadata; import io.quarkiverse.operatorsdk.bundle.runtime.BundleConfiguration; import io.quarkiverse.operatorsdk.bundle.runtime.BundleGenerationConfiguration; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; import io.quarkiverse.operatorsdk.common.ClassUtils; import io.quarkiverse.operatorsdk.common.ConfigurationUtils; import io.quarkiverse.operatorsdk.common.DeserializedKubernetesResourcesBuildItem; import io.quarkiverse.operatorsdk.common.ReconciledAugmentedClassInfo; import io.quarkiverse.operatorsdk.common.ReconcilerAugmentedClassInfo; import io.quarkiverse.operatorsdk.deployment.GeneratedCRDInfoBuildItem; import io.quarkiverse.operatorsdk.deployment.UnownedCRDInfoBuildItem; import io.quarkiverse.operatorsdk.deployment.VersionBuildItem; import io.quarkiverse.operatorsdk.runtime.BuildTimeOperatorConfiguration; import io.quarkus.deployment.annotations.BuildProducer; import io.quarkus.deployment.annotations.BuildStep; import io.quarkus.deployment.builditem.ApplicationInfoBuildItem; import io.quarkus.deployment.builditem.CombinedIndexBuildItem; import io.quarkus.deployment.builditem.GeneratedFileSystemResourceBuildItem; import io.quarkus.deployment.pkg.builditem.JarBuildItem; import io.quarkus.deployment.pkg.builditem.OutputTargetBuildItem; import io.quarkus.kubernetes.deployment.KubernetesConfig; import io.quarkus.kubernetes.deployment.ResourceNameUtil; public class BundleProcessor { public static final String CRD_DISPLAY_NAME = "CRD_DISPLAY_NAME"; public static final String CRD_DESCRIPTION = "CRD_DESCRIPTION"; private static final Logger log = Logger.getLogger(BundleProcessor.class); private static final DotName SHARED_CSV_METADATA = DotName.createSimple(SharedCSVMetadata.class.getName()); private static final DotName CSV_METADATA = DotName.createSimple(CSVMetadata.class.getName()); private static final String BUNDLE = "bundle"; private static final String DEFAULT_PROVIDER_NAME = System.getProperty("user.name"); private static ReconcilerAugmentedClassInfo augmentReconcilerInfo( ReconcilerAugmentedClassInfo reconcilerInfo) { // if primary resource is a CR, check if it is annotated with CSVMetadata and augment it if it is final ReconciledAugmentedClassInfo<?> primaryCI = reconcilerInfo.associatedResourceInfo(); augmentResourceInfoIfCR(primaryCI); reconcilerInfo.getDependentResourceInfos().forEach(draci -> { // if the dependent is a CR, check if it is annotated with CSVMetadata and augment it if it is final ReconciledAugmentedClassInfo<?> reconciledAugmentedClassInfo = draci.associatedResourceInfo(); augmentResourceInfoIfCR(reconciledAugmentedClassInfo); }); return reconcilerInfo; } private static void augmentResourceInfoIfCR(ReconciledAugmentedClassInfo<?> reconciledAugmentedClassInfo) { if (reconciledAugmentedClassInfo.isCR()) { final var csvMetadata = reconciledAugmentedClassInfo.classInfo().annotation(CSV_METADATA); if (csvMetadata != null) { // extract display name and description final var displayName = ConfigurationUtils.annotationValueOrDefault(csvMetadata, "displayName", AnnotationValue::asString, () -> reconciledAugmentedClassInfo.asResourceTargeting().kind()); reconciledAugmentedClassInfo.setExtendedInfo(CRD_DISPLAY_NAME, displayName); final var description = ConfigurationUtils.annotationValueOrDefault( csvMetadata, "description", AnnotationValue::asString, () -> null); if (description != null) { reconciledAugmentedClassInfo.setExtendedInfo(CRD_DESCRIPTION, description); } } } } private static String getBundleName(AnnotationInstance csvMetadata, String defaultName) { if (csvMetadata == null) { return defaultName; } else { final var bundleName = csvMetadata.value("bundleName"); if (bundleName != null) { return bundleName.asString(); } else { return Optional.ofNullable(csvMetadata.value("name")) .map(AnnotationValue::asString) .orElse(defaultName); } } } @SuppressWarnings({ "unused" }) @BuildStep(onlyIf = IsGenerationEnabled.class) CSVMetadataBuildItem gatherCSVMetadata(KubernetesConfig kubernetesConfig, ApplicationInfoBuildItem appConfiguration, BundleGenerationConfiguration bundleConfiguration, CombinedIndexBuildItem combinedIndexBuildItem, JarBuildItem jarBuildItem) { final var index = combinedIndexBuildItem.getIndex(); final var defaultName = ResourceNameUtil.getResourceName(kubernetesConfig, appConfiguration); // note that version, replaces, etc. should probably be settable at the reconciler level // use version specified in bundle configuration, if not use the one extracted from the project, if available final var version = kubernetesConfig.version().orElse(appConfiguration.getVersion()); final var defaultVersion = bundleConfiguration.version() .orElse(ApplicationInfoBuildItem.UNSET_VALUE.equals(version) ? null : version); final var defaultReplaces = bundleConfiguration.replaces().orElse(null); final var bundleConfigs = bundleConfiguration.bundles(); final var defaultBundleConfig = bundleConfigs.get(BundleGenerationConfiguration.DEFAULT_BUNDLE_NAME); final var sharedMetadataHolders = getSharedMetadataHolders(defaultName, defaultVersion, defaultReplaces, defaultBundleConfig, index); final var csvGroups = new HashMap<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>>(); ClassUtils.getKnownReconcilers(index, log) .forEach(reconcilerInfo -> { // figure out which group should be used to generate CSV final var name = reconcilerInfo.nameOrFailIfUnset(); log.debugf("Processing reconciler: %s", name); // Check whether the reconciler must be shipped using a custom bundle final var csvMetadataAnnotation = reconcilerInfo.classInfo() .declaredAnnotation(CSV_METADATA); final var sharedMetadataName = getBundleName(csvMetadataAnnotation, defaultName); final var isNameInferred = defaultName.equals(sharedMetadataName); var csvMetadata = sharedMetadataHolders.get(sharedMetadataName); if (csvMetadata == null) { final var origin = reconcilerInfo.classInfo().name().toString(); if (!sharedMetadataName.equals(defaultName)) { final var maybeExistingOrigin = csvGroups.keySet().stream() .filter(mh -> mh.bundleName.equals(sharedMetadataName)) .map(CSVMetadataHolder::getOrigin) .findFirst(); if (maybeExistingOrigin.isPresent()) { throw new IllegalStateException("Reconcilers '" + maybeExistingOrigin.get() + "' and '" + origin + "' are using the same bundle name '" + sharedMetadataName + "' but no SharedCSVMetadata implementation with that name exists. Please create a SharedCSVMetadata with that name to have one single source of truth and reference it via CSVMetadata annotations using that name on your reconcilers."); } } // merge default bundle configuration with more specific one if they exist var bundleConfig = bundleConfigs.get(sharedMetadataName); if (bundleConfig != null) { bundleConfig.mergeWithDefaults(defaultBundleConfig); } else { bundleConfig = defaultBundleConfig; } csvMetadata = createMetadataHolder(csvMetadataAnnotation, new CSVMetadataHolder(sharedMetadataName, defaultVersion, defaultReplaces, DEFAULT_PROVIDER_NAME, origin), bundleConfig, origin); if (DEFAULT_PROVIDER_NAME.equals(csvMetadata.providerName)) { log.warnf( "It is recommended that you provide a provider name provided for %s: '%s' was used as default value.", origin, DEFAULT_PROVIDER_NAME); } } log.infof("Assigning '%s' reconciler to %s", reconcilerInfo.nameOrFailIfUnset(), getMetadataOriginInformation(csvMetadataAnnotation, isNameInferred, csvMetadata)); csvGroups.computeIfAbsent(csvMetadata, m -> new ArrayList<>()).add( augmentReconcilerInfo(reconcilerInfo)); }); return new CSVMetadataBuildItem(csvGroups); } private String getMetadataOriginInformation(AnnotationInstance csvMetadataAnnotation, boolean isNameInferred, CSVMetadataHolder metadataHolder) { final var isDefault = csvMetadataAnnotation == null; final var actualName = metadataHolder.bundleName; if (isDefault) { return "default bundle automatically named '" + actualName + "'"; } else { return "bundle " + (isNameInferred ? "automatically " : "") + "named '" + actualName + "' defined by '" + metadataHolder.getOrigin() + "'"; } } @SuppressWarnings("unused") @BuildStep(onlyIf = IsGenerationEnabled.class) void generateBundle(ApplicationInfoBuildItem configuration, KubernetesConfig kubernetesConfig, BundleGenerationConfiguration bundleConfiguration, BuildTimeOperatorConfiguration operatorConfiguration, OutputTargetBuildItem outputTarget, CSVMetadataBuildItem csvMetadata, UnownedCRDInfoBuildItem unownedCRDs, VersionBuildItem versionBuildItem, BuildProducer<GeneratedBundleBuildItem> doneGeneratingCSV, GeneratedCRDInfoBuildItem generatedCustomResourcesDefinitions, @SuppressWarnings("OptionalUsedAsFieldOrParameterType") Optional<DeserializedKubernetesResourcesBuildItem> maybeGeneratedKubeResources, BuildProducer<GeneratedFileSystemResourceBuildItem> generatedCSVs) { final var outputDir = outputTarget.getOutputDirectory().resolve(BUNDLE); final var serviceAccounts = new LinkedList<ServiceAccount>(); final var clusterRoleBindings = new LinkedList<ClusterRoleBinding>(); final var clusterRoles = new LinkedList<ClusterRole>(); final var roleBindings = new LinkedList<RoleBinding>(); final var roles = new LinkedList<Role>(); final var deployments = new LinkedList<Deployment>(); maybeGeneratedKubeResources.ifPresent(generatedKubeResources -> { final var resources = generatedKubeResources.getResources(); resources.forEach(r -> { if (r instanceof ServiceAccount) { serviceAccounts.add((ServiceAccount) r); return; } if (r instanceof ClusterRoleBinding) { clusterRoleBindings.add((ClusterRoleBinding) r); return; } if (r instanceof ClusterRole) { clusterRoles.add((ClusterRole) r); return; } if (r instanceof RoleBinding) { roleBindings.add((RoleBinding) r); return; } if (r instanceof Role) { roles.add((Role) r); return; } if (r instanceof Deployment) { deployments.add((Deployment) r); } }); }); final var deploymentName = ResourceNameUtil.getResourceName(kubernetesConfig, configuration); final var generated = BundleGenerator.prepareGeneration(bundleConfiguration, operatorConfiguration, versionBuildItem.getVersion(), csvMetadata.getCsvGroups(), generatedCustomResourcesDefinitions.getCRDGenerationInfo(), unownedCRDs.getCRDs(), outputTarget.getOutputDirectory(), deploymentName); generated.forEach(manifestBuilder -> { final var fileName = manifestBuilder.getFileName(); final var name = manifestBuilder.getName(); try { generatedCSVs.produce( new GeneratedFileSystemResourceBuildItem( Path.of(BUNDLE).resolve(name).resolve(fileName).toString(), manifestBuilder.getManifestData(serviceAccounts, clusterRoleBindings, clusterRoles, roleBindings, roles, deployments))); log.infof("Processing %s for '%s' controller -> %s", manifestBuilder.getManifestType(), name, outputDir.resolve(name).resolve(fileName)); } catch (IOException e) { log.errorf("Cannot process %s for '%s' controller: %s", manifestBuilder.getManifestType(), name, e.getMessage()); } }); doneGeneratingCSV.produce(new GeneratedBundleBuildItem()); } private Map<String, CSVMetadataHolder> getSharedMetadataHolders(String name, String version, String defaultReplaces, BundleConfiguration defaultBundleConfig, IndexView index) { CSVMetadataHolder csvMetadata = new CSVMetadataHolder(name, version, defaultReplaces, DEFAULT_PROVIDER_NAME, "default"); final var sharedMetadataImpls = index.getAllKnownImplementations(SHARED_CSV_METADATA); final var result = new HashMap<String, CSVMetadataHolder>(sharedMetadataImpls.size() + 1); sharedMetadataImpls.forEach(sharedMetadataImpl -> { final var csvMetadataAnn = sharedMetadataImpl.declaredAnnotation(CSV_METADATA); if (csvMetadataAnn != null) { final var origin = sharedMetadataImpl.name().toString(); final var metadataHolder = createMetadataHolder(csvMetadataAnn, csvMetadata, defaultBundleConfig, origin); final var existing = result.get(metadataHolder.bundleName); if (existing != null) { throw new IllegalStateException( "Only one SharedCSVMetadata named " + metadataHolder.bundleName + " can be defined. Was defined on (at least): " + existing.getOrigin() + " and " + origin); } result.put(metadataHolder.bundleName, metadataHolder); } }); return result; } private CSVMetadataHolder createMetadataHolder(AnnotationInstance csvMetadata, CSVMetadataHolder mh, BundleConfiguration bundleConfig, String origin) { if (csvMetadata == null) { return mh; } final var providerField = csvMetadata.value("provider"); String providerName = mh.providerName; String providerURL = mh.providerURL; if (providerField != null) { final var provider = providerField.asNested(); providerName = ConfigurationUtils.annotationValueOrDefault(provider, "name", AnnotationValue::asString, () -> mh.providerName); providerURL = ConfigurationUtils.annotationValueOrDefault(provider, "url", AnnotationValue::asString, () -> mh.providerURL); } final var annotationsField = csvMetadata.value("annotations"); CSVMetadataHolder.Annotations annotations; if (annotationsField != null) { final var annotationsAnn = annotationsField.asNested(); Map<String, String> others = extractNameValueMap(annotationsAnn.value("others")); annotations = new CSVMetadataHolder.Annotations( ConfigurationUtils.annotationValueOrDefault(annotationsAnn, "containerImage", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(annotationsAnn, "repository", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(annotationsAnn, "capabilities", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(annotationsAnn, "categories", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(annotationsAnn, "certified", AnnotationValue::asBoolean, () -> false), ConfigurationUtils.annotationValueOrDefault(annotationsAnn, "almExamples", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(annotationsAnn, "skipRange", AnnotationValue::asString, () -> null), others); } else { annotations = mh.annotations; } if (bundleConfig != null) { annotations = CSVMetadataHolder.Annotations.override(annotations, bundleConfig.annotations()); } Map<String, String> labels = extractNameValueMap(csvMetadata.value("labels")); final var maintainersField = csvMetadata.value("maintainers"); CSVMetadataHolder.Maintainer[] maintainers; if (maintainersField != null) { final var maintainersAnn = maintainersField.asNestedArray(); maintainers = new CSVMetadataHolder.Maintainer[maintainersAnn.length]; for (int i = 0; i < maintainersAnn.length; i++) { maintainers[i] = new CSVMetadataHolder.Maintainer( ConfigurationUtils.annotationValueOrDefault(maintainersAnn[i], "name", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(maintainersAnn[i], "email", AnnotationValue::asString, () -> null)); } } else { maintainers = mh.maintainers; } final var linksField = csvMetadata.value("links"); CSVMetadataHolder.Link[] links; if (linksField != null) { final var linkAnn = linksField.asNestedArray(); links = new CSVMetadataHolder.Link[linkAnn.length]; for (int i = 0; i < linkAnn.length; i++) { links[i] = new CSVMetadataHolder.Link( ConfigurationUtils.annotationValueOrDefault(linkAnn[i], "name", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(linkAnn[i], "url", AnnotationValue::asString, () -> null)); } } else { links = mh.links; } final var iconField = csvMetadata.value("icon"); CSVMetadataHolder.Icon[] icon; if (iconField != null) { final var iconAnn = iconField.asNestedArray(); icon = new CSVMetadataHolder.Icon[iconAnn.length]; for (int i = 0; i < iconAnn.length; i++) { icon[i] = new CSVMetadataHolder.Icon( ConfigurationUtils.annotationValueOrDefault(iconAnn[i], "fileName", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(iconAnn[i], "mediatype", AnnotationValue::asString, () -> CSVMetadata.Icon.DEFAULT_MEDIA_TYPE)); } } else { icon = mh.icon; } final var installModesField = csvMetadata.value("installModes"); CSVMetadataHolder.InstallMode[] installModes; if (installModesField != null) { final var installModesAnn = installModesField.asNestedArray(); installModes = new CSVMetadataHolder.InstallMode[installModesAnn.length]; for (int i = 0; i < installModesAnn.length; i++) { installModes[i] = new CSVMetadataHolder.InstallMode( ConfigurationUtils.annotationValueOrDefault(installModesAnn[i], "type", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(installModesAnn[i], "supported", AnnotationValue::asBoolean, () -> true)); } } else { installModes = mh.installModes; } final var permissionsField = csvMetadata.value("permissionRules"); CSVMetadataHolder.PermissionRule[] permissionRules; if (permissionsField != null) { final var permissionsAnn = permissionsField.asNestedArray(); permissionRules = new CSVMetadataHolder.PermissionRule[permissionsAnn.length]; for (int i = 0; i < permissionsAnn.length; i++) { permissionRules[i] = new CSVMetadataHolder.PermissionRule( ConfigurationUtils.annotationValueOrDefault(permissionsAnn[i], "apiGroups", AnnotationValue::asStringArray, () -> null), ConfigurationUtils.annotationValueOrDefault(permissionsAnn[i], "resources", AnnotationValue::asStringArray, () -> null), ConfigurationUtils.annotationValueOrDefault(permissionsAnn[i], "verbs", AnnotationValue::asStringArray, () -> ALL_COMMON_VERBS), ConfigurationUtils.annotationValueOrDefault(permissionsAnn[i], "serviceAccountName", AnnotationValue::asString, () -> null)); } } else { permissionRules = mh.permissionRules; } final var requiredCRDsField = csvMetadata.value("requiredCRDs"); CSVMetadataHolder.RequiredCRD[] requiredCRDs; if (requiredCRDsField != null) { final var requiredCRDAnn = requiredCRDsField.asNestedArray(); requiredCRDs = new CSVMetadataHolder.RequiredCRD[requiredCRDAnn.length]; for (int i = 0; i < requiredCRDAnn.length; i++) { requiredCRDs[i] = new CSVMetadataHolder.RequiredCRD( ConfigurationUtils.annotationValueOrDefault(requiredCRDAnn[i], "kind", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(requiredCRDAnn[i], "name", AnnotationValue::asString, () -> null), ConfigurationUtils.annotationValueOrDefault(requiredCRDAnn[i], "version", AnnotationValue::asString, () -> null)); } } else { requiredCRDs = mh.requiredCRDs; } return new CSVMetadataHolder( getBundleName(csvMetadata, mh.bundleName), ConfigurationUtils.annotationValueOrDefault(csvMetadata, "csvName", AnnotationValue::asString, () -> mh.csvName), ConfigurationUtils.annotationValueOrDefault(csvMetadata, "description", AnnotationValue::asString, () -> mh.description), ConfigurationUtils.annotationValueOrDefault(csvMetadata, "displayName", AnnotationValue::asString, () -> mh.displayName), annotations, labels, ConfigurationUtils.annotationValueOrDefault(csvMetadata, "keywords", AnnotationValue::asStringArray, () -> mh.keywords), providerName, providerURL, ConfigurationUtils.annotationValueOrDefault(csvMetadata, "replaces", AnnotationValue::asString, () -> mh.replaces), ConfigurationUtils.annotationValueOrDefault(csvMetadata, "skips", AnnotationValue::asStringArray, () -> mh.skips), ConfigurationUtils.annotationValueOrDefault(csvMetadata, "version", AnnotationValue::asString, () -> mh.version), ConfigurationUtils.annotationValueOrDefault(csvMetadata, "maturity", AnnotationValue::asString, () -> mh.maturity), ConfigurationUtils.annotationValueOrDefault(csvMetadata, "minKubeVersion", AnnotationValue::asString, () -> mh.minKubeVersion), maintainers, links, icon, installModes, permissionRules, requiredCRDs, origin); } private static Map<String, String> extractNameValueMap(AnnotationValue annotationValue) { Map<String, String> map; if (annotationValue != null) { final var array = annotationValue.asNestedArray(); map = new HashMap<>(array.length); for (AnnotationInstance instance : array) { map.put(instance.value("name").asString(), instance.value("value").asString()); } } else { map = new HashMap<>(); } return map; } private static class IsGenerationEnabled implements BooleanSupplier { private BundleGenerationConfiguration config; @Override public boolean getAsBoolean() { return config.enabled(); } } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/KubernetesLabelConfigOverrider.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/KubernetesLabelConfigOverrider.java
package io.quarkiverse.operatorsdk.bundle.deployment; import java.util.Map; import io.smallrye.config.PropertiesConfigSource; import io.smallrye.config.SmallRyeConfigBuilder; import io.smallrye.config.SmallRyeConfigBuilderCustomizer; /** * Overrides the default value for the Kubernetes extension-provided {@code add-version-to-label-selectors} when the bundle * generator is used. See <a href="https://github.com/quarkiverse/quarkus-operator-sdk/issues/823">this issue</a> for more * details. */ public class KubernetesLabelConfigOverrider implements SmallRyeConfigBuilderCustomizer { @Override public void configBuilder(SmallRyeConfigBuilder builder) { // not sure what value for the priority should be used since they seem pretty random builder.withSources(new PropertiesConfigSource(Map.of("quarkus.kubernetes.add-version-to-label-selectors", "false"), "KubernetesLabelConfigOverrider", 50)); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/CSVMetadataBuildItem.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/CSVMetadataBuildItem.java
package io.quarkiverse.operatorsdk.bundle.deployment; import java.util.List; import java.util.Map; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; import io.quarkiverse.operatorsdk.common.ReconcilerAugmentedClassInfo; import io.quarkus.builder.item.SimpleBuildItem; public final class CSVMetadataBuildItem extends SimpleBuildItem { private final Map<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> csvGroups; public CSVMetadataBuildItem(Map<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> csvGroups) { this.csvGroups = csvGroups; } public Map<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> getCsvGroups() { return csvGroups; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/BundleGenerator.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/BundleGenerator.java
package io.quarkiverse.operatorsdk.bundle.deployment; import java.nio.file.Path; import java.util.*; import org.jboss.logging.Logger; import io.quarkiverse.operatorsdk.bundle.deployment.builders.AnnotationsManifestsBuilder; import io.quarkiverse.operatorsdk.bundle.deployment.builders.BundleDockerfileManifestsBuilder; import io.quarkiverse.operatorsdk.bundle.deployment.builders.CsvManifestsBuilder; import io.quarkiverse.operatorsdk.bundle.deployment.builders.CustomResourceManifestsBuilder; import io.quarkiverse.operatorsdk.bundle.deployment.builders.ManifestsBuilder; import io.quarkiverse.operatorsdk.bundle.runtime.BundleGenerationConfiguration; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; import io.quarkiverse.operatorsdk.common.ReconcilerAugmentedClassInfo; import io.quarkiverse.operatorsdk.runtime.BuildTimeOperatorConfiguration; import io.quarkiverse.operatorsdk.runtime.CRDGenerationInfo; import io.quarkiverse.operatorsdk.runtime.CRDInfo; import io.quarkiverse.operatorsdk.runtime.CRDInfos; import io.quarkiverse.operatorsdk.runtime.Version; import io.quarkus.container.util.PathsUtil; public class BundleGenerator { private static final Logger log = Logger.getLogger(BundleGenerator.class); public static final String MANIFESTS = "manifests"; private static final String DOT = "."; private static final String COMMA = ","; private static final String DEFAULT = "default"; private static final String METADATA = "metadata"; private static final String SLASH = "/"; private static final String REGISTRY_PLUS = "registry+"; private static final String PACKAGE = "package"; private static final String MEDIA_TYPE = "mediatype"; private static final String CHANNEL = "channel"; private static final String CHANNELS = "channels"; private static final String BUNDLE_PREFIX = "operators.operatorframework.io.bundle"; private static final String METRICS_PREFIX = "operators.operatorframework.io.metrics"; private static final String ANNOTATIONS_VERSION = "v1"; private static final String BUILDER = "builder"; private static final String METRICS_V1 = "metrics+v1"; private static final String PROJECT_LAYOUT = "project_layout"; private static final String LAYOUT_V1_ALPHA = "quarkus.javaoperatorsdk.io/v1-alpha"; private static final String QOSDK = "qosdk-bundle-generator/"; private BundleGenerator() { } public static List<ManifestsBuilder> prepareGeneration(BundleGenerationConfiguration bundleConfiguration, BuildTimeOperatorConfiguration operatorConfiguration, Version version, Map<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> csvGroups, CRDGenerationInfo crds, CRDInfos unownedCRDs, Path outputDirectory, String deploymentName) { List<ManifestsBuilder> builders = new ArrayList<>(); final var mainSourcesRoot = PathsUtil.findMainSourcesRoot(outputDirectory); final var crdNameToInfoMappings = crds.getCrds().getCRDNameToInfoMappings(); for (Map.Entry<CSVMetadataHolder, List<ReconcilerAugmentedClassInfo>> entry : csvGroups.entrySet()) { final var csvMetadata = entry.getKey(); final var labels = generateBundleLabels(csvMetadata, bundleConfiguration, version); final var csvBuilder = new CsvManifestsBuilder(csvMetadata, operatorConfiguration, entry.getValue(), mainSourcesRoot != null ? mainSourcesRoot.getKey() : null, deploymentName); builders.add(csvBuilder); builders.add(new AnnotationsManifestsBuilder(csvMetadata, labels)); builders.add(new BundleDockerfileManifestsBuilder(csvMetadata, labels)); // output owned CRDs in the manifest, fail if we're missing some var missing = addCRDManifestBuilder(crdNameToInfoMappings, builders, csvMetadata, csvBuilder.getOwnedCRs()); if (!missing.isEmpty()) { throw new IllegalStateException( "Missing owned CRD data for resources: " + missing + " for bundle: " + csvMetadata.bundleName); } // output required CRDs in the manifest, output a warning in case we're missing some missing = addCRDManifestBuilder(crdNameToInfoMappings, builders, csvMetadata, csvBuilder.getRequiredCRs()); if (!missing.isEmpty()) { log.warnf("Missing required CRD data for resources: %s for bundle: %s", missing, csvMetadata.bundleName); } // output non-generated CRDs unownedCRDs.getCRDNameToInfoMappings().values() .forEach(info -> builders.add(new CustomResourceManifestsBuilder(csvMetadata, info))); } return builders; } private static HashSet<String> addCRDManifestBuilder(Map<String, CRDInfo> crds, List<ManifestsBuilder> builders, CSVMetadataHolder csvMetadata, Set<String> controllerDefinedCRs) { final var missing = new HashSet<>(controllerDefinedCRs); controllerDefinedCRs.forEach(crdName -> { final var info = crds.get(crdName); if (info != null) { builders.add(new CustomResourceManifestsBuilder(csvMetadata, info)); missing.remove(crdName); } }); return missing; } private static SortedMap<String, String> generateBundleLabels(CSVMetadataHolder csvMetadata, BundleGenerationConfiguration bundleConfiguration, Version version) { var packageName = csvMetadata.bundleName; SortedMap<String, String> values = new TreeMap<>(); values.put(join(BUNDLE_PREFIX, CHANNEL, DEFAULT, ANNOTATIONS_VERSION), bundleConfiguration.defaultChannel().orElse(bundleConfiguration.channels().get(0))); values.put(join(BUNDLE_PREFIX, CHANNELS, ANNOTATIONS_VERSION), String.join(COMMA, bundleConfiguration.channels())); values.put(join(BUNDLE_PREFIX, MANIFESTS, ANNOTATIONS_VERSION), MANIFESTS + SLASH); values.put(join(BUNDLE_PREFIX, MEDIA_TYPE, ANNOTATIONS_VERSION), REGISTRY_PLUS + ANNOTATIONS_VERSION); values.put(join(BUNDLE_PREFIX, METADATA, ANNOTATIONS_VERSION), METADATA + SLASH); values.put(join(BUNDLE_PREFIX, PACKAGE, ANNOTATIONS_VERSION), packageName); values.put(join(METRICS_PREFIX, BUILDER), QOSDK + version.getExtensionVersion() + "+" + version.getExtensionCommit()); values.put(join(METRICS_PREFIX, MEDIA_TYPE, ANNOTATIONS_VERSION), METRICS_V1); values.put(join(METRICS_PREFIX, PROJECT_LAYOUT), LAYOUT_V1_ALPHA); return values; } private static String join(String... elements) { return String.join(DOT, elements); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/ManifestsBuilder.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/ManifestsBuilder.java
package io.quarkiverse.operatorsdk.bundle.deployment.builders; import java.io.IOException; import java.nio.file.Path; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.rbac.ClusterRole; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; public abstract class ManifestsBuilder { protected static final ObjectMapper YAML_MAPPER; static { YAML_MAPPER = new ObjectMapper((new YAMLFactory()).enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) .enable(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS) .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)); YAML_MAPPER.configure(SerializationFeature.INDENT_OUTPUT, true); YAML_MAPPER.setDefaultPropertyInclusion( JsonInclude.Value.construct(JsonInclude.Include.ALWAYS, JsonInclude.Include.NON_NULL)); YAML_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_EMPTY); } protected final CSVMetadataHolder metadata; public ManifestsBuilder(CSVMetadataHolder metadata) { this.metadata = metadata; } public abstract Path getFileName(); public abstract byte[] getManifestData(List<ServiceAccount> serviceAccounts, List<ClusterRoleBinding> clusterRoleBindings, List<ClusterRole> clusterRoles, List<RoleBinding> roleBindings, List<Role> roles, List<Deployment> deployments) throws IOException; public abstract String getManifestType(); public String getName() { return metadata.bundleName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ManifestsBuilder that = (ManifestsBuilder) o; return getFileName().equals(that.getFileName()); } @Override public int hashCode() { return getFileName().hashCode(); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/BundleDockerfileManifestsBuilder.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/BundleDockerfileManifestsBuilder.java
package io.quarkiverse.operatorsdk.bundle.deployment.builders; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.List; import java.util.SortedMap; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.rbac.ClusterRole; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; public class BundleDockerfileManifestsBuilder extends ManifestsBuilder { private static final String DOCKERFILE = "bundle.Dockerfile"; private static final String LABEL = "LABEL "; private static final char EQUALS = '='; private static final String PREFIX = "FROM scratch\n\n# Core bundle labels.\n"; private static final String SUFFIX = "\n# Copy files to locations specified by labels.\nCOPY manifests /manifests/\nCOPY metadata /metadata/\n"; private static final char LINE_BREAK = '\n'; private final SortedMap<String, String> bundleLabels; public BundleDockerfileManifestsBuilder(CSVMetadataHolder metadata, SortedMap<String, String> bundleLabels) { super(metadata); this.bundleLabels = bundleLabels; } @Override public Path getFileName() { return Path.of(DOCKERFILE); } @Override public byte[] getManifestData(List<ServiceAccount> serviceAccounts, List<ClusterRoleBinding> clusterRoleBindings, List<ClusterRole> clusterRoles, List<RoleBinding> roleBindings, List<Role> roles, List<Deployment> deployments) { final var sb = new StringBuilder(1024); sb.append(PREFIX); bundleLabels.forEach((key, value) -> sb.append(LABEL).append(key).append(EQUALS).append(value).append(LINE_BREAK)); sb.append(SUFFIX); return sb.toString().getBytes(StandardCharsets.UTF_8); } @Override public String getManifestType() { return "bundle"; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/CsvManifestsBuilder.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/CsvManifestsBuilder.java
package io.quarkiverse.operatorsdk.bundle.deployment.builders; import static io.quarkiverse.operatorsdk.bundle.deployment.BundleGenerator.MANIFESTS; import static io.quarkiverse.operatorsdk.bundle.deployment.BundleProcessor.CRD_DESCRIPTION; import static io.quarkiverse.operatorsdk.bundle.deployment.BundleProcessor.CRD_DISPLAY_NAME; import static io.quarkiverse.operatorsdk.bundle.runtime.BundleConfiguration.*; import static java.util.Comparator.comparing; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import java.util.stream.Collectors; import org.jboss.logging.Logger; import io.fabric8.kubernetes.api.model.GroupVersionKind; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.apps.DeploymentSpecBuilder; import io.fabric8.kubernetes.api.model.rbac.ClusterRole; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.api.model.rbac.PolicyRule; import io.fabric8.kubernetes.api.model.rbac.PolicyRuleBuilder; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.fabric8.kubernetes.api.model.rbac.RoleRef; import io.fabric8.kubernetes.api.model.rbac.Subject; import io.fabric8.openshift.api.model.operatorhub.v1alpha1.CRDDescription; import io.fabric8.openshift.api.model.operatorhub.v1alpha1.CRDDescriptionBuilder; import io.fabric8.openshift.api.model.operatorhub.v1alpha1.ClusterServiceVersionBuilder; import io.fabric8.openshift.api.model.operatorhub.v1alpha1.NamedInstallStrategyFluent; import io.fabric8.openshift.api.model.operatorhub.v1alpha1.StrategyDeploymentPermissionsBuilder; import io.fabric8.openshift.api.model.operatorhub.v1alpha1.StrategyDeploymentPermissionsFluent; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder.RequiredCRD; import io.quarkiverse.operatorsdk.common.ConfigurationUtils; import io.quarkiverse.operatorsdk.common.ReconciledAugmentedClassInfo; import io.quarkiverse.operatorsdk.common.ReconciledResourceAugmentedClassInfo; import io.quarkiverse.operatorsdk.common.ReconcilerAugmentedClassInfo; import io.quarkiverse.operatorsdk.common.ResourceAssociatedAugmentedClassInfo; import io.quarkiverse.operatorsdk.runtime.BuildTimeOperatorConfiguration; public class CsvManifestsBuilder extends ManifestsBuilder { private static final Logger log = Logger.getLogger(CsvManifestsBuilder.class); private static final String DEFAULT_INSTALL_MODE = "AllNamespaces"; private static final String DEPLOYMENT = "deployment"; private static final String SERVICE_ACCOUNT_KIND = "ServiceAccount"; private static final String CLUSTER_ROLE_KIND = "ClusterRole"; private static final String ROLE_KIND = "Role"; private static final String NO_SERVICE_ACCOUNT = ""; private static final Logger LOGGER = Logger.getLogger(CsvManifestsBuilder.class.getName()); private static final String IMAGE_PNG = "image/png"; public static final String OLM_TARGET_NAMESPACES = "metadata.annotations['olm.targetNamespaces']"; private static final Comparator<String> nullsFirst = Comparator.nullsFirst(String::compareTo); private static final Comparator<GroupVersionKind> gvkComparator = comparing(GroupVersionKind::getGroup, nullsFirst) .thenComparing(GroupVersionKind::getKind, nullsFirst) .thenComparing(GroupVersionKind::getVersion, nullsFirst); private static final Comparator<CRDDescription> crdDescriptionComparator = comparing(CRDDescription::getName, nullsFirst); private ClusterServiceVersionBuilder csvBuilder; private final Set<CRDDescription> ownedCRs = new HashSet<>(); private final Set<CRDDescription> requiredCRs = new HashSet<>(); private final Path kubernetesResources; private final String deploymentName; private final List<ReconcilerAugmentedClassInfo> controllers; public CsvManifestsBuilder(CSVMetadataHolder metadata, BuildTimeOperatorConfiguration operatorConfiguration, List<ReconcilerAugmentedClassInfo> controllers, Path mainSourcesRoot, String deploymentName) { super(metadata); this.deploymentName = deploymentName; this.controllers = controllers; this.kubernetesResources = mainSourcesRoot != null ? mainSourcesRoot.resolve("kubernetes") : null; csvBuilder = new ClusterServiceVersionBuilder(); final var metadataBuilder = csvBuilder.withNewMetadata().withName(metadata.csvName); if (metadata.annotations != null) { metadataBuilder.addToAnnotations(OLM_SKIP_RANGE_ANNOTATION, metadata.annotations.skipRange); metadataBuilder.addToAnnotations(CONTAINER_IMAGE_ANNOTATION, metadata.annotations.containerImage); metadataBuilder.addToAnnotations(REPOSITORY_ANNOTATION, metadata.annotations.repository); metadataBuilder.addToAnnotations(CAPABILITIES_ANNOTATION, metadata.annotations.capabilities); metadataBuilder.addToAnnotations(CATEGORIES_ANNOTATION, metadata.annotations.categories); metadataBuilder.addToAnnotations(CERTIFIED_ANNOTATION, String.valueOf(metadata.annotations.certified)); metadataBuilder.addToAnnotations(ALM_EXAMPLES_ANNOTATION, metadata.annotations.almExamples); if (metadata.annotations.others != null) { metadata.annotations.others.forEach(metadataBuilder::addToAnnotations); } } if (metadata.labels != null) { metadata.labels.forEach(metadataBuilder::addToLabels); } csvBuilder = metadataBuilder.endMetadata(); final var csvSpecBuilder = csvBuilder .editOrNewSpec() .withDescription(metadata.description) .withDisplayName(defaultIfEmpty(metadata.displayName, metadata.csvName)) .withKeywords(metadata.keywords) .withReplaces(metadata.replaces) .withVersion(metadata.version) .withMinKubeVersion(metadata.minKubeVersion) .withMaturity(metadata.maturity); if (metadata.providerName != null) { csvSpecBuilder.withNewProvider() .withName(metadata.providerName) .withUrl(metadata.providerURL) .endProvider(); } if (metadata.maintainers != null) { for (CSVMetadataHolder.Maintainer maintainer : metadata.maintainers) { csvSpecBuilder.addNewMaintainer(maintainer.email, maintainer.name); } } if (metadata.links != null) { for (CSVMetadataHolder.Link link : metadata.links) { csvSpecBuilder.addNewLink(link.name, link.url); } } final var defaultIconName = getIconName(); // check if user has auto-detected icon final var defaultIcon = readIconAsBase64(defaultIconName); if (defaultIcon != null) { csvSpecBuilder.addNewIcon(defaultIcon, IMAGE_PNG); } if (metadata.icon != null) { // deal with explicit icons for (CSVMetadataHolder.Icon icon : metadata.icon) { if (!icon.fileName.isBlank() && !defaultIconName.equals(icon.fileName)) { String iconAsBase64 = readIconAsBase64(icon.fileName); if (iconAsBase64 != null) { csvSpecBuilder.addNewIcon() .withBase64data(iconAsBase64) .withMediatype(icon.mediatype) .endIcon(); } else { throw new IllegalArgumentException( "Couldn't find '" + icon.fileName + "' in " + kubernetesResources); } } } } else { // legacy icon support try (var iconAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(defaultIconName)) { if (iconAsStream != null) { log.warn( "Using icon found in the application's resource. It is now recommended to put icons in 'src/main/kubernetes' instead of resources and provide an explicit name / media type using the @CSVMetadata.Icon annotation. This avoids unduly bundling unneeded resources into the application."); final byte[] iconAsBase64 = Base64.getEncoder().encode(iconAsStream.readAllBytes()); csvSpecBuilder.addNewIcon(new String(iconAsBase64), IMAGE_PNG); } } catch (IOException e) { // ignore } } if (metadata.installModes == null || metadata.installModes.length == 0) { csvSpecBuilder.addNewInstallMode(true, DEFAULT_INSTALL_MODE); } else { for (CSVMetadataHolder.InstallMode installMode : metadata.installModes) { csvSpecBuilder.addNewInstallMode(installMode.supported, installMode.type); } } // add owned and required CRD, also collect them final var nativeApis = new ArrayList<GroupVersionKind>(); controllers.forEach(raci -> { // deal with primary resource final var resourceInfo = raci.associatedResourceInfo(); if (resourceInfo.isCR()) { final var asResource = resourceInfo.asResourceTargeting(); // if the primary is not a CR, mark it as native API if (asResource.isCR()) { // check if the primary resource is unowned, in which case, make it required, otherwise, it's owned final var crdDescription = createCRDDescription(asResource); if (operatorConfiguration.isControllerOwningPrimary(raci.nameOrFailIfUnset())) { ownedCRs.add(crdDescription); } else { requiredCRs.add(crdDescription); } } else { nativeApis.add(new GroupVersionKind(asResource.group(), asResource.kind(), asResource.version())); } } // add required CRD for each dependent that targets a CR final var dependents = raci.getDependentResourceInfos(); if (dependents != null && !dependents.isEmpty()) { dependents.stream() .filter(draci -> !draci.isOptional()) .map(ResourceAssociatedAugmentedClassInfo::associatedResourceInfo) .filter(ReconciledAugmentedClassInfo::isResource) .map(ReconciledAugmentedClassInfo::asResourceTargeting) .forEach(secondaryResource -> { if (secondaryResource.isCR()) { requiredCRs.add(createCRDDescription(secondaryResource)); } else { nativeApis.add(new GroupVersionKind(secondaryResource.group(), secondaryResource.kind(), secondaryResource.version())); } }); } }); // add required CRDs from CSV metadata if (metadata.requiredCRDs != null) { for (RequiredCRD requiredCRD : metadata.requiredCRDs) { requiredCRs.add(new CRDDescriptionBuilder() .withKind(requiredCRD.kind) .withName(requiredCRD.name) .withVersion(requiredCRD.version) .build()); } } // add sorted native APIs csvSpecBuilder.addAllToNativeAPIs(nativeApis.stream() .distinct() .sorted(gvkComparator) .toList()); csvSpecBuilder.editOrNewCustomresourcedefinitions() .addAllToOwned(ownedCRs.stream().sorted(crdDescriptionComparator).toList()) .addAllToRequired(requiredCRs.stream().sorted(crdDescriptionComparator).toList()) .endCustomresourcedefinitions() .endSpec(); } private CRDDescription createCRDDescription(ReconciledResourceAugmentedClassInfo<?> secondaryResource) { final var fullResourceName = secondaryResource.fullResourceName(); return new CRDDescriptionBuilder() .withName(fullResourceName) .withDisplayName(secondaryResource.getExtendedInfo(CRD_DISPLAY_NAME, String.class)) .withDescription(secondaryResource.getExtendedInfo(CRD_DESCRIPTION, String.class)) .withVersion(secondaryResource.version()) .withKind(secondaryResource.kind()) .build(); } public Set<String> getOwnedCRs() { return ownedCRs.stream() .map(CRDDescription::getName) .sorted() .collect(Collectors.toCollection(LinkedHashSet::new)); } public Set<String> getRequiredCRs() { return requiredCRs.stream() .map(CRDDescription::getName) .sorted() .collect(Collectors.toCollection(LinkedHashSet::new)); } @Override public String getManifestType() { return "CSV"; } public Path getFileName() { return Path.of(MANIFESTS, getName() + ".clusterserviceversion.yaml"); } private String getIconName() { return getName() + ".icon.png"; } private String readIconAsBase64(String fileName) { if (kubernetesResources != null) { try (var iconAsStream = new FileInputStream(kubernetesResources.resolve(fileName).toFile())) { final byte[] iconAsBase64 = Base64.getEncoder().encode(iconAsStream.readAllBytes()); return new String(iconAsBase64); } catch (IOException e) { return null; } } return null; } public byte[] getManifestData(List<ServiceAccount> serviceAccounts, List<ClusterRoleBinding> clusterRoleBindings, List<ClusterRole> clusterRoles, List<RoleBinding> roleBindings, List<Role> roles, List<Deployment> deployments) throws IOException { final var csvSpecBuilder = csvBuilder.editOrNewSpec(); String defaultServiceAccountName = NO_SERVICE_ACCOUNT; if (!serviceAccounts.isEmpty()) { defaultServiceAccountName = serviceAccounts.get(0).getMetadata().getName(); } final var installSpec = csvSpecBuilder.editOrNewInstall() .withStrategy(DEPLOYMENT).editOrNewSpec(); handleClusterPermissions(clusterRoleBindings, clusterRoles, roles, defaultServiceAccountName, installSpec); handlePermissions(roleBindings, clusterRoles, roles, defaultServiceAccountName, installSpec); handleDeployments(deployments, installSpec); // do not forget to end the elements!! installSpec.endSpec().endInstall(); csvSpecBuilder.endSpec(); final var csv = csvBuilder.build(); return YAML_MAPPER.writeValueAsBytes(csv); } private void handleDeployments(List<Deployment> deployments, NamedInstallStrategyFluent<?>.SpecNested<?> installSpec) { deployments.forEach(deployment -> handleDeployment(deployment, installSpec)); } private void handlePermissions(List<RoleBinding> roleBindings, List<ClusterRole> clusterRoles, List<Role> roles, String defaultServiceAccountName, NamedInstallStrategyFluent<?>.SpecNested<?> installSpec) { Map<String, List<PolicyRule>> customPermissionRules = new HashMap<>(); if (metadata.permissionRules != null) { for (CSVMetadataHolder.PermissionRule permissionRule : metadata.permissionRules) { String serviceAccountName = defaultIfEmpty(permissionRule.serviceAccountName, defaultServiceAccountName); List<PolicyRule> customRulesByServiceAccount = customPermissionRules.computeIfAbsent(serviceAccountName, k -> new LinkedList<>()); customRulesByServiceAccount.add(new PolicyRuleBuilder() .addAllToApiGroups(Arrays.asList(permissionRule.apiGroups)) .addAllToResources(Arrays.asList(permissionRule.resources)) .addAllToVerbs(Arrays.asList(permissionRule.verbs)) .build()); } } for (RoleBinding binding : roleBindings) { String serviceAccountName = findServiceAccountFromSubjects(binding.getSubjects(), defaultServiceAccountName); if (NO_SERVICE_ACCOUNT.equals(serviceAccountName)) { LOGGER.warnf("Role '%s' was not added because the service account is missing", binding.getRoleRef().getName()); continue; } List<PolicyRule> rules = new LinkedList<>(findRules(binding.getRoleRef(), clusterRoles, roles)); Optional.ofNullable(customPermissionRules.remove(serviceAccountName)).ifPresent(rules::addAll); handlePermission(rules, serviceAccountName, installSpec); } } private void handleClusterPermissions(List<ClusterRoleBinding> clusterRoleBindings, List<ClusterRole> clusterRoles, List<Role> roles, String defaultServiceAccountName, NamedInstallStrategyFluent<?>.SpecNested<?> installSpec) { for (ClusterRoleBinding binding : clusterRoleBindings) { String serviceAccountName = findServiceAccountFromSubjects(binding.getSubjects(), defaultServiceAccountName); if (NO_SERVICE_ACCOUNT.equals(serviceAccountName)) { LOGGER.warnf("Cluster Role '%s' was not added because the service account is missing", binding.getRoleRef().getName()); continue; } handleClusterPermission(findRules(binding.getRoleRef(), clusterRoles, roles), serviceAccountName, installSpec); } } private void handleDeployment(Deployment deployment, NamedInstallStrategyFluent<?>.SpecNested<?> installSpec) { if (deployment != null) { final var deploymentName = deployment.getMetadata().getName(); var deploymentSpec = deployment.getSpec(); // if we're dealing with the operator's deployment, modify it to add the namespaces env variables if (deploymentName.equals(this.deploymentName)) { final var containerBuilder = new DeploymentSpecBuilder(deploymentSpec) .editTemplate() .editSpec() .editFirstContainer(); controllers.stream() .map(ResourceAssociatedAugmentedClassInfo::nameOrFailIfUnset) .forEach(reconcilerName -> { final var envVarName = ConfigurationUtils.getNamespacesPropertyName(reconcilerName, true); // remove existing env var if already present to avoid duplication containerBuilder.removeMatchingFromEnv(env -> envVarName.equals(env.getName())); containerBuilder .addNewEnv() .withName(envVarName) .withNewValueFrom() .withNewFieldRef() .withFieldPath(OLM_TARGET_NAMESPACES) .endFieldRef() .endValueFrom() .endEnv(); }); deploymentSpec = containerBuilder .endContainer() .endSpec() .endTemplate() .build(); } installSpec.addNewDeployment() .withName(deploymentName) .withSpec(deploymentSpec) .endDeployment(); } } private void handlePermission(List<PolicyRule> rules, String serviceAccountName, NamedInstallStrategyFluent<?>.SpecNested<?> installSpec) { if (!rules.isEmpty()) { Predicate<StrategyDeploymentPermissionsBuilder> sameServiceAccountName = p -> serviceAccountName .equals(p.getServiceAccountName()); if (installSpec.hasMatchingPermission(sameServiceAccountName)) { var permission = installSpec.editMatchingPermission(sameServiceAccountName); appendRulesInPermission(permission, rules); permission.endPermission(); } else { installSpec.addNewPermission() .withServiceAccountName(serviceAccountName) .addAllToRules(rules) .endPermission(); } } } private void handleClusterPermission(List<PolicyRule> rules, String serviceAccountName, NamedInstallStrategyFluent<?>.SpecNested<?> installSpec) { Predicate<StrategyDeploymentPermissionsBuilder> sameServiceAccountName = p -> serviceAccountName .equals(p.getServiceAccountName()); if (installSpec.hasMatchingClusterPermission(sameServiceAccountName)) { var permission = installSpec.editMatchingClusterPermission(sameServiceAccountName); appendRulesInPermission(permission, rules); permission.endClusterPermission(); } else { installSpec.addNewClusterPermission() .withServiceAccountName(serviceAccountName) .addAllToRules(rules) .endClusterPermission(); } } private String findServiceAccountFromSubjects(List<Subject> subjects, String defaultServiceAccountName) { return subjects.stream() .filter(o -> SERVICE_ACCOUNT_KIND.equalsIgnoreCase(o.getKind())) .map(Subject::getName) .findFirst() .orElse(defaultServiceAccountName); } private List<PolicyRule> findRules(RoleRef roleRef, List<ClusterRole> clusterRoles, List<Role> roles) { if (roleRef == null) { return Collections.emptyList(); } String roleRefKind = roleRef.getKind(); String roleRefName = roleRef.getName(); if (CLUSTER_ROLE_KIND.equals(roleRefKind)) { for (ClusterRole role : clusterRoles) { if (roleRefName.equals(role.getMetadata().getName())) { return role.getRules(); } } } else if (ROLE_KIND.equals(roleRefKind)) { for (Role role : roles) { if (roleRefName.equals(role.getMetadata().getName())) { return role.getRules(); } } } return Collections.emptyList(); } @SuppressWarnings({ "rawtypes", "unchecked" }) private void appendRulesInPermission(StrategyDeploymentPermissionsFluent permission, List<PolicyRule> rules) { for (PolicyRule rule : rules) { if (!permission.hasMatchingRule(r -> r.equals(rule))) { permission.addToRules(rule); } } } private static String defaultIfEmpty(String possiblyNullOrEmpty, String defaultValue) { return Optional.ofNullable(possiblyNullOrEmpty).filter(s -> !s.isBlank()).orElse(defaultValue); } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/AnnotationsManifestsBuilder.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/AnnotationsManifestsBuilder.java
package io.quarkiverse.operatorsdk.bundle.deployment.builders; import java.io.IOException; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.SortedMap; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.rbac.ClusterRole; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; public class AnnotationsManifestsBuilder extends ManifestsBuilder { private static final String METADATA = "metadata"; private static final String ANNOTATIONS = "annotations"; private final SortedMap<String, String> bundleLabels; public AnnotationsManifestsBuilder(CSVMetadataHolder metadata, SortedMap<String, String> bundleLabels) { super(metadata); this.bundleLabels = bundleLabels; } @Override public Path getFileName() { return Path.of(METADATA, ANNOTATIONS + ".yaml"); } @Override public byte[] getManifestData(List<ServiceAccount> serviceAccounts, List<ClusterRoleBinding> clusterRoleBindings, List<ClusterRole> clusterRoles, List<RoleBinding> roleBindings, List<Role> roles, List<Deployment> deployments) throws IOException { return YAML_MAPPER.writeValueAsBytes(Collections.singletonMap(ANNOTATIONS, bundleLabels)); } @Override public String getManifestType() { return ANNOTATIONS; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
quarkiverse/quarkus-operator-sdk
https://github.com/quarkiverse/quarkus-operator-sdk/blob/c5276c168ac00f94007e8b0c2c1b2c8162a1c424/bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/CustomResourceManifestsBuilder.java
bundle-generator/deployment/src/main/java/io/quarkiverse/operatorsdk/bundle/deployment/builders/CustomResourceManifestsBuilder.java
package io.quarkiverse.operatorsdk.bundle.deployment.builders; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import io.fabric8.kubernetes.api.model.ServiceAccount; import io.fabric8.kubernetes.api.model.apps.Deployment; import io.fabric8.kubernetes.api.model.rbac.ClusterRole; import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding; import io.fabric8.kubernetes.api.model.rbac.Role; import io.fabric8.kubernetes.api.model.rbac.RoleBinding; import io.quarkiverse.operatorsdk.bundle.runtime.CSVMetadataHolder; import io.quarkiverse.operatorsdk.runtime.CRDInfo; public class CustomResourceManifestsBuilder extends ManifestsBuilder { private static final String MANIFESTS = "manifests"; private final CRDInfo crd; public CustomResourceManifestsBuilder(CSVMetadataHolder metadata, CRDInfo crd) { super(metadata); this.crd = crd; } @Override public Path getFileName() { return Path.of(MANIFESTS, crd.getCrdName() + "-" + crd.getCrdSpecVersion() + ".crd.yml"); } @Override public byte[] getManifestData(List<ServiceAccount> serviceAccounts, List<ClusterRoleBinding> clusterRoleBindings, List<ClusterRole> clusterRoles, List<RoleBinding> roleBindings, List<Role> roles, List<Deployment> deployments) throws IOException { return Files.readAllBytes(new File(crd.getFilePath()).toPath()); } @Override public String getManifestType() { return "Custom Resource Definition"; } }
java
Apache-2.0
c5276c168ac00f94007e8b0c2c1b2c8162a1c424
2026-01-05T02:41:12.555806Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/decompiler/Decompiler.java
src/asmcup/decompiler/Decompiler.java
package asmcup.decompiler; import java.io.*; import asmcup.compiler.VMFuncTable; import asmcup.vm.VMConsts; public class Decompiler implements VMConsts { private final PrintStream out; public Decompiler() { out = System.out; } public Decompiler(PrintStream out) { this.out = out; } public void decompile(byte[] ram) { int pc = 0; int end = 255; while (read8(ram, end) == 0 && end > 0) { end--; } while (pc <= end) { pc += decompileCommand(ram, pc); } } public int read8(byte[] ram, int pc) { return ram[pc & 0xFF] & 0xFF; } public int read16(byte[] ram, int pc) { return read8(ram, pc) | (read8(ram, pc + 1) << 8); } public int read32(byte[] ram, int pc) { return read16(ram, pc) | (read16(ram, pc + 2) << 16); } public float readFloat(byte[] ram, int pc) { return Float.intBitsToFloat(read32(ram, pc)); } public void dump(int pc, String s) { out.printf("L%02x: %s%n", pc, s); } public int decompileCommand(byte[] ram, int pc) { int bits = ram[pc & 0xFF] & 0xFF; int opcode = bits & 0b11; int data = bits >> 2; switch (opcode) { case OP_BRANCH: return decompileBranch(ram, pc, data); case OP_PUSH: return decompilePush(ram, pc, data); case OP_POP: return decompilePop(ram, pc, data); case OP_FUNC: return decompileFunc(ram, pc, data); } return 1; } public int decompileFunc(byte[] ram, int pc, int data) { dump(pc, VMFuncTable.unparse(data)); return 1; } public int decompilePop(byte[] ram, int pc, int data) { int addr; switch (data) { case MAGIC_POP_BYTE: addr = read8(ram, pc + 1); dump(pc, String.format("pop8 $%02x", addr)); return 2; case MAGIC_POP_BYTE_INDIRECT: addr = read8(ram, pc + 1); dump(pc, String.format("pop8 [$%02x]", addr)); return 2; case MAGIC_POP_FLOAT: addr = read8(ram, pc + 1); dump(pc, String.format("popf $%02x", addr)); return 2; case MAGIC_POP_FLOAT_INDIRECT: addr = read8(ram, pc + 1); dump(pc, String.format("popf [$%02x]", addr)); return 2; } int r = data - 32; addr = (pc + r + 1) & 0xFF; dump(pc, String.format("pop8r $%02x ; relative %d", addr, r)); return 1; } public int decompileBranch(byte[] ram, int pc, int data) { int addr; switch (data) { case MAGIC_BRANCH_ALWAYS: addr = read8(ram, pc + 1); dump(pc, String.format("jmp $%02x", addr)); return 2; case MAGIC_BRANCH_IMMEDIATE: addr = read8(ram, pc + 1); dump(pc, String.format("jnz $%02x", addr)); return 2; case MAGIC_BRANCH_INDIRECT: addr = read8(ram, pc + 1); dump(pc, String.format("jmp [$%02x]", addr)); return 2; } int r = data - 32; addr = (pc + r + 1) & 0xFF; dump(pc, String.format("jnzr $%02x ; relative %d", addr, r)); return 1; } public int decompilePush(byte[] ram, int pc, int data) { int addr; float f; switch (data) { case MAGIC_PUSH_BYTE_IMMEDIATE: return verbosePushByte(ram, pc); case MAGIC_PUSH_BYTE_MEMORY: addr = read8(ram, pc + 1); dump(pc, String.format("push8 $%02x", addr)); return 2; case MAGIC_PUSH_FLOAT_IMMEDIATE: return verbosePushFloat(ram, pc); case MAGIC_PUSH_FLOAT_MEMORY: addr = read8(ram, pc + 1); dump(pc, String.format("pushf $%02x", addr)); return 2; } int r = data - 32; addr = (pc + r + 1) & 0xFF; dump(pc, String.format("push8r $%02x ; relative %d", addr, r)); return 1; } protected int verbosePushByte(byte[] ram, int pc) { // We just read a 2 byte push8 that could get condensed into the 1 byte // function call by the compiler. This may break programs when they are // decompiled and then recompiled because addresses may change. int value = read8(ram, pc + 1); switch (value) { case 0: case 1: case 2: case 3: case 4: case 255: int instruction = (MAGIC_PUSH_BYTE_IMMEDIATE << 2) + OP_PUSH; dump(pc, String.format("db8 #$%02x ; verbose push8 #value", instruction)); dump(pc+1, String.format("db8 #$%02x ; (continued)", value)); break; default: dump(pc, String.format("push8 #$%02x", value)); } return 2; } protected int verbosePushFloat(byte[] ram, int pc) { // We just read a 5 byte pushf that could get condensed into the 1 byte // function call by the compiler. This may break programs when they are // decompiled and then recompiled because addresses may change. float value = readFloat(ram, pc + 1); if (value == -1.0f || value == 0.0f || value == 1.0f || value == 2.0f || value == 3.0f || Float.isInfinite(value)) { int instruction = (MAGIC_PUSH_FLOAT_IMMEDIATE << 2) + OP_PUSH; dump(pc, String.format("db8 #$%02x ; verbose pushf #value", instruction)); dump(pc+1, String.format("dbf #%.9e ; (continued)", value)); } else { dump(pc, String.format("pushf #%.9e", value)); } return 5; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/decompiler/Main.java
src/asmcup/decompiler/Main.java
package asmcup.decompiler; import java.io.*; import java.nio.file.Files; public class Main { public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.printf("USAGE: asmcup-decompiler <file>%n"); System.exit(1); return; } File in = new File(args[0]); byte[] ram = Files.readAllBytes(in.toPath()); if (ram.length != 256) { System.err.printf("ERROR: Program must be 256 bytes not %d%n", ram.length); System.exit(1); return; } Decompiler decompiler = new Decompiler(); decompiler.decompile(ram); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/PlaybackVM.java
src/asmcup/runtime/PlaybackVM.java
package asmcup.runtime; import asmcup.vm.VM; public class PlaybackVM extends VM { protected byte[] data = {}; @Override public void tick() { if (data == null) { setIO(false); return; } setIO(data.length > 0); for (int i=0 ; i < data.length; i++) { push8(data[i]); } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/Robot.java
src/asmcup/runtime/Robot.java
package asmcup.runtime; import asmcup.vm.VM; public class Robot { protected final int id; protected VM vm; protected float x, y; protected float facing; protected int overclock; protected int battery; protected float motor; protected float steer; protected float lazer; protected float lazerEnd; protected float lastX, lastY; protected float frequency; protected int gold; protected float sensor; protected float beamDirection; protected int sensorIgnore; protected int sensorFrame; protected boolean ramming; protected int lastValidIO, lastInvalidIO; public Robot(int id) { this(id, new VM()); } public Robot(int id, byte[] rom) { this(id, new VM(rom.clone())); } public Robot(int id, VM vm) { this.id = id; this.vm = vm; this.battery = BATTERY_MAX; } public VM getVM() { return vm; } public float getX() { return x; } public float getY() { return y; } public int getColumn() { return (int)(x / World.TILE_SIZE); } public int getRow() { return (int)(y / World.TILE_SIZE); } public int getCellX() { return getColumn() / World.TILES_PER_CELL; } public int getCellY() { return getRow() / World.TILES_PER_CELL; } public int getCellKey() { return getCellX() | (getCellY() << 16); } public float getFacing() { return facing; } public float getMotor() { return motor; } public float getSteer() { return steer; } public int getBattery() { return battery; } public int getOverclock() { return overclock; } public float getSensor() { return sensor; } public float getBeamAngle() { return (float)(facing + beamDirection * StrictMath.PI / 2); } public int getSensorFrame() { return sensorFrame; } public float getLazer() { return lazer; } public float getLazerEnd() { return lazerEnd; } public void setMotor(float f) { motor = clampSafe(f, -1, 1); } public void setSteer(float f) { steer = clampSafe(f, -1, 1); } public void setLazer(float f) { lazer = clampSafe(f, 0, 1.0f); } public void setOverclock(int v) { overclock = StrictMath.min(100, StrictMath.max(0, v)); } public void setFacing(float facing) { this.facing = facing; } public void position(float x, float y) { this.x = x; this.y = y; lastX = x; lastY = y; } public boolean isRamming() { return ramming; } public int getLastIO() { return lastValidIO; } public int getLastInvalidIO() { return lastInvalidIO; } public void kill() { battery = 0; } public void damage(int dmg) { if (dmg < 0) { throw new IllegalArgumentException("Damage cannot be negative"); } battery -= dmg; } public void addBattery(int charge) { if (charge < 0) { throw new IllegalArgumentException("Recharge amount cannot be negative"); } battery += charge; } public boolean isDead() { return battery <= 0; } public int getGold() { return gold; } public void addGold(int g) { if (g < 0) { throw new IllegalArgumentException("Gold amount cannot be negetive"); } gold += g; } public void tick(World world) { tickSoftware(world); tickHardware(world); } protected void tickSoftware(World world) { int cyclesUsed = 0; while (cyclesUsed <= overclock) { vm.tick(); handleIO(world); cyclesUsed++; battery--; } } protected void tickHardware(World world) { tickSteer(world); tickMotor(world); tickLazer(world); } protected void tickSteer(World world) { if (StrictMath.abs(steer) <= 0.01f) { steer = 0.0f; } facing += steer * STEER_RATE; } protected void tickMotor(World world) { float s; if (StrictMath.abs(motor) <= 0.01f) { motor = 0.0f; return; } if (motor < 0) { s = motor * 0.5f * SPEED_MAX; } else { s = motor * SPEED_MAX; } float tx = x + (float)StrictMath.cos(facing) * s; float ty = y + (float)StrictMath.sin(facing) * s; if (world.canRobotGoTo(tx, ty)) { x = tx; y = ty; ramming = true; } else if (world.canRobotGoTo(tx, y)) { x = tx; ramming = true; } else if (world.canRobotGoTo(x, ty)) { y = ty; ramming = true; } else { ramming = false; } } protected void tickLazer(World world) { if (lazer <= 0) { lazerEnd = 0; return; } float cos = (float)StrictMath.cos(getBeamAngle()); float sin = (float)StrictMath.sin(getBeamAngle()); for (int i=0; i < RAY_STEPS; i++) { if ((i * RAY_INTERVAL) >= (lazer * LAZER_RANGE)) { lazerEnd = lazer * LAZER_RANGE; return; } battery -= LAZER_BATTERY_COST; float tx = x + cos * (i * RAY_INTERVAL); float ty = y + sin * (i * RAY_INTERVAL); int tile = world.getTileXY(tx, ty); int type = tile & 0b111; int variant = (tile >> 3) & 0b11; if (type == TILE.WALL) { lazerEnd = i * RAY_INTERVAL; return; } if (type == TILE.OBSTACLE) { if (variant >= 2) { world.setTileXY(tx, ty, TILE.GROUND); } lazerEnd = i * RAY_INTERVAL; return; } Robot robot = world.getRobot(tx, ty); if (robot != null && robot != this) { robot.damage(LAZER_DAMAGE); return; } } lazerEnd = RAY_INTERVAL * RAY_STEPS; } protected void handleIO(World world) { if (!vm.checkIO()) { return; } int offset, value; value = vm.pop8(); switch (value) { case IO_MOTOR: motor = popFloatSafe(-1.0f, 1.0f); break; case IO_STEER: steer = popFloatSafe(-1.0f, 1.0f); break; case IO_SENSOR: sensorRay(world); break; case IO_SENSOR_CONFIG: sensorIgnore = vm.pop8(); break; case IO_OVERCLOCK: setOverclock(vm.pop8()); break; case IO_LAZER: lazer = popFloatSafe(0.0f, 1.0f); break; case IO_BATTERY: vm.pushFloat((float)battery / BATTERY_MAX); break; case IO_MARK: value = vm.pop8(); offset = vm.pop8(); world.mark(this, offset, value); break; case IO_MARK_READ: offset = vm.pop8(); value = world.markRead(this, offset); vm.push8(value); break; case IO_ACCELEROMETER: vm.pushFloat(x - lastX); vm.pushFloat(y - lastY); lastX = x; lastY = y; break; case IO_RADIO: frequency = popFloatSafe(-FREQUENCY_MAX, FREQUENCY_MAX); break; case IO_SEND: world.send(this, frequency, vm.pop8()); break; case IO_RECV: vm.push8(world.recv(this, frequency)); break; case IO_COMPASS: vm.pushFloat(floatModPositive(facing, (float)(StrictMath.PI * 2))); break; case IO_BEAM_DIRECTION: beamDirection = popFloatSafe(-1.0f, 1.0f); break; default: lastInvalidIO = world.getFrame(); return; } lastValidIO = world.getFrame(); } protected void sensorRay(World world) { float cos = (float)StrictMath.cos(getBeamAngle()); float sin = (float)StrictMath.sin(getBeamAngle()); sensorFrame = world.getFrame(); for (int i = 0; i < RAY_STEPS; i++) { float sx = x + (cos * i * RAY_INTERVAL); float sy = y + (sin * i * RAY_INTERVAL); int hit = sensorPoint(world, sx, sy); if (hit != 0) { sensor = i * RAY_INTERVAL; vm.pushFloat(sensor); vm.push8(hit); return; } } sensor = RAY_RANGE; vm.pushFloat(sensor); vm.push8(0); } protected int sensorPoint(World world, float sx, float sy) { int tileVariation = world.getTileXY(sx, sy) & TILE.VARIATION_BITS; // In the tile, variation is stored in the 4th and 5th bit. // We need it at the 7th and 8th bit. tileVariation = tileVariation << 3; if (world.checkTile(TILE.IS_WALL, sx, sy)) { if ((sensorIgnore & SENSOR_WALL) == 0) { return SENSOR_WALL | tileVariation; } else { return 0; } } if ((sensorIgnore & SENSOR_HAZARD) == 0) { if (world.checkTile(TILE.IS_HAZARD, sx, sy)) { return SENSOR_HAZARD | tileVariation; } } if ((sensorIgnore & SENSOR_OBSTACLE) == 0) { if (world.checkTile(TILE.IS_OBSTACLE, sx, sy)) { return SENSOR_OBSTACLE | tileVariation; } } Item item = world.getItem(sx, sy); if ((sensorIgnore & SENSOR_GOLD) == 0) { if (item instanceof Item.Gold) { return SENSOR_GOLD; } } if ((sensorIgnore & SENSOR_BATTERY) == 0) { if (item instanceof Item.Battery) { return SENSOR_BATTERY; } } Robot robot = world.getRobot(sx, sy); if ((sensorIgnore & SENSOR_ROBOT) == 0) { if (robot != null && robot != this) { // TODO: Add alliance once implemented! return SENSOR_ROBOT; } } return 0; } protected float popFloatSafe(float min, float max) { return clampSafe(vm.popFloat(), min, max); } protected static float clampSafe(float f, float min, float max) { if (f > max) { return max; } else if (f < min) { return min; } else if (Float.isNaN(f)) { return 0; } return f; } protected static float floatModPositive(float dividend, float divisor) { return ((dividend % divisor) + divisor) % divisor; } public static final int IO_SENSOR = 0; public static final int IO_MOTOR = 1; public static final int IO_STEER = 2; public static final int IO_OVERCLOCK = 3; public static final int IO_LAZER = 4; public static final int IO_LASER = 4; public static final int IO_BATTERY = 5; public static final int IO_MARK = 6; public static final int IO_MARK_READ = 7; public static final int IO_ACCELEROMETER = 8; public static final int IO_RADIO = 9; public static final int IO_SEND = 10; public static final int IO_RECV = 11; public static final int IO_RECEIVE = 11; public static final int IO_SENSOR_CONFIG = 12; public static final int IO_COMPASS = 13; public static final int IO_BEAM_DIRECTION = 14; public static final float SPEED_MAX = 8; public static final float STEER_RATE = (float)(StrictMath.PI * 0.1); public static final int BATTERY_MAX = 60 * 60 * 24; public static final int OVERCLOCK_MAX = 100; public static final float FREQUENCY_MAX = 1000 * 10; public static final int LAZER_RANGE = 100; public static final int LAZER_BATTERY_COST = 4; public static final int LAZER_DAMAGE = 1024; public static final int SENSOR_WALL = 1; public static final int SENSOR_HAZARD = 2; public static final int SENSOR_GOLD = 4; public static final int SENSOR_BATTERY = 8; public static final int SENSOR_OBSTACLE = 16; public static final int SENSOR_ROBOT = 32; public static final int RAY_INTERVAL = 4; public static final int RAY_STEPS = 64; public static final int RAY_RANGE = RAY_INTERVAL * RAY_STEPS; public static final int COLLIDE_RANGE = 10; }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/World.java
src/asmcup/runtime/World.java
package asmcup.runtime; import java.util.*; public class World { protected final ArrayList<Robot> robots; protected final HashMap<Integer, Cell> cells; protected final HashMap<Integer, byte[]> tileData; protected final int seed; protected int frame; private static final Random random = new Random(); public World() { this(random.nextInt()); } public World(int seed) { this.robots = new ArrayList<>(); this.cells = new HashMap<>(); this.tileData = new HashMap<>(); this.seed = seed; this.frame = 0; } public Iterable<Robot> getRobots() { return robots; } public int getSeed() { return seed; } public int getFrame() { return frame; } public void addRobot(Robot robot) { robots.add(robot); } public void removeRobot(Robot robot) { robots.remove(robot); } public Cell getCell(int cellCol, int cellRow) { int key = Cell.key(cellCol, cellRow); Cell cell = cells.get(key); if (cell == null) { cell = new Cell(this, cellCol, cellRow); cells.put(key, cell); cell.generate(); } return cell; } public Cell getCellXY(float x, float y) { return getCell((int)(x / CELL_SIZE), (int)(y / CELL_SIZE)); } public int getTile(int tileCol, int tileRow) { int cellCol = tileCol / TILES_PER_CELL; int cellRow = tileRow / TILES_PER_CELL; Cell cell = getCell(cellCol, cellRow); return cell.getTile(tileCol - cellCol * TILES_PER_CELL, tileRow - cellRow * TILES_PER_CELL); } public int getTileXY(float x, float y) { if (x < 0 || y < 0 || x > SIZE || y > SIZE) { return TILE.WALL; } return getTile((int)(x / TILE_SIZE), (int)(y / TILE_SIZE)); } public boolean checkTile(TILE.TileProperty prop, float x, float y) { int tile = getTileXY(x, y); return prop.presentIn(tile); } public boolean isSolid(float x, float y) { return checkTile(TILE.IS_SOLID, x, y); } public boolean isHazard(float x, float y) { return checkTile(TILE.IS_HAZARD, x, y); } public boolean isObstacle(float x, float y) { return checkTile(TILE.IS_OBSTACLE, x, y); } public boolean checkTileNear(TILE.TileProperty prop, float x, float y, float r) { return checkTile(prop, x, y) || checkTile(prop, x - r, y - r) || checkTile(prop, x + r, y + r) || checkTile(prop, x - r, y + r) || checkTile(prop, x + r, y - r); } public boolean isSolidNear(float x, float y, float r) { return checkTileNear(TILE.IS_SOLID, x, y, r); } public boolean isUnspawnableNear(float x, float y, float r) { return checkTileNear(TILE.IS_UNSPAWNABLE, x, y, r); } public boolean canRobotGoTo(float x, float y) { return !isSolidNear(x, y, Robot.COLLIDE_RANGE); } public boolean canSpawnRobotAt(float x, float y) { return !isUnspawnableNear(x, y, Robot.COLLIDE_RANGE); } public int getHazard(float x, float y) { int tile = getTileXY(x, y); if ((tile & 0b111) != TILE.HAZARD) { return -1; } return tile >> 3; } public void setTileXY(float x, float y, int value) { Cell cell = getCellXY(x, y); int col = (int)(x / TILE_SIZE - cell.getX() * TILES_PER_CELL); int row = (int)(y / TILE_SIZE - cell.getY() * TILES_PER_CELL); col = StrictMath.max(col, 0); row = StrictMath.max(row, 0); col = StrictMath.min(col, TILES_PER_CELL * CELL_COUNT - 1); row = StrictMath.min(row, TILES_PER_CELL * CELL_COUNT - 1); cell.setTile(col, row, value); } public void randomizePosition(Robot robot) { int x, y; do { x = (int)(StrictMath.random() * SIZE); y = (int)(StrictMath.random() * SIZE); } while (!canSpawnRobotAt(x, y)); robot.position(x, y); } public void tick() { for (Robot robot : robots) { robot.tick(this); tickItems(robot); tickHazards(robot); } frame++; } protected void tickHazards(Robot robot) { switch (getHazard(robot.getX(), robot.getY())) { case 0: robot.damage(Robot.BATTERY_MAX / 100); break; case 1: robot.damage(Robot.BATTERY_MAX / 75); break; case 2: robot.damage(Robot.BATTERY_MAX / 50); break; case 3: robot.kill(); break; } } public Item getItem(float x, float y) { return getCellXY(x, y).getItem(x, y); } public void addItem(float x, float y, Item item) { item.position(x, y); getCellXY(x, y).addItem(item); } protected void tickItems(Robot robot) { Cell cell = getCellXY(robot.getX(), robot.getY()); Item item = cell.getItem(robot.getX(), robot.getY()); if (item == null) { return; } item.collect(robot); cell.removeItem(item); } public Robot getRobot(float x, float y) { for (Robot robot : robots) { if (Math.abs(robot.getX() - x) < Robot.COLLIDE_RANGE && Math.abs(robot.getY() - y) < Robot.COLLIDE_RANGE) { return robot; } } return null; } public void mark(Robot robot, int offset, int value) { int key = robot.getColumn() | (robot.getRow() << 16); byte[] data = tileData.get(key); if (data == null) { data = new byte[8]; tileData.put(key, data); } data[offset & 0b11] = (byte)(value & 0xFF); } public int markRead(Robot robot, int offset) { int key = robot.getColumn() | (robot.getRow() << 16); byte[] data = tileData.get(key); return (data == null) ? 0 : data[offset & 0b11]; } public void send(Robot robot, float frequency, int data) { // TODO send data on radio } public int recv(Robot robot, float frequency) { // TODO read data on radio return 0; } public static final int TILE_SIZE = 32; public static final int TILE_HALF = TILE_SIZE / 2; public static final int TILES_PER_CELL = 20; public static final int CELL_SIZE = TILES_PER_CELL * TILE_SIZE; public static final int CELL_COUNT = 0xFF; public static final int SIZE = TILE_SIZE * TILES_PER_CELL * (CELL_COUNT + 1); public static final int CENTER = SIZE / 2; }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/Item.java
src/asmcup/runtime/Item.java
package asmcup.runtime; public abstract class Item { protected float x, y; public float getX() { return x; } public float getY() { return y; } public void position(float x, float y) { this.x = x; this.y = y; } public boolean withinDistance(float tx, float ty) { float dx = tx - x; float dy = ty - y; return StrictMath.sqrt(dx * dx + dy * dy) <= 20; } public abstract void collect(Robot robot); public static class Battery extends Item { protected int value; public Battery() { this(DEFAULT_VALUE); } public Battery(int value) { this.value = value; } public void collect(Robot robot) { robot.addBattery(value * 100); } public int getVariant() { return value / 25; } public static final int DEFAULT_VALUE = 50; } public static class Gold extends Item { protected int value; public Gold() { this(DEFAULT_VALUE); } public Gold(int value) { this.value = value; } public int getValue() { return value; } public int getVariant() { return value / 25; } public void collect(Robot robot) { robot.addGold(value); } public static final int DEFAULT_VALUE = 50; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/Recorder.java
src/asmcup/runtime/Recorder.java
package asmcup.runtime; public interface Recorder { public void record(RecordedRobot robot, byte[] data); }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/PlaybackRobot.java
src/asmcup/runtime/PlaybackRobot.java
package asmcup.runtime; import java.util.HashMap; public class PlaybackRobot extends Robot { protected final PlaybackVM vm; protected final HashMap<Integer, byte[]> frames; public PlaybackRobot(int id, PlaybackVM vm) { super(id, vm); this.vm = vm; this.frames = new HashMap<>(); } @Override public void tick(World world) { vm.data = frames.get(world.getFrame()); super.tick(world); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/TILE.java
src/asmcup/runtime/TILE.java
package asmcup.runtime; // This class houses constants related to tiles as well as tile classification // functionality. // Please be aware that actual tiles in the code are represented as int. // This class cannot (and should not) be instantiated. public enum TILE {; // Courtesy of http://stackoverflow.com/a/9618724 public static final int GROUND = 0; public static final int HAZARD = 1; public static final int WALL = 2; public static final int OBSTACLE = 3; public static final int FLOOR = 4; public static final int TYPE_BITS = 0b111; public static final int VARIATION_BITS = 0b11000; public interface TileProperty { public boolean presentIn(int tile); } public static final TileProperty IS_GROUND = isType(GROUND); public static final TileProperty IS_HAZARD = isType(HAZARD); public static final TileProperty IS_WALL = isType(WALL); public static final TileProperty IS_OBSTACLE = isType(OBSTACLE); public static final TileProperty IS_FLOOR = isType(FLOOR); public static TileProperty isType(int type) { return (int tile) -> (tile & TYPE_BITS) == type; } public static final TileProperty IS_SOLID = isSolid(); public static final TileProperty IS_SPAWNABLE = isSpawnable(); public static final TileProperty IS_UNSPAWNABLE = not(IS_SPAWNABLE); public static TileProperty isSolid() { return (int tile) -> { switch (tile & TYPE_BITS) { case WALL: case OBSTACLE: return true; } return false; }; } public static TileProperty isSpawnable() { return (int tile) -> { switch (tile & TYPE_BITS) { case HAZARD: case WALL: case OBSTACLE: return false; } return true; }; } public static TileProperty not(TileProperty prop) { return (int tile) -> !prop.presentIn(tile); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/Cell.java
src/asmcup/runtime/Cell.java
package asmcup.runtime; import java.util.*; public class Cell { protected final World world; protected final int cellX, cellY; protected final int[] tiles = new int[World.TILES_PER_CELL * World.TILES_PER_CELL]; protected final ArrayList<Item> items = new ArrayList<>(); public Cell(World world, int cellX, int cellY) { this.world = world; this.cellX = cellX; this.cellY = cellY; } public void generate() { Generator gen = new Generator(world, this); if (cellX == 0 || cellY == 0 || cellX == World.CELL_COUNT || cellY == World.CELL_COUNT) { gen.square(gen.same(TILE.HAZARD, 3), 0, 0, World.TILES_PER_CELL); return; } gen.square(gen.variantRare(TILE.GROUND), 0, 0, World.TILES_PER_CELL); if (gen.chance(33)) { gen.room(); } else { gen.openArea(); } } public int getX() { return cellX; } public int getY() { return cellY; } public int getKey() { return key(cellX, cellY); } public static int key(int cellX, int cellY) { return clampCell(cellX) | (clampCell(cellY) << 16); } protected static int clampCell(int i) { return StrictMath.max(0, StrictMath.min(World.CELL_COUNT, i)); } public void addItem(Item item) { if (item == null) { throw new NullPointerException(); } items.add(item); } public Iterable<Item> getItems() { return items; } public Item getItem(float x, float y) { for (Item item : items) { if (item.withinDistance(x, y)) { return item; } } return null; } public void removeItem(Item item) { items.remove(item); } protected int getTile(int col, int row) { return tiles[clampTile(col) + (clampTile(row) * World.TILES_PER_CELL)]; } private static int clampTile(int i) { return StrictMath.max(0, StrictMath.min(World.TILES_PER_CELL - 1, i)); } public void setTile(int col, int row, int value) { if (col < 0 || row < 0) { throw new IllegalArgumentException("Tile coordinates cannot be negative"); } if (col >= World.TILES_PER_CELL || row >= World.TILES_PER_CELL) { throw new IllegalArgumentException("Tile coordinates outside of bounds"); } tiles[col + (row * World.TILES_PER_CELL)] = value; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/RecordedRobot.java
src/asmcup/runtime/RecordedRobot.java
package asmcup.runtime; public class RecordedRobot extends Robot { protected final Recorder recorder; protected RecordedVM vm; public RecordedRobot(Recorder recorder, int id, byte[] rom) { this(recorder, id, new RecordedVM(rom)); } public RecordedRobot(Recorder recorder, int id, RecordedVM vm) { super(id, vm); this.recorder = recorder; this.vm = vm; } @Override protected void handleIO(World world) { vm.trapIO = true; super.handleIO(world); vm.trapIO = false; } @Override public void tick(World world) { super.tick(world); if (vm.hasRecordedIO()) { recorder.record(this, vm.getRecordedIO()); } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/Generator.java
src/asmcup/runtime/Generator.java
package asmcup.runtime; import java.util.Random; public class Generator { protected final World world; protected final Cell cell; protected final Random random; protected int wpad, hpad; protected int width, height; protected int left, right, top, bottom; protected TileFunc wall; protected boolean room; protected int itemBonus; public Generator(World world, Cell cell) { this.world = world; this.cell = cell; this.random = new Random(world.getSeed() ^ cell.getKey()); } public int nextInt(int bound) { return random.nextInt(bound); } public float nextFloat() { return random.nextFloat(); } public int nextRare() { return chance(66) ? 0 : (1 + nextInt(3)); } public boolean chance(int p) { return nextInt(100) < p; } public TileFunc same(int type) { int variant = nextInt(4) << 3; return (col, row) -> type | variant; } public TileFunc same(int type, int variant) { return (col, row) -> type | (variant << 3); } public TileFunc variant(int type) { return (col, row) -> type | (nextInt(4) << 3); } public TileFunc variantRare(int type) { return (col, row) -> type | (nextRare() << 3); } public void set(TileFunc f, int col, int row) { cell.setTile(col, row, f.tile(col, row)); } public void hline(TileFunc f, int col, int row, int w) { for (int i=0; i < w; i++) { set(f, col + i, row); } } public void vline(TileFunc f, int col, int row, int h) { for (int i=0; i < h; i++) { set(f, col, row + i); } } public void rect(TileFunc f, int col, int row, int w, int h) { for (int r=0; r < h; r++) { for (int c=0; c < w; c++) { set(f, col + c, row + r); } } } public void square(TileFunc f, int col, int row, int s) { rect(f, col, row, s, s); } public void outline(TileFunc f, int col, int row, int w, int h) { hline(f, col, row, w); hline(f, col, row + h - 1, w); vline(f, col, row, h); vline(f, col + w - 1, row, h); } public void openArea() { room = false; hpad = 0; wpad = 0; width = World.TILES_PER_CELL; height = World.TILES_PER_CELL; left = 0; top = 0; right = width; bottom = height; int count = nextInt(15); for (int i = 0; i < count; i++) { int col = nextInt(World.TILES_PER_CELL); int row = nextInt(World.TILES_PER_CELL); int p = nextInt(100); if (p < 10) { hazards(col, row); } else if (p < 33) { rubble(col, row); } else { set(variant(TILE.OBSTACLE), col, row); } } items(); } public void rubble(int col, int row) { int count = 1 + nextInt(20); for (int i=0; i < count; i++) { set(variant(TILE.WALL), col, row); if (chance(50)) { col = wiggle(col); } else { row = wiggle(row); } } } public void hazards(int col, int row) { int count = 3 + nextInt(15); int variant = nextInt(4); switch (variant) { case 0: count = 3 + nextInt(10); break; case 1: count = 2 + nextInt(5); break; case 2: count = 1 + nextInt(3); break; case 3: count = 1; break; } for (int i=0; i < count; i++) { set(variantRare(TILE.HAZARD), col, row); col = wiggle(col); row = wiggle(row); } } protected int wiggle(int x) { x += nextInt(3) - 1; x = StrictMath.min(x, World.TILES_PER_CELL - 1); x = StrictMath.max(x, 0); return x; } public void room() { wpad = 1 + nextInt(3); hpad = 1 + nextInt(3); width = World.TILES_PER_CELL - wpad * 2; width = StrictMath.max(5, width); height = World.TILES_PER_CELL - hpad * 2; height = StrictMath.max(5, height); left = wpad + 1; top = hpad + 1; right = left + width - 2; bottom = top + height - 2; room = true; itemBonus = 10; if (chance(80)) { wall = same(TILE.WALL); } else { wall = same(TILE.HAZARD); itemBonus += 3 * ((wall.tile(0, 0) >> 3) & 0b11); } rect(same(TILE.FLOOR), wpad, hpad, width, height); outline(wall, wpad, hpad, width, height); maze(); exits(); items(); } public int roomCol(int spacing) { return wpad + 1 + spacing + nextInt(width - spacing * 2 - 2); } public int roomRow(int spacing) { return hpad + 1 + spacing + nextInt(height - spacing * 2 - 2); } public void maze() { if (chance(50)) { return; } if (chance(50)) { hmaze(); } else { vmaze(); } } public void hmaze() { TileFunc floor = same(TILE.FLOOR); int row = hpad + 2 + nextInt(3); int bottom = hpad + height - 2; while (row < bottom) { hline(wall, wpad, row, width); int t = 1 + nextInt(width - 3); set(floor, wpad + t, row); row += 2 + nextInt(5); } } public void vmaze() { TileFunc floor = same(TILE.FLOOR); int col = wpad + 2 + nextInt(3); int right = wpad + width - 2; while (col < right) { vline(wall, col, hpad, height); int t = 1 + nextInt(height - 3); set(floor, col, hpad + t); col += 2 + nextInt(5); } } public void exits() { int count = 1 + nextInt(4); for (int i=0; i < count; i++) { exit(); } } public boolean exit() { int col, row; switch (nextInt(4)) { case 0: col = wpad + 1 + nextInt(width - 2); row = hpad; break; case 1: col = wpad; row = hpad + 1 + nextInt(height - 2); break; case 2: col = wpad + 1 + nextInt(width - 2); row = World.TILES_PER_CELL - 1 - hpad; break; default: col = World.TILES_PER_CELL - 1 - wpad; row = hpad + 1 + nextInt(height - 2); break; } if (isBlocked(col, row)) { return false; } if (chance(33)) { set(same(TILE.OBSTACLE, 2 + nextInt(2)), col, row); itemBonus += 5; } else { set(variant(TILE.GROUND), col, row); } return true; } public boolean isBlocked(int col, int row) { for (int i=-1; i < 2; i += 2) { if (isSolidRoom(col + i, row) || isSolidRoom(col, row + i)) { return true; } } return false; } public boolean isSolidRoom(int col, int row) { return isInsideRoom(col, row) && world.isSolid(col, row); } public boolean isInsideRoom(int col, int row) { return col >= left && row >= top && col < right && row < bottom; } public void items() { int count = 1 + nextInt(3 + itemBonus) + itemBonus / 2; for (int i = 0; i < count; i++) { Item item; switch (nextInt(2)) { case 0: item = gold(); break; default: item = battery(); break; } spawnItem(item); } } public void spawnItem(Item item) { int left = cell.getX() * World.CELL_SIZE + World.TILE_HALF; int top = cell.getY() * World.CELL_SIZE + World.TILE_HALF; int x = 0, y = 0; for (int i = 0; i < 20; i++) { x = left + roomCol(1) * World.TILE_SIZE; y = top + roomRow(1) * World.TILE_SIZE; if (world.checkTile(TILE.IS_SPAWNABLE, x, y)) { break; } } item.position(x, y); cell.addItem(item); } public Item.Gold gold() { return new Item.Gold(); } public Item.Battery battery() { return new Item.Battery(); } public static interface TileFunc { public int tile(int col, int row); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/Main.java
src/asmcup/runtime/Main.java
package asmcup.runtime; import java.io.*; import java.nio.charset.Charset; import java.util.Base64; import asmcup.vm.VM; public class Main implements Recorder { protected World world; protected int frames; protected boolean recording; public static void main(String[] args) throws IOException { Main main = new Main(); if (args.length > 1) { System.err.printf("USAGE: asmcup-runtime [file]%n"); System.exit(1); return; } InputStream input; if (args.length > 0) { input = new FileInputStream(new File(args[0])); } else { input = System.in; } main.configure(input); main.run(); } public void configure(InputStream input) throws IOException { InputStreamReader streamReader = new InputStreamReader(input, Charset.forName("US-ASCII")); BufferedReader reader = new BufferedReader(streamReader); String line; while ((line = reader.readLine()) != null) { configure(line); } reader.close(); } public void configure(String line) { String command; String[] parts; line = line.trim(); if (line.isEmpty()) { return; } parts = line.split("[\\s\\t]+"); if (parts.length <= 0) { return; } switch (command = parts[0].toLowerCase()) { case "frames": setFrames(parts[1]); break; case "seed": setSeed(parts[1]); break; case "bot": addBot(parts[1], parts[2]); break; case "record": setRecording(parts[1]); break; default: throw new IllegalArgumentException("Unknown command " + command); } } public void setFrames(String count) { frames = Integer.parseInt(count); } public void setSeed(String seed) { world = new World(Integer.parseInt(seed)); } public void setRecording(String enabled) { recording = Integer.parseInt(enabled) > 0; } public void addBot(String id, String encoded) { addBot(Integer.parseInt(id), encoded); } public void addBot(int id, String encoded) { byte[] rom = Base64.getDecoder().decode(encoded.trim()); addBot(id, rom); } public void addBot(int id, byte[] rom) { Robot robot; if (recording) { robot = new RecordedRobot(this, id, rom); } else { robot = new Robot(id, new VM(rom)); } world.addRobot(robot); } public void run() { for (int i=0; i < frames; i++) { world.tick(); } } public void record(RecordedRobot robot, byte[] data) { String encoded = Base64.getEncoder().encodeToString(data); System.out.printf("io %d %d %s%n", world.getFrame(), robot.id, encoded); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/runtime/RecordedVM.java
src/asmcup/runtime/RecordedVM.java
package asmcup.runtime; import java.io.ByteArrayOutputStream; import asmcup.vm.VM; public class RecordedVM extends VM { protected boolean trapIO; protected ByteArrayOutputStream output; public RecordedVM(byte[] rom) { super(rom); output = new ByteArrayOutputStream(); } public boolean hasRecordedIO() { return output.size() > 0; } public byte[] getRecordedIO() { byte[] data = output.toByteArray(); output.reset(); return data; } @Override public int pop8() { int value = super.pop8(); if (trapIO) { output.write(value); } return value; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/genetics/GAFrontPanel.java
src/asmcup/genetics/GAFrontPanel.java
package asmcup.genetics; import javax.swing.*; import asmcup.sandbox.FrontPanel; public class GAFrontPanel extends FrontPanel { public final GeneticAlgorithm ga; protected JSpinner popSpinner = createSpinner(100, 1, 1000 * 1000); protected JSpinner mutationSpinner = createSpinner(100, 0, 100); protected JSpinner sizeSpinner = createSpinner(256, 1, 256); protected JSpinner chunkSpinner = createSpinner(4, 0, 256); protected JLabel bestLabel = new JLabel("0"); protected JLabel worstLabel = new JLabel("0"); protected JLabel genLabel = new JLabel("0"); protected JLabel mutationLabel = new JLabel("0"); public GAFrontPanel(GeneticAlgorithm ga) { this.ga = ga; setBorder(BorderFactory.createTitledBorder("Gene Pool")); addRow("Population:", popSpinner, "Number of robots that are kept in the gene pool"); addRow("Mutation Chance:", mutationSpinner, "Maximum chance that mutation will occur during mating"); addRow("Mutation Size:", chunkSpinner, "Maximum number of bytes that will be changed per mutation"); addRow("Program Size:", sizeSpinner, "Number of bytes in the ROM that will be used"); addRow("Best:", bestLabel, "Highest score in the gene pool"); addRow("Worst:", worstLabel, "Lowest score in the gene pool"); addRow("Mutation:", mutationLabel, "Current chance of mutation"); addRow("Generation:", genLabel, "Current generation of gene pool"); } public void update() { ga.maxMutationRate = getInt(mutationSpinner); ga.dnaLength = getInt(sizeSpinner); ga.mutationSize = getInt(chunkSpinner); //ga.resizePopulation(getInt(popSpinner)); } public void updateStats() { worstLabel.setText(String.valueOf(ga.getWorstScore())); bestLabel.setText(String.valueOf(ga.getBestScore())); genLabel.setText(String.valueOf(ga.generation)); mutationLabel.setText(String.valueOf(ga.mutationRate) + "%"); } public int getPopulationSize() { return getInt(popSpinner); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/genetics/Gene.java
src/asmcup/genetics/Gene.java
package asmcup.genetics; import java.util.Objects; public class Gene implements Comparable<Gene> { public final byte[] dna; public final float score; public final int gen; public Gene(byte[] dna, int gen, float score) { this.dna = dna; this.gen = gen; this.score = score; } @Override public int compareTo(Gene other) { float d = score - other.score; if (d == 0) { return 0; } else if (d < 0) { return 1; } return -1; } @Override public boolean equals(Object obj) { return obj instanceof Gene && compareTo((Gene) obj) == 0; } @Override public int hashCode() { // explicit default implementation to hashCode the internal pointer return Objects.hashCode(this); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/genetics/Genetics.java
src/asmcup/genetics/Genetics.java
package asmcup.genetics; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import asmcup.evaluation.EvaluatorFrontPanel; import asmcup.evaluation.SpawnEvaluator; import asmcup.sandbox.*; public class Genetics extends JFrame { public final Sandbox sandbox; public final GeneticsMenu menu; public final GeneticAlgorithm ga; public final SpawnEvaluator evaluator; public final FrontPanel panel = new FrontPanel(); public final EvaluatorFrontPanel evalPanel; public final GAFrontPanel gaPanel; protected JButton startButton = new JButton("Start"); protected JButton stopButton = new JButton("Stop"); protected Thread thread; protected boolean running = false; public Genetics(Sandbox sandbox) throws IOException { this.sandbox = sandbox; menu = new GeneticsMenu(this); evaluator = new SpawnEvaluator(sandbox.spawns, false); ga = new GeneticAlgorithm(evaluator); evalPanel = new EvaluatorFrontPanel(evaluator); gaPanel = new GAFrontPanel(ga); panel.addWideItem(evalPanel); panel.addWideItem(gaPanel); panel.addItems(stopButton, startButton); startButton.addActionListener(e -> start()); stopButton.addActionListener(e -> stop()); // The order is important here! evalPanel.updateEvaluator(); gaPanel.update(); setTitle("Genetics"); setResizable(false); setIconImage(ImageIO.read(getClass().getResource("/dna.png"))); setContentPane(panel); pack(); } public GeneticsMenu getMenu() { return menu; } public void start() { if (thread != null && thread.isAlive()) { return; } if (sandbox.spawns.size() <= 0) { sandbox.spawns.addSpawnAtRobot(); } startButton.setEnabled(false); stopButton.setEnabled(true); evalPanel.setComponentsEnabled(false); gaPanel.setComponentsEnabled(false); evalPanel.updateEvaluator(); gaPanel.update(); thread = new Thread(new Runnable() { public void run() { ga.resizePopulation(gaPanel.getPopulationSize()); while (running) { ga.nextGeneration(); gaPanel.updateStats(); } } }); running = true; thread.start(); } public void stop() { running = false; startButton.setEnabled(true); stopButton.setEnabled(false); evalPanel.setComponentsEnabled(true); gaPanel.setComponentsEnabled(true); } public void flash() { sandbox.loadROM(ga.getBestDNA()); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/genetics/GeneticsMenu.java
src/asmcup/genetics/GeneticsMenu.java
package asmcup.genetics; import java.awt.event.*; import javax.swing.*; public class GeneticsMenu extends JMenu { public final Genetics genetics; public GeneticsMenu(Genetics genetics) { super("Genetics"); this.genetics = genetics; add("Flash Best", e -> genetics.flash()); add("Pin Best", e -> genetics.ga.pin()); add("Pin ROM", e -> genetics.ga.pin(genetics.sandbox.getROM())); addSeparator(); add("Start Training", e -> genetics.start()); add("Stop Training", e-> genetics.stop()); addSeparator(); add("Modify Parameters", e -> genetics.setVisible(true)); addSeparator(); add("Clear Pinned", e -> genetics.ga.clearPinned()); } protected void add(String label, ActionListener listener) { JMenuItem item = new JMenuItem(label); item.addActionListener(listener); add(item); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/genetics/Spawn.java
src/asmcup/genetics/Spawn.java
package asmcup.genetics; import java.util.Random; import asmcup.runtime.World; public class Spawn { public final float x, y, facing; public final int seed; public Spawn(float x, float y, float facing, int seed) { this.x = x; this.y = y; this.facing = facing; this.seed = seed; } public World getNewWorld() { return new World(seed); } public static Spawn randomFromSeed(int seed) { Random random = new Random(seed); float sx = random.nextFloat() * World.SIZE; float sy = random.nextFloat() * World.SIZE; float facing = random.nextFloat() * (float)Math.PI * 2; World world = new World(seed); // Wiggle around until the start position is fair. // TODO ? Make this the job of world ("deterministic" random)? // TODO needs to check for an isSpawnable while (!world.canSpawnRobotAt(sx, sy)) { sx += (random.nextFloat() - 0.5f) * World.CELL_SIZE; sy += (random.nextFloat() - 0.5f) * World.CELL_SIZE; } return new Spawn(sx, sy, facing, seed); } @Override public String toString() { return "(" + x + ", " + y + " -> " + facing + ") in " + seed; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/genetics/GeneticAlgorithm.java
src/asmcup/genetics/GeneticAlgorithm.java
package asmcup.genetics; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import asmcup.evaluation.Evaluator; public class GeneticAlgorithm { public final ArrayList<Gene> pinned; public final Random random; public final Evaluator evaluator; public Gene[] population; public int generation; public int mutationRate = 50; public int minMutationRate = 1; public int maxMutationRate = 100; public int mutationSize = 4; public int dnaLength = 256; // FIXME: Handle DNA length changes gracefully // TODO: Meaningful initial population? public GeneticAlgorithm(Evaluator evaluator) { this.evaluator = evaluator; random = new Random(); population = new Gene[0]; pinned = new ArrayList<>(); } public Gene createGene(byte[] rom) { return new Gene(rom, generation, evaluator.score(rom)); } public void initializePopulation(int populationSize) { population = new Gene[populationSize]; for (int i=0; i < population.length; i++) { population[i] = randomGene(); } } public void resizePopulation(int newSize) { Gene[] newPop = new Gene[newSize]; for (int i=0; i < newSize; i++) { newPop[i] = randomGene(); } population = newPop; } public void nextGeneration() { adjustMutationRate(); int halfPoint = population.length / 2; int pin = pinned.size(); for (int i=halfPoint; i < population.length; i++) { if (pin > 0) { pin--; population[i] = cross(pinned.get(pin), selectRandomGene()); } else { population[i] = cross(); } } Arrays.sort(population); generation++; } private byte randomByte() { return (byte)random.nextInt(256); } private Gene randomGene() { return createGene(randomDNA()); } private byte[] randomDNA() { byte[] dna = new byte[256]; for (int i = 0; i < dnaLength; i++) { dna[i] = randomByte(); } return dna; } public Gene selectRandomGene() { int i = random.nextInt(population.length / 2); return population[i]; } public Gene cross() { int a, b; do { a = random.nextInt(population.length / 2); b = random.nextInt(population.length / 2); } while (a == b); return cross(population[a], population[b]); } public Gene cross(Gene mom, Gene dad) { byte[] dna = mom.dna.clone(); switch (random.nextInt(2)) { case 0: crossTwoPoint(mom, dad, dna); break; case 1: default: crossUniform(mom, dad, dna); break; } if (random.nextInt(100) <= mutationRate) { mutate(dna); } return createGene(dna); } protected void crossTwoPoint(Gene mom, Gene dad, byte[] dna) { int dest, src, size; src = random.nextInt(dnaLength); dest = random.nextInt(dnaLength); size = 1 + random.nextInt(dnaLength); for (int i = 0; i < size; i++) { dna[(dest + i) % dnaLength] = dad.dna[(src + i) % dnaLength]; } } protected void crossUniform(Gene mom, Gene dad, byte[] dna) { for (int i=0; i < dnaLength; i++) { if (random.nextBoolean()) { dna[i] = dad.dna[i]; } } } protected void mutate(byte[] dna) { int dest = random.nextInt(dnaLength); int size = 1 + random.nextInt(mutationSize); int gap = 1 + random.nextInt(mutationSize); for (int i=0; i < size; i += gap) { dna[(dest + i) % dnaLength] = randomByte(); } } public byte[] getBestDNA() { return population[0].dna.clone(); } public float getBestScore() { return population[0].score; } public float getWorstScore() { return population[population.length / 2 - 1].score; } public void adjustMutationRate() { float p = getWorstScore() / getBestScore(); // TODO: That's the laziest lerp I've ever seen... mutationRate = minMutationRate + (int)(p * maxMutationRate); mutationRate = Math.max(minMutationRate, mutationRate); mutationRate = Math.min(maxMutationRate, mutationRate); } public void pin() { pinned.add(population[0]); } public void clearPinned() { pinned.clear(); } public void pin(byte[] dna) { pinned.add(createGene(dna)); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/vm/VMConsts.java
src/asmcup/vm/VMConsts.java
package asmcup.vm; public interface VMConsts extends VMFuncs { public static final int OP_FUNC = 0; public static final int OP_PUSH = 1; public static final int OP_POP = 2; public static final int OP_BRANCH = 3; public static final int MAGIC_PUSH_BYTE_MEMORY = 0; public static final int MAGIC_PUSH_FLOAT_MEMORY = 31; public static final int MAGIC_PUSH_BYTE_IMMEDIATE = 32; public static final int MAGIC_PUSH_FLOAT_IMMEDIATE = 33; public static final int MAGIC_POP_BYTE = 0; public static final int MAGIC_POP_FLOAT = 31; public static final int MAGIC_POP_BYTE_INDIRECT = 32; public static final int MAGIC_POP_FLOAT_INDIRECT = 33; public static final int MAGIC_BRANCH_ALWAYS = 31; public static final int MAGIC_BRANCH_IMMEDIATE = 32; public static final int MAGIC_BRANCH_INDIRECT = 33; }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/vm/VM.java
src/asmcup/vm/VM.java
package asmcup.vm; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Objects; public class VM implements VMConsts { private final byte[] ram; private int pc, sp; private boolean io; public VM() { this.ram = new byte[256]; } public VM(byte[] ram) { if (ram.length != 256) { throw new IllegalArgumentException("Memory must be 256 bytes"); } this.ram = ram; } public VM(DataInputStream stream) throws IOException { ram = new byte[256]; stream.readFully(ram); pc = stream.readUnsignedByte() & 0xFF; sp = stream.readUnsignedByte() & 0xFF; io = stream.readBoolean(); } @Override public boolean equals(Object obj) { if (!(obj instanceof VM)) return false; VM vm = (VM) obj; return Arrays.equals(getMemory(), vm.getMemory()) && getProgramCounter() == vm.getProgramCounter() && getStackPointer() == vm.getStackPointer() && io == vm.io; } @Override public int hashCode() { return Objects.hash(getMemory(), getProgramCounter(), getStackPointer(), io); } public void save(DataOutputStream stream) throws IOException { stream.write(ram); stream.writeByte(pc); stream.writeByte(sp); stream.writeBoolean(io); } public int getProgramCounter() { return pc; } public int getStackPointer() { return 0xFF - sp; } public byte[] getMemory() { return ram; } public int read8() { int value = ram[pc] & 0xFF; pc = (pc + 1) & 0xFF; return value; } public int read8(int addr) { return ram[addr & 0xFF] & 0xFF; } public int read8indirect() { return ram[read8()] & 0xFF; } public int read16() { return read8() | (read8() << 8); } public int read16(int addr) { return read8(addr) | (read8(addr + 1) << 8); } public int read32() { return read16() | (read16() << 16); } public int read32(int addr) { return read16(addr) | (read16(addr + 2) << 16); } public float readFloat() { return Float.intBitsToFloat(read32()); } public float readFloatIndirect() { return Float.intBitsToFloat(read32(read8())); } public void write8(int addr, int value) { ram[addr & 0xFF] = (byte)value; } public void write16(int addr, int value) { write8(addr, value); write8(addr + 1, value >> 8); } public void write32(int addr, int value) { write16(addr, value); write16(addr + 2, value >> 16); } public void writeFloat(int addr, float value) { write32(addr, Float.floatToRawIntBits(value)); } public void push8(int x) { ram[0xFF - sp] = (byte) x; sp = (sp + 1) & 0xFF; } public void push8(boolean x) { push8(x ? 1 : 0); } public void push16(int x) { push8(x); push8(x >> 8); } public void push32(int x) { push16(x); push16(x >> 16); } public void pushFloat(float x) { push32(Float.floatToRawIntBits(x)); } public int pop8() { sp = (sp - 1) & 0xFF; return ram[0xFF - sp] & 0xFF; } public int pop16() { return (pop8() << 8) | pop8(); } public int pop32() { return (pop16() << 16) | pop16(); } public float popFloat() { return Float.intBitsToFloat(pop32()); } public int peek8() { return peek8(0); } public int peek8(int r) { return ram[0xFF - ((sp - r - 1) & 0xFF)] & 0xFF; } public int peek16(int r) { return peek8(r + 1) | (peek8(r) << 8); } public int peek32(int r) { return peek16(r + 2) | (peek16(r) << 16); } public float peekFloat() { return peekFloat(0); } public float peekFloat(int r) { return Float.intBitsToFloat(peek32(r)); } public boolean checkIO() { boolean x = io; io = false; return x; } public void setIO(boolean io) { this.io = io; } public void tick() { int bits = read8(); int opcode = bits & 0b11; int data = bits >> 2; switch (opcode) { case OP_FUNC: op_func(data); break; case OP_PUSH: op_push(data); break; case OP_POP: op_pop(data); break; case OP_BRANCH: op_branch(data); break; } } public void op_func(int data) { switch (data) { case F_NOP: break; case F_B2F: pushFloat(pop8()); break; case F_F2B: push8((int)popFloat()); break; case F_NOT: push8(~pop8()); break; case F_OR: push8(pop8() | pop8()); break; case F_AND: push8(pop8() & pop8()); break; case F_XOR: push8(pop8() ^ pop8()); break; case F_SHL: push8(pop8() << 1); break; case F_SHR: push8(pop8() >> 1); break; case F_ADD8: push8(pop8() + pop8()); break; case F_SUB8: push8(pop8() - pop8()); break; case F_MUL8: push8(pop8() * pop8()); break; case F_DIV8: int a = pop8(); int b = pop8(); push8(b == 0 ? 0 : a / b); break; case F_MADD8: push8(pop8() * pop8() + pop8()); break; case F_NEGF: pushFloat(-popFloat()); break; case F_ADDF: pushFloat(popFloat() + popFloat()); break; case F_SUBF: pushFloat(popFloat() - popFloat()); break; case F_MULF: pushFloat(popFloat() * popFloat()); break; case F_DIVF: pushFloat(popFloat() / popFloat()); break; case F_MADDF: pushFloat(popFloat() * popFloat() + popFloat()); break; case F_COS: pushFloat((float) StrictMath.cos(popFloat())); break; case F_SIN: pushFloat((float) StrictMath.sin(popFloat())); break; case F_TAN: pushFloat((float) StrictMath.tan(popFloat())); break; case F_ACOS: pushFloat((float) StrictMath.acos(popFloat())); break; case F_ASIN: pushFloat((float) StrictMath.asin(popFloat())); break; case F_ATAN: pushFloat((float) StrictMath.atan(popFloat())); break; case F_ABSF: pushFloat(StrictMath.abs(popFloat())); break; case F_MINF: pushFloat(StrictMath.min(popFloat(), popFloat())); break; case F_MAXF: pushFloat(StrictMath.max(popFloat(), popFloat())); break; case F_POW: pushFloat((float) StrictMath.pow(popFloat(), popFloat())); break; case F_LOG: pushFloat((float) StrictMath.log(popFloat())); break; case F_LOG10: pushFloat((float) StrictMath.log10(popFloat())); break; case F_IF_EQ8: push8(pop8() == pop8()); break; case F_IF_NE8: push8(pop8() != pop8()); break; case F_IF_LT8: push8(pop8() < pop8()); break; case F_IF_LTE8: push8(pop8() <= pop8()); break; case F_IF_LTF: push8(popFloat() < popFloat()); break; case F_IF_LTEF: push8(popFloat() <= popFloat()); break; case F_IF_GTF: push8(popFloat() > popFloat()); break; case F_IF_GTEF: push8(popFloat() <= popFloat()); break; case F_C_0: push8(0); break; case F_C_1: push8(1); break; case F_C_2: push8(2); break; case F_C_3: push8(3); break; case F_C_4: push8(4); break; case F_C_255: push8(0xFF); break; case F_C_M1F: pushFloat(-1.0f); break; case F_C_0F: pushFloat(0.0f); break; case F_C_1F: pushFloat(1.0f); break; case F_C_2F: pushFloat(2.0f); break; case F_C_3F: pushFloat(3.0f); break; case F_C_INF: pushFloat(Float.POSITIVE_INFINITY); break; case F_ISNAN: push8(Float.isNaN(popFloat())); break; case F_DUP8: push8(peek8()); break; case F_DUPF: pushFloat(peekFloat()); break; case F_JSR: int ret = pc; pc = pop8(); push8(ret); break; case F_RET: pc = pop8(); break; case F_FT8: push8(peek8(pop8())); break; case F_FTF: pushFloat(peekFloat(pop8())); break; case F_IO: io = true; break; } } public void op_push(int data) { switch (data) { case MAGIC_PUSH_BYTE_IMMEDIATE: push8(read8()); break; case MAGIC_PUSH_BYTE_MEMORY: push8(read8indirect()); break; case MAGIC_PUSH_FLOAT_IMMEDIATE: pushFloat(readFloat()); break; case MAGIC_PUSH_FLOAT_MEMORY: pushFloat(readFloatIndirect()); break; default: push8(read8(pc + data - 32)); break; } } public void op_pop(int data) { switch (data) { case MAGIC_POP_BYTE: write8(read8(), pop8()); break; case MAGIC_POP_FLOAT: writeFloat(read8(), popFloat()); break; case MAGIC_POP_BYTE_INDIRECT: write8(read8indirect(), pop8()); break; case MAGIC_POP_FLOAT_INDIRECT: writeFloat(read8indirect(), popFloat()); break; default: write8(pc + data - 32, pop8()); break; } } public void op_branch(int data) { int addr; switch (data) { case MAGIC_BRANCH_ALWAYS: pc = read8(); break; case MAGIC_BRANCH_IMMEDIATE: addr = read8(); if (pop8() != 0) { pc = addr; } break; case MAGIC_BRANCH_INDIRECT: pc = read8indirect(); break; default: if (pop8() != 0) { pc = (pc + data - 32) & 0xFF; } break; } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/vm/VMFuncs.java
src/asmcup/vm/VMFuncs.java
package asmcup.vm; public interface VMFuncs { public static final int F_NOP = 0; // Casting public static final int F_B2F = 1; public static final int F_F2B = 2; // Bitwise (8-bit) public static final int F_NOT = 3; public static final int F_OR = 4; public static final int F_AND = 5; public static final int F_XOR = 6; public static final int F_SHL = 7; public static final int F_SHR = 8; // Arithmetic (8-bit) public static final int F_ADD8 = 9; public static final int F_SUB8 = 10; public static final int F_MUL8 = 11; public static final int F_DIV8 = 12; public static final int F_MADD8 = 13; // Arithmetic (floating) public static final int F_NEGF = 14; public static final int F_ADDF = 15; public static final int F_SUBF = 16; public static final int F_MULF = 17; public static final int F_DIVF = 18; public static final int F_MADDF = 19; // Math (floating) public static final int F_COS = 20; public static final int F_SIN = 21; public static final int F_TAN = 22; public static final int F_ACOS = 23; public static final int F_ASIN = 24; public static final int F_ATAN = 25; public static final int F_ABSF = 26; public static final int F_MINF = 27; public static final int F_MAXF = 28; public static final int F_POW = 29; public static final int F_LOG = 30; public static final int F_LOG10 = 31; // Conditional public static final int F_IF_EQ8 = 32; public static final int F_IF_NE8 = 33; public static final int F_IF_LT8 = 34; public static final int F_IF_LTE8 = 35; public static final int F_IF_GT8 = 36; public static final int F_IF_GTE8 = 37; public static final int F_IF_LTF = 38; public static final int F_IF_LTEF = 39; public static final int F_IF_GTF = 40; public static final int F_IF_GTEF = 41; // Integer constants public static final int F_C_0 = 42; public static final int F_C_1 = 43; public static final int F_C_2 = 44; public static final int F_C_3 = 45; public static final int F_C_4 = 46; public static final int F_C_255 = 47; // Float constants public static final int F_C_0F = 48; public static final int F_C_1F = 49; public static final int F_C_2F = 50; public static final int F_C_3F = 51; public static final int F_C_M1F = 52; public static final int F_C_INF = 53; public static final int F_ISNAN = 54; public static final int F_DUP8 = 55; public static final int F_DUPF = 56; public static final int F_JSR = 57; public static final int F_RET = 58; public static final int F_FT8 = 59; public static final int F_FTF = 60; public static final int F_NOP61 = 61; public static final int F_NOP62 = 62; public static final int F_IO = 63; }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/LoadWorldDialog.java
src/asmcup/sandbox/LoadWorldDialog.java
package asmcup.sandbox; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JSpinner; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import asmcup.genetics.Spawn; import asmcup.runtime.World; public class LoadWorldDialog extends JFrame { protected final Sandbox sandbox; protected final FrontPanel panel = new FrontPanel(); protected JSpinner spinnerSeed; protected JSpinner spinnerX, spinnerY; protected JSpinner spinnerFacing; protected JButton loadButton = new JButton("Load"); protected JButton showButton = new JButton("Get current"); public LoadWorldDialog(Sandbox sandbox) throws IOException { this.sandbox = sandbox; spinnerSeed = panel.createSpinner(0, Integer.MIN_VALUE, Integer.MAX_VALUE); spinnerX = panel.createSpinner(0.0f, 0f, (float)World.SIZE); spinnerY = panel.createSpinner(0.0f, 0f, (float)World.SIZE); spinnerFacing = panel.createSpinner(0.0f, -(float)Math.PI, (float)Math.PI * 2, 0.1f); panel.addRow("World Seed:", spinnerSeed); panel.addRow("Robot X:", spinnerX); panel.addRow("Robot Y:", spinnerY); panel.addRow("Robot Facing:", spinnerFacing); panel.setBorder(BorderFactory.createTitledBorder("Spawn Location")); loadButton.addActionListener(e -> load()); showButton.addActionListener(e -> update()); panel.addItems(loadButton, showButton); setTitle("Load World"); setResizable(false); setIconImage(ImageIO.read(getClass().getResource("/world.png"))); setContentPane(panel); pack(); } public void load() { Spawn spawn = new Spawn(panel.getFloat(spinnerX), panel.getFloat(spinnerY), panel.getFloat(spinnerFacing), panel.getInt(spinnerSeed)); sandbox.loadSpawn(spawn); } public void update() { spinnerSeed.setValue(sandbox.getWorld().getSeed()); spinnerX.setValue(sandbox.getRobot().getX()); spinnerY.setValue(sandbox.getRobot().getY()); spinnerFacing.setValue(sandbox.getRobot().getFacing()); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/Utils.java
src/asmcup/sandbox/Utils.java
package asmcup.sandbox; import java.io.*; import java.nio.charset.Charset; import java.nio.file.*; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; public class Utils { public static String readAsString(String path) throws IOException { return readAsString(new File(path)); } public static String readAsString(File file) throws IOException { return readAsString(file.toPath()); } public static String readAsString(Path path) throws IOException { return new String(Files.readAllBytes(path), Charset.forName("US-ASCII")); } public static String readAsString(JFrame frame, String ext, String desc) throws IOException { File file = findFileOpen(frame, ext, desc); if (file == null) { return null; } return readAsString(file); } public static String readAsString(InputStream input) throws IOException { String line; StringBuilder builder = new StringBuilder(); InputStreamReader streamReader = new InputStreamReader(input, Charset.forName("US-ASCII")); BufferedReader reader = new BufferedReader(streamReader); while ((line = reader.readLine()) != null) { builder.append(line); builder.append("\n"); } return builder.toString(); } public static byte[] readAsBytes(JFrame frame, String ext, String desc) throws IOException { File file = findFileOpen(frame, ext, desc); if (file == null) { return null; } return Files.readAllBytes(file.toPath()); } public static void write(Path path, String text) throws IOException { Files.write(path, text.getBytes("ASCII")); } public static void write(File file, String text) throws IOException { write(file.toPath(), text); } public static void write(JFrame frame, String ext, String desc, String text) throws IOException { File file = findFileSave(frame, ext, desc); if (file == null) { return; } write(file, text); } public static void write(JFrame frame, String ext, String desc, byte[] data) throws IOException { File file = findFileSave(frame, ext, desc); if (file == null) { return; } Files.write(file.toPath(), data); } public static File findFileOpen(JFrame frame, String ext, String desc) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter(desc, ext)); if (chooser.showOpenDialog(frame) != JFileChooser.APPROVE_OPTION) { return null; } return chooser.getSelectedFile(); } public static File findFileSave(JFrame frame, String ext, String desc) { JFileChooser chooser = new JFileChooser(); chooser.setFileFilter(new FileNameExtensionFilter(desc, ext)); if (chooser.showSaveDialog(frame) != JFileChooser.APPROVE_OPTION) { return null; } return getSelectedFileWithExtension(chooser); } /** * Returns the selected file from a JFileChooser, including the extension from * the file filter. * From: http://stackoverflow.com/a/18984561 */ public static File getSelectedFileWithExtension(JFileChooser c) { File file = c.getSelectedFile(); if (c.getFileFilter() instanceof FileNameExtensionFilter) { String[] exts = ((FileNameExtensionFilter)c.getFileFilter()).getExtensions(); String nameLower = file.getName().toLowerCase(); for (String ext : exts) { // check if it already has a valid extension if (nameLower.endsWith('.' + ext.toLowerCase())) { return file; // if yes, return as-is } } // if not, append the first extension from the selected filter file = new File(file.toString() + '.' + exts[0]); } return file; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/Canvas.java
src/asmcup/sandbox/Canvas.java
package asmcup.sandbox; import java.awt.*; import javax.swing.JComponent; public class Canvas extends JComponent { public final Sandbox sandbox; public final CanvasMenu menu; public Canvas(Sandbox sandbox) { this.sandbox = sandbox; this.menu = new CanvasMenu(this); setPreferredSize(new Dimension(Sandbox.WIDTH, Sandbox.HEIGHT)); setComponentPopupMenu(menu); } @Override protected void paintComponent(Graphics g) { Image backBuffer = sandbox.getBackBuffer(); if (backBuffer == null) { return; } synchronized (backBuffer) { g.drawImage(backBuffer, 0, 0, null); } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/DefaultContextMenu.java
src/asmcup/sandbox/DefaultContextMenu.java
package asmcup.sandbox; import javax.swing.*; import javax.swing.text.JTextComponent; import javax.swing.undo.UndoManager; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class DefaultContextMenu extends JPopupMenu { private Clipboard clipboard; private UndoManager undoManager; private JMenuItem undo; private JMenuItem redo; private JMenuItem cut; private JMenuItem copy; private JMenuItem paste; private JMenuItem delete; private JMenuItem selectAll; private JTextComponent jTextComponent; public DefaultContextMenu(JTextComponent jTextComponent) { setTextComponent(jTextComponent); undoManager = new UndoManager(); clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); undo = new JMenuItem("Undo"); undo.setEnabled(false); undo.setAccelerator(KeyStroke.getKeyStroke("control Z")); undo.addActionListener(event -> undoManager.undo()); add(undo); redo = new JMenuItem("Redo"); redo.setEnabled(false); redo.setAccelerator(KeyStroke.getKeyStroke("control Y")); redo.addActionListener(event -> undoManager.redo()); add(redo); add(new JSeparator()); cut = new JMenuItem("Cut"); cut.setEnabled(false); cut.setAccelerator(KeyStroke.getKeyStroke("control X")); cut.addActionListener(event -> jTextComponent.cut()); add(cut); copy = new JMenuItem("Copy"); copy.setEnabled(false); copy.setAccelerator(KeyStroke.getKeyStroke("control C")); copy.addActionListener(event -> jTextComponent.copy()); add(copy); paste = new JMenuItem("Paste"); paste.setEnabled(false); paste.setAccelerator(KeyStroke.getKeyStroke("control V")); paste.addActionListener(event -> jTextComponent.paste()); add(paste); delete = new JMenuItem("Delete"); delete.setEnabled(false); delete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)); delete.addActionListener(event -> jTextComponent.replaceSelection("")); add(delete); add(new JSeparator()); selectAll = new JMenuItem("Select All"); selectAll.setEnabled(false); selectAll.setAccelerator(KeyStroke.getKeyStroke("control A")); selectAll.addActionListener(event -> jTextComponent.selectAll()); add(selectAll); } private void setTextComponent(JTextComponent jTextComponent) { this.jTextComponent = jTextComponent; jTextComponent.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent pressedEvent) { if ((pressedEvent.getKeyCode() == KeyEvent.VK_Z) && ((pressedEvent.getModifiers() & KeyEvent.CTRL_MASK) != 0)) { if (undoManager.canUndo()) { undoManager.undo(); } } if ((pressedEvent.getKeyCode() == KeyEvent.VK_Y) && ((pressedEvent.getModifiers() & KeyEvent.CTRL_MASK) != 0)) { if (undoManager.canRedo()) { undoManager.redo(); } } } }); jTextComponent.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent releasedEvent) { if (releasedEvent.getButton() == MouseEvent.BUTTON3) { processClick(releasedEvent); } } }); jTextComponent.getDocument().addUndoableEditListener(event -> undoManager.addEdit(event.getEdit())); } private void processClick(MouseEvent event) { jTextComponent = (JTextComponent) event.getSource(); jTextComponent.requestFocus(); boolean enableUndo = undoManager.canUndo(); boolean enableRedo = undoManager.canRedo(); boolean enableCut = false; boolean enableCopy = false; boolean enablePaste = false; boolean enableDelete = false; boolean enableSelectAll = false; String selectedText = jTextComponent.getSelectedText(); String text = jTextComponent.getText(); if (text != null) { if (text.length() > 0) { enableSelectAll = true; } } if (selectedText != null) { if (selectedText.length() > 0) { enableCut = true; enableCopy = true; enableDelete = true; } } if (clipboard.isDataFlavorAvailable(DataFlavor.stringFlavor) && jTextComponent.isEnabled()) { enablePaste = true; } undo.setEnabled(enableUndo); redo.setEnabled(enableRedo); cut.setEnabled(enableCut); copy.setEnabled(enableCopy); paste.setEnabled(enablePaste); delete.setEnabled(enableDelete); selectAll.setEnabled(enableSelectAll); show(jTextComponent, event.getX(), event.getY()); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/Debugger.java
src/asmcup/sandbox/Debugger.java
package asmcup.sandbox; import java.awt.*; import java.awt.event.*; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import asmcup.runtime.Robot; public class Debugger extends JFrame { protected final Sandbox sandbox; protected MemoryPane memPane; protected JScrollPane scrollPane; protected JSlider motorSlider, steerSlider, overclockSlider; protected JSlider lazerSlider; protected JProgressBar batteryBar, sensorBar; protected JLabel goldLabel; protected FrontPanel bottomPane; protected JPanel panel; volatile protected boolean updating; public Debugger(Sandbox sandbox) throws IOException { this.sandbox = sandbox; memPane = new MemoryPane(); scrollPane = new JScrollPane(memPane); motorSlider = slider(-100, 100); steerSlider = slider(-100, 100); lazerSlider = slider(0, 100); overclockSlider = slider(0, 100); sensorBar = bar(0, 256); batteryBar = bar(0, Robot.BATTERY_MAX); goldLabel = new JLabel("0"); panel = new JPanel(new BorderLayout()); bottomPane = new FrontPanel(); //bottomPane.minimizeLabels(); bottomPane.addRow("Motor:", motorSlider); bottomPane.addRow("Steer:", steerSlider); bottomPane.addRow("Lazer:", lazerSlider); bottomPane.addRow("Clock:", overclockSlider); bottomPane.addRow("Battery:", batteryBar); bottomPane.addRow("Sensor:", sensorBar); bottomPane.addRow("Gold:", goldLabel); updating = false; panel.add(scrollPane, BorderLayout.CENTER); panel.add(bottomPane, BorderLayout.SOUTH); setTitle("Debugger"); setIconImage(ImageIO.read(getClass().getResource("/debugger.png"))); setResizable(false); setContentPane(panel); pack(); } protected JSlider slider(int min, int max) { JSlider slider = new JSlider(min, max, 0); slider.addChangeListener((e) -> updateControls()); return slider; } protected JProgressBar bar(int min, int max) { JProgressBar bar = new JProgressBar(min, max); bar.setStringPainted(true); return bar; } public void updateDebugger() { Robot robot = sandbox.getRobot(); updating = true; motorSlider.setValue((int)(robot.getMotor() * 100)); steerSlider.setValue((int)(robot.getSteer() * 100)); lazerSlider.setValue((int)(robot.getLazer() * 100)); overclockSlider.setValue(robot.getOverclock()); sensorBar.setValue((int)robot.getSensor()); batteryBar.setValue(robot.getBattery()); goldLabel.setText(String.valueOf(robot.getGold())); updating = false; repaint(); } public void updateControls() { if (updating) { return; } synchronized (sandbox.getWorld()) { Robot robot = sandbox.getRobot(); robot.setMotor(motorSlider.getValue() / 100.0f); robot.setSteer(steerSlider.getValue() / 100.0f); robot.setLazer(lazerSlider.getValue() / 100.0f); robot.setOverclock(overclockSlider.getValue()); } } protected class MemoryPane extends JComponent { protected Font font; protected int start, end; protected Mouse mouse = new Mouse(); public MemoryPane() { font = new Font(Font.MONOSPACED, Font.PLAIN, 12); setPreferredSize(new Dimension(17 * 16, 16 * 16)); addMouseListener(mouse); addMouseMotionListener(mouse); } public int transform(int x, int y) { int col = Math.max(0, (x - 16) / 16); int row = Math.max(0, y / 16); return Math.min(255, row * 16 + col); } public int transform(MouseEvent e) { return transform(e.getX(), e.getY()); } public void select(int a, int b) { start = Math.min(a, b); end = Math.max(a, b); } @Override protected void paintComponent(Graphics g) { Rectangle c = g.getClipBounds(); Robot robot = sandbox.getRobot(); g.setColor(Color.WHITE); g.fillRect(c.x, c.y, c.width, c.height); g.setFont(font); for (int row=0; row < 16; row++) { int y = 12 + row * 16; g.setColor(Color.DARK_GRAY); g.fillRect(0, row * 16, 16, 16); g.setColor(Color.WHITE); g.drawString(String.format("%02x", row * 16), 0, y); for (int col=0; col < 16; col++) { int x = 16 + col * 16; int addr = row * 16 + col; int value = robot.getVM().read8(addr); if (addr >= start && addr <= end) { g.setColor(Color.BLACK); g.fillRect(x, y - 12, 16, 16); g.setColor(Color.WHITE); } else { g.setColor(Color.BLACK); } if (addr == robot.getVM().getProgramCounter()) { g.setColor(Color.RED); } g.drawString(String.format("%02x", value), x + 1, y); if (addr == robot.getVM().getStackPointer()) { g.setColor(Color.RED); g.drawRect(x, y - 12, 16, 16); } } } } protected class Mouse extends MouseAdapter { protected boolean dragging = false; protected int dragStart; @Override public void mousePressed(MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: dragStart = transform(e); dragging = true; repaint(); break; } } @Override public void mouseReleased(MouseEvent e) { switch (e.getButton()) { case MouseEvent.BUTTON1: mouseDragged(e); dragging = false; break; } } @Override public void mouseDragged(MouseEvent e) { if (dragging) { select(dragStart, transform(e)); repaint(); } } } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/FrontPanel.java
src/asmcup/sandbox/FrontPanel.java
package asmcup.sandbox; import java.awt.*; import java.util.ArrayList; import javax.swing.*; public class FrontPanel extends JPanel { protected GridBagLayout gridLayout = new GridBagLayout(); protected GridBagConstraints cComponent = new GridBagConstraints(); protected GridBagConstraints cLabel = new GridBagConstraints(); protected GridBagConstraints cWideItem = new GridBagConstraints(); protected GridBagConstraints cItemLeft = new GridBagConstraints(); protected GridBagConstraints cItemRight = new GridBagConstraints(); protected ArrayList<JComponent> components = new ArrayList<>(); protected int currentRow = 0; public FrontPanel() { setLayout(gridLayout); cLabel.gridx = 0; cLabel.fill = GridBagConstraints.HORIZONTAL; cComponent.gridx = 1; cComponent.weightx = 1; cComponent.fill = GridBagConstraints.HORIZONTAL; cItemLeft.gridx = 0; cItemLeft.weightx = 1; cItemLeft.fill = GridBagConstraints.HORIZONTAL; cItemRight.gridx = 1; cItemRight.weightx = 1; cItemRight.fill = GridBagConstraints.HORIZONTAL; cWideItem.gridx = 0; cWideItem.gridwidth = 2; normalLabels(); } public void minimizeLabels() { cLabel.weightx = 0; } public void normalLabels() { cLabel.weightx = 1; } @SuppressWarnings("rawtypes") public JSpinner createSpinner(Number value, Comparable min, Comparable max) { return createSpinner(value, min, max, 1); } @SuppressWarnings("rawtypes") public JSpinner createSpinner(Number value, Comparable min, Comparable max, Number step) { SpinnerModel model = new SpinnerNumberModel(value, min, max, step); JSpinner spinner = new JSpinner(model); components.add(spinner); return spinner; } public JCheckBox createCheckBox() { JCheckBox checkbox = new JCheckBox(); components.add(checkbox); return checkbox; } public void setComponentsEnabled(boolean enabled) { for (JComponent component : components) { component.setEnabled(enabled); } } public int getInt(JSpinner spinner) { return (Integer)spinner.getValue(); } public float getFloat(JSpinner spinner) { return (Float)spinner.getValue(); } public void addRow(String label, JComponent component) { addRow(label, component, ""); } public void addRow(String labelText, JComponent component, String hint) { JLabel label = new JLabel(labelText); component.setToolTipText(hint); label.setToolTipText(hint); addLabelledItem(label, component); } public void addWideItem(JComponent item) { cWideItem.gridy = currentRow; add(item, cWideItem); currentRow++; } public void addLabelledItem(JLabel label, JComponent component) { cLabel.gridy = currentRow; cComponent.gridy = currentRow; add(label, cLabel); add(component, cComponent); currentRow++; } public void addItems(JComponent left, JComponent right) { cItemLeft.gridy = currentRow; cItemRight.gridy = currentRow; add(left, cItemLeft); add(right, cItemRight); currentRow++; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/Menu.java
src/asmcup/sandbox/Menu.java
package asmcup.sandbox; import java.awt.*; import java.awt.datatransfer.*; import java.awt.event.*; import java.net.URI; import java.util.Base64; import javax.swing.*; public class Menu extends JMenuBar { protected final Sandbox sandbox; protected JDialog about; public Menu(Sandbox sandbox) { this.sandbox = sandbox; addWorldMenu(); addRobotMenu(); addViewMenu(); addToolsMenu(); addGeneticsMenu(); addHelpMenu(); } protected JMenuItem item(String label, ActionListener f, KeyStroke k) { JMenuItem item = new JMenuItem(label); item.addActionListener(f); if (k != null) { item.setAccelerator(k); } return item; } protected JMenuItem item(String label, ActionListener f) { return item(label, f, null); } protected JMenuItem item(String label, ActionListener f, int key) { return item(label, f, KeyStroke.getKeyStroke(key, 0)); } public void showLoadWorld() { sandbox.loadWorld.setVisible(true); } public void singleTick() { sandbox.singleTick(); } public void setSpeed(float speed) { sandbox.setFramerate(Sandbox.DEFAULT_FRAMERATE * speed); } public void showCodeEditor() { sandbox.codeEditor.setVisible(true); } public void showDebugger() { sandbox.debugger.setVisible(true); } public void showSpawns() { sandbox.spawnsWindow.setVisible(true); } public void showEvaluator() { sandbox.evaluator.setVisible(true); } public void showGenetics() { sandbox.genetics.setVisible(true); } public void showAbout() { if (about == null) { createAbout(); } about.setVisible(true); } protected void createAbout() { String text; try { text = Utils.readAsString(getClass().getResourceAsStream("/about.txt")); } catch (Exception e) { e.printStackTrace(); sandbox.showError("Unable to load about.txt"); return; } JTextArea textArea = new JTextArea(); textArea.setEditable(false); textArea.setText(text); about = new JDialog(sandbox.frame, "About"); about.setSize(500, 350); about.setLocationRelativeTo(sandbox.frame); about.setContentPane(new JScrollPane(textArea)); } public void showGithub() { browse("https://github.com/asmcup/runtime"); } public void showHomepage() { browse("https://asmcup.github.io"); } public void browse(String url) { try { Desktop.getDesktop().browse(new URI(url)); } catch (Exception e) { e.printStackTrace(); sandbox.showError("Unable to open browser"); } } public void loadROM() { try { byte[] rom = Utils.readAsBytes(sandbox.frame, "bin", "Program Binary"); sandbox.loadROM(rom); } catch (Exception e) { e.printStackTrace(); sandbox.showError("Unable to load ROM: " + e.getMessage()); } } public void saveROM() { try { Utils.write(sandbox.frame, "bin", "Program Binary", sandbox.getROM()); } catch (Exception e) { e.printStackTrace(); sandbox.showError("Unable to save ROM: " + e.getMessage()); } } public void copyROM() { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); String encoded = Base64.getEncoder().encodeToString(sandbox.getROM()); try { clipboard.setContents(new StringSelection(encoded), null); } catch (Exception e) { e.printStackTrace(); sandbox.showError("Unable to copy ROM: " + e.getMessage()); } } public void pasteROM() { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); String text = ""; byte[] rom; try { text = (String)clipboard.getData(DataFlavor.stringFlavor); rom = Base64.getDecoder().decode(text); if (rom == null || rom.length != 256) { sandbox.showError("Program must be 256 bytes"); return; } } catch (Exception e) { e.printStackTrace(); sandbox.showError("Unable to paste: " + e.getMessage()); return; } sandbox.loadROM(rom); } protected void addRobotMenu() { JMenu menu = new JMenu("Robot"); menu.add(item("Load ROM...", e-> loadROM())); menu.add(item("Save ROM...", e-> saveROM())); menu.add(item("Paste ROM", e-> pasteROM())); menu.add(item("Copy ROM", e -> copyROM())); menu.addSeparator(); menu.add(item("Flash", e -> sandbox.flash(), KeyEvent.VK_F)); add(menu); } protected void addWorldMenu() { JMenu menu = new JMenu("World"); menu.add(item("Generate New", e -> sandbox.reseed(), KeyEvent.VK_N)); menu.add(item("Reset", e -> sandbox.resetWorld(), KeyEvent.VK_R)); menu.add(item("Load World", e -> showLoadWorld(), KeyEvent.VK_L)); menu.addSeparator(); menu.add(item("Pause/Resume", e -> sandbox.togglePaused(), KeyEvent.VK_P)); menu.add(item("Single tick", e -> singleTick(), KeyEvent.VK_T)); addSpeedMenu(menu); menu.addSeparator(); menu.add(item("Quit", e -> sandbox.quit(), KeyEvent.VK_ESCAPE)); add(menu); } private void addSpeedMenu(JMenu menu) { JMenu speedMenu = new JMenu("Simulation speed"); speedMenu.add(item("0.5x", e -> setSpeed(0.5f))); speedMenu.add(item("1x", e -> setSpeed(1f))); speedMenu.add(item("2x", e -> setSpeed(2f))); speedMenu.add(item("4x", e -> setSpeed(4f))); speedMenu.add(item("10x", e -> setSpeed(10f))); menu.add(speedMenu); } protected void addViewMenu() { JMenu menu = new JMenu("View"); menu.add(item("Toggle Grid", e -> sandbox.toggleGrid(), KeyStroke.getKeyStroke(KeyEvent.VK_G, ActionEvent.CTRL_MASK))); menu.addSeparator(); menu.add(item("Center Camera", e -> sandbox.centerView(), KeyEvent.VK_SPACE)); menu.add(item("Lock Camera", e -> sandbox.toggleLockCenter(), KeyEvent.VK_C)); add(menu); } protected void addToolsMenu() { JMenu menu = new JMenu("Tools"); menu.add(item("Code Editor", e -> showCodeEditor(), KeyEvent.VK_E)); menu.add(item("Debugger", e -> showDebugger(), KeyEvent.VK_D)); menu.add(item("Spawns", e -> showSpawns(), KeyEvent.VK_S)); menu.add(item("Evaluator", e -> showEvaluator(), KeyEvent.VK_V)); menu.add(item("Genetics", e-> showGenetics(), KeyEvent.VK_G)); add(menu); } protected void addHelpMenu() { JMenu menu = new JMenu("Help"); menu.add(item("Homepage", e -> showHomepage())); menu.add(item("Github Project", e -> showGithub())); menu.add(item("About", e -> showAbout())); add(menu); } protected void addGeneticsMenu() { add(sandbox.genetics.getMenu()); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/Sandbox.java
src/asmcup/sandbox/Sandbox.java
package asmcup.sandbox; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.*; import asmcup.evaluation.EvaluatorWindow; import asmcup.evaluation.Spawns; import asmcup.evaluation.SpawnsWindow; import asmcup.genetics.*; import asmcup.runtime.*; import asmcup.runtime.Robot; import asmcup.runtime.TILE; public class Sandbox { public final Mouse mouse; public final Menu menu; public final Canvas canvas; public final JFrame frame; public final LoadWorldDialog loadWorld; public final CodeEditor codeEditor; public final Debugger debugger; public final EvaluatorWindow evaluator; public final Genetics genetics; public final Spawns spawns; public final SpawnsWindow spawnsWindow; protected Image backBuffer; protected World world; protected Robot robot; protected int panX, panY; protected boolean paused = false; protected float frameRate = DEFAULT_FRAMERATE; protected Image[] ground, wall, obstacles, hazards, floor; protected Image[] coins, batteryImg; protected Image bot; protected boolean showGrid; protected boolean lockCenter; protected byte[] rom = new byte[256]; public Sandbox() throws IOException { reseed(); // Core components mouse = new Mouse(this); canvas = new Canvas(this); frame = new JFrame("Sandbox"); // Modules loadWorld = new LoadWorldDialog(this); codeEditor = new CodeEditor(this); debugger = new Debugger(this); spawns = new Spawns(this); spawnsWindow = new SpawnsWindow(this); evaluator = new EvaluatorWindow(this); genetics = new Genetics(this); // Menu gets built last menu = new Menu(this); canvas.addMouseListener(mouse); canvas.addMouseMotionListener(mouse); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setJMenuBar(menu); frame.setContentPane(canvas); frame.pack(); ground = loadImage("/ground.png"); wall = loadImage("/wall.png"); obstacles = loadImage("/obstacles.png"); hazards = loadImage("/hazards.png"); bot = ImageIO.read(getClass().getResource("/robot.png")); coins = loadImage("/gold.png"); floor = loadImage("/floor.png"); batteryImg = loadImage("/battery.png"); frame.setIconImage(bot); } public int getPanX() { return panX; } public int getPanY() { return panY; } public World getWorld() { return world; } public Robot getRobot() { return robot; } public byte[] getROM() { return rom; } public void setROM(byte[] rom) { if (rom.length != 256) { throw new IllegalArgumentException("ROM must be 256 bytes"); } this.rom = rom; } public void flash() { synchronized (world) { Robot old = robot; world.removeRobot(old); robot = new Robot(1, rom); robot.position(old.getX(), old.getY()); robot.setFacing(old.getFacing()); world.addRobot(robot); } } public void loadROM(byte[] rom) { setROM(rom); flash(); } public void showError(String msg) { JOptionPane.showMessageDialog(frame, msg); } public void pan(int dx, int dy) { panX += dx; panY += dy; } protected Image[] loadImage(String path) throws IOException { URL url = getClass().getResource(path); Image sheet = ImageIO.read(url); Image[] variants = new Image[4]; for (int i=0; i < 4; i++) { Image img = new BufferedImage(World.TILE_SIZE, World.TILE_SIZE, BufferedImage.TYPE_INT_ARGB); Graphics g = img.getGraphics(); g.drawImage(sheet, -i * World.TILE_SIZE, 0, null); variants[i] = img; } return variants; } public void run() { long lastTick; frame.setVisible(true); while (frame.isVisible()) { lastTick = System.currentTimeMillis(); if (!paused) { tick(); } tickWait(lastTick); } } protected void tick() { synchronized (world) { if (lockCenter) { centerView(); } world.tick(); debugger.updateDebugger(); redraw(); } } protected void tickWait(long lastTick) { long now = System.currentTimeMillis(); long span = now - lastTick; int msPerFrame = Math.round(1000 / frameRate); int wait = (int)(msPerFrame - span); sleep(wait); } public void togglePaused() { paused = !paused; redraw(); } public void singleTick() { if (paused) { tick(); } } public void setFramerate(float f) { frameRate = f; } public void reseed() { world = new World(); if (robot == null) { robot = new Robot(1); } world.randomizePosition(robot); centerView(); world.addRobot(robot); redraw(); } public void resetWorld() { resetWorld(world.getSeed()); } public void resetWorld(int seed) { synchronized (this) { world = new World(seed); world.addRobot(robot); } redraw(); } public void loadSpawn(Spawn spawn) { robot.position(spawn.x, spawn.y); robot.setFacing(spawn.facing); resetWorld(spawn.seed); centerView(); } public void centerView() { panX = (int)robot.getX(); panY = (int)robot.getY(); redraw(); } public void draw() { if (backBuffer == null) { return; } Graphics2D g = (Graphics2D)backBuffer.getGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, WIDTH, HEIGHT); AffineTransform originalTransform = g.getTransform(); g.translate(WIDTH/2 - panX, HEIGHT/2 - panY); int left = (int)Math.floor((panX - WIDTH/2.0) / World.CELL_SIZE); int right = (int)Math.ceil((panX + WIDTH/2.0) / World.CELL_SIZE); int top = (int)Math.floor((panY - HEIGHT/2.0) / World.CELL_SIZE); int bottom = (int)Math.ceil((panY + HEIGHT/2.0) / World.CELL_SIZE); left = Math.max(0, left); right = Math.max(0, right); top = Math.max(0, top); bottom = Math.max(0, bottom); for (int cellY=top; cellY < bottom; cellY++) { for (int cellX=left; cellX < right; cellX++) { drawCell(g, world.getCell(cellX, cellY)); } } for (Robot robot : world.getRobots()) { drawRobot(g, robot); } g.setColor(Color.PINK); for (Spawn spawn : spawns.getIterable()) { int x = (int)spawn.x; int y = (int)spawn.y; g.drawLine(x - 4, y, x + 4, y); g.drawLine(x, y - 4, x, y + 4); } g.setTransform(originalTransform); if (paused) { g.setColor(Color.WHITE); g.drawString("PAUSED", 25, 50); } } protected void drawCell(Graphics2D g, Cell cell) { int left = cell.getX() * World.TILES_PER_CELL; int right = left + World.TILES_PER_CELL; int top = cell.getY() * World.TILES_PER_CELL; int bottom = top + World.TILES_PER_CELL; for (int row=top; row < bottom; row++) { for (int col=left; col < right; col++) { int tile = world.getTile(col, row); drawTile(g, col, row, tile); } } for (Item item : cell.getItems()) { drawItem(g, item); } if (showGrid) { g.setColor(Color.WHITE); int x = left * World.TILE_SIZE; int y = top * World.TILE_SIZE; g.drawRect(x, y, World.CELL_SIZE, World.CELL_SIZE); String msg = String.format("%d, %d", cell.getX(), cell.getY()); g.drawString(msg, x + 100, y + 100); msg = String.format("%x", cell.getKey()); g.drawString(msg, x + 100, y + 150); } } protected void drawTile(Graphics2D g, int col, int row, int tile) { int x = col * World.TILE_SIZE; int y = row * World.TILE_SIZE; int variant = (tile >> 3) & 0b11; switch (tile & 0b111) { case TILE.GROUND: drawVariant(g, ground, x, y, variant); break; case TILE.OBSTACLE: drawVariant(g, ground, x, y, variant ^ 0b11); drawVariant(g, obstacles, x, y, variant); break; case TILE.WALL: drawVariant(g, wall, x, y, variant); break; case TILE.HAZARD: drawVariant(g, hazards, x, y, variant); break; case TILE.FLOOR: drawVariant(g, floor, x, y, variant); break; } } protected void drawRobot(Graphics2D g, Robot robot) { int rx = (int)robot.getX(); int ry = (int)robot.getY(); AffineTransform t = g.getTransform(); g.rotate(robot.getFacing(), rx, ry); g.drawImage(bot, rx - World.TILE_HALF, ry - World.TILE_HALF, null); g.setTransform(t); g.rotate(robot.getBeamAngle(), rx, ry); if (robot.getLazerEnd() > 0) { int w = (int)(robot.getLazerEnd()); g.setColor(Color.RED); g.drawLine(rx, ry, rx + w, ry); } if (world.getFrame() - robot.getSensorFrame() < 3) { int w = (int)(robot.getSensor()); g.setColor(Color.BLUE); g.drawLine(rx, ry, rx + w, ry); } g.setTransform(t); if (showGrid) { g.setColor(Color.RED); g.fillRect(rx - 1, ry - 1, 3, 3); } } protected void drawItem(Graphics2D g, Item item) { if (item instanceof Item.Battery) { drawItemBattery(g, (Item.Battery)item); } else if (item instanceof Item.Gold) { drawItemGold(g, (Item.Gold)item); } if (showGrid) { g.setColor(Color.RED); g.fillRect((int)item.getX(), (int)item.getY(), 2, 2); } } protected void drawItemBattery(Graphics2D g, Item.Battery battery) { int x = (int)battery.getX(); int y = (int)battery.getY(); drawVariant(g, batteryImg, x - 16, y - 16, battery.getVariant()); } protected void drawItemGold(Graphics2D g, Item.Gold gold) { int x = (int)gold.getX(); int y = (int)gold.getY(); drawVariant(g, coins, x - 16, y - 16, gold.getVariant()); } protected void drawVariant(Graphics2D g, Image[] imgs, int x, int y, int variant) { g.drawImage(imgs[variant], x, y, null); } public static void sleep(int ms) { if (ms <= 0) { return; } try { Thread.sleep(ms); } catch (InterruptedException e) { } } protected Image createBackBuffer() { Image img = frame.createVolatileImage(WIDTH, HEIGHT); if (img == null) { return null; } Graphics g = img.getGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, WIDTH, HEIGHT); return img; } public void redraw() { if (backBuffer != null) { synchronized (backBuffer) { draw(); } frame.repaint(); } } public Image getBackBuffer() { if (backBuffer == null) { backBuffer = createBackBuffer(); } return backBuffer; } public void quit() { System.exit(0); } public void toggleGrid() { showGrid = !showGrid; redraw(); } public void toggleLockCenter() { lockCenter = !lockCenter; } public static final int WIDTH = 800; public static final int HEIGHT = 600; public static final int DEFAULT_FRAMERATE = 10; }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/Mouse.java
src/asmcup/sandbox/Mouse.java
package asmcup.sandbox; import java.awt.event.*; public class Mouse extends MouseAdapter { public final Sandbox sandbox; protected boolean panning; protected int screenX, screenY; protected int worldX, worldY; protected int panStartX, panStartY; public Mouse(Sandbox sandbox) { this.sandbox = sandbox; } public int getWorldX() { return worldX; } public int getWorldY() { return worldY; } protected void update(MouseEvent e) { screenX = e.getX(); screenY = e.getY(); worldX = sandbox.getPanX() + screenX - Sandbox.WIDTH / 2; worldY = sandbox.getPanY() + screenY - Sandbox.HEIGHT / 2; } protected void startPanning() { panStartX = screenX; panStartY = screenY; panning = true; sandbox.redraw(); } protected void pan() { int dx = panStartX - screenX; int dy = panStartY - screenY; sandbox.pan(dx, dy); sandbox.redraw(); panStartX = screenX; panStartY = screenY; } protected void finishPanning() { panning = false; sandbox.redraw(); } @Override public void mousePressed(MouseEvent e) { update(e); switch (e.getButton()) { case MouseEvent.BUTTON1: startPanning(); break; } } @Override public void mouseReleased(MouseEvent e) { update(e); switch (e.getButton()) { case MouseEvent.BUTTON1: finishPanning(); break; } } @Override public void mouseDragged(MouseEvent e) { update(e); if (panning) { pan(); } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/CanvasMenu.java
src/asmcup/sandbox/CanvasMenu.java
package asmcup.sandbox; import java.awt.event.*; import javax.swing.*; import asmcup.runtime.*; public class CanvasMenu extends JPopupMenu { public final Sandbox sandbox; public final Canvas canvas; public CanvasMenu(Canvas canvas) { this.canvas = canvas; this.sandbox = canvas.sandbox; add("Teleport", e -> teleport(e)); add("Flash & Teleport", e -> flashAndTeleport(e)); addSeparator(); add("Add Gold Item", e -> addGoldItem(e)); add("Add Battery Item", e -> addBatteryItem(e)); addSeparator(); add("Add Genetics Spawn", e -> addGeneticSpawn(e)); add("Add Genetics Reward", e -> addGeneticReward(e)); } public void teleport(ActionEvent e) { Mouse mouse = sandbox.mouse; World world = sandbox.getWorld(); Robot robot = sandbox.getRobot(); synchronized (world) { robot.position(mouse.getWorldX(), mouse.getWorldY()); sandbox.redraw(); } } public void flashAndTeleport(ActionEvent e) { sandbox.flash(); teleport(e); } public void addGoldItem(ActionEvent e) { Mouse mouse = sandbox.mouse; Item gold = new Item.Gold(); sandbox.getWorld().addItem(mouse.getWorldX(), mouse.getWorldY(), gold); } public void addBatteryItem(ActionEvent e) { Mouse mouse = sandbox.mouse; Item battery = new Item.Battery(); sandbox.getWorld().addItem(mouse.getWorldX(), mouse.getWorldY(), battery); } public void addGeneticSpawn(ActionEvent e) { sandbox.spawns.addSpawnAtMouse(); } public void addGeneticReward(ActionEvent e) { } protected void add(String label, ActionListener listener) { JMenuItem item = new JMenuItem(label); item.addActionListener(listener); add(item); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/Main.java
src/asmcup/sandbox/Main.java
package asmcup.sandbox; import java.io.IOException; import javax.swing.UIManager; public class Main { public static void main(String[] args) throws IOException { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { // Don't care if theme can't be set } Sandbox sandbox = new Sandbox(); sandbox.run(); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/sandbox/CodeEditor.java
src/asmcup/sandbox/CodeEditor.java
package asmcup.sandbox; import java.awt.*; import java.awt.datatransfer.*; import java.awt.dnd.*; import java.awt.event.*; import java.io.*; import java.util.List; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.border.BevelBorder; import javax.swing.text.PlainDocument; import asmcup.compiler.Compiler; import asmcup.decompiler.Decompiler; public class CodeEditor extends JFrame { protected final Sandbox sandbox; protected JEditorPane editor; protected JLabel statusLabel; protected Menu menu; protected byte[] ram = new byte[256]; protected File currentFile; public CodeEditor(Sandbox sandbox) throws IOException { this.sandbox = sandbox; this.editor = new JEditorPane(); this.statusLabel = new JLabel(); this.menu = new Menu(); JPanel statusBar = new JPanel(); statusBar.add(statusLabel); statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED)); JPanel contentPanel = new JPanel(); contentPanel.setLayout(new BorderLayout()); contentPanel.add(new JScrollPane(editor), BorderLayout.CENTER); contentPanel.add(statusBar, BorderLayout.PAGE_END); setTitle("Code Editor"); setSize(400, 400); setContentPane(contentPanel); setJMenuBar(menu); setIconImage(ImageIO.read(getClass().getResource("/notepad.png"))); editor.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); editor.getDocument().putProperty(PlainDocument.tabSizeAttribute, 2); new DefaultContextMenu(editor); editor.setDropTarget(new DropTarget() { public synchronized void drop(DropTargetDropEvent e) { try { dropFiles(e); } catch (Exception ex) { ex.printStackTrace(); } } }); } public void dropFiles(DropTargetDropEvent e) throws Exception { e.acceptDrop(DnDConstants.ACTION_COPY); Object obj = e.getTransferable().getTransferData(DataFlavor.javaFileListFlavor); @SuppressWarnings("unchecked") List<File> droppedFiles = (List<File>) obj; if (droppedFiles.size() != 0) { openFile(droppedFiles.get(0)); } } public void openFile() { if (currentFile == null) { currentFile = findFileOpen(); } if (currentFile == null) { return; } try { String text = Utils.readAsString(currentFile); editor.setText(text); } catch (Exception e) { e.printStackTrace(); } setTitle(currentFile.getName() + " - Code Editor"); } public void openFile(File file) { currentFile = file; openFile(); } public void closeFile() { editor.setText(""); setTitle("Code Editor"); } public void closeEditor() { setVisible(false); } public boolean compile() { Compiler compiler = new Compiler(); try { ram = compiler.compile(editor.getText()); statusLabel.setText(String.format("Bytes used: %d", compiler.getBytesUsed())); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, e.getMessage()); return false; } return true; } public void flash() { synchronized (sandbox.getWorld()) { sandbox.loadROM(ram.clone()); } } public void compileAndFlash() { if (compile()) { flash(); } } public void decompile() { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { Decompiler decompiler = new Decompiler(new PrintStream(out, false, "UTF-8")); decompiler.decompile(sandbox.getROM()); editor.setText(out.toString("UTF-8")); } catch (UnsupportedEncodingException e) { sandbox.showError("Unsupported encoding..."); } } public File findFileSave() { return Utils.findFileSave(sandbox.frame, "asm", "Source File (.asm)"); } public File findFileOpen() { return Utils.findFileOpen(sandbox.frame, "asm", "Source File (.asm)"); } public void saveFile() { if (currentFile == null) { currentFile = findFileSave(); } save(currentFile); } public void save(File file) { if (file == null) { return; } try { Utils.write(file, editor.getText()); } catch (IOException e) { e.printStackTrace(); } } public void saveFileAs() { save(findFileSave()); } protected class Menu extends JMenuBar { public Menu() { addFileMenu(); addCompileMenu(); } protected JMenuItem item(String label, ActionListener f, KeyStroke shortcut) { JMenuItem item = new JMenuItem(); item.setAction(new AbstractAction(label) { public void actionPerformed(ActionEvent e) { f.actionPerformed(e); } }); if (shortcut != null) { item.setAccelerator(shortcut); } return item; } protected void addFileMenu() { JMenu menu = new JMenu("File"); menu.add(item("New Code", e -> closeFile(), KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK))); menu.add(item("Open Code...", e -> openFile(null), KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK))); menu.add(item("Reload Code", e -> openFile(), KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK))); menu.addSeparator(); menu.add(item("Save Code", e -> saveFile(), KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK))); menu.add(item("Save Code As...", e -> saveFileAs(), KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.ALT_MASK | ActionEvent.CTRL_MASK))); menu.addSeparator(); menu.add(item("Close Editor", (e) -> closeEditor(), KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK))); add(menu); } protected void addCompileMenu() { JMenu menu = new JMenu("Tools"); menu.add(item("Compile & Flash", e -> compileAndFlash(), KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK))); menu.add(item("Compile", e -> compile(), null)); menu.add(item("Flash", e -> flash(), null)); menu.addSeparator(); menu.add(item("Decompile current ROM", e -> decompile(), null)); add(menu); } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/evaluation/SpawnsWindow.java
src/asmcup/evaluation/SpawnsWindow.java
package asmcup.evaluation; import java.awt.Dimension; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import asmcup.genetics.Spawn; import asmcup.sandbox.*; public class SpawnsWindow extends JFrame { protected final Sandbox sandbox; protected final Spawns spawns; protected final FrontPanel panel = new FrontPanel(); protected JList<Spawn> spawnList; protected JButton addButton = new JButton("Add current"); protected JButton deleteButton = new JButton("Delete"); protected JButton applyButton = new JButton("Show"); protected JButton clearButton = new JButton("Clear"); public SpawnsWindow(Sandbox sandbox) throws IOException { this.sandbox = sandbox; spawns = sandbox.spawns; //listModel = new SpawnListModel(); spawnList = new JList<Spawn>(spawns); spawnList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); spawnList.setLayoutOrientation(JList.VERTICAL); spawnList.setVisibleRowCount(-1); JScrollPane listScroller = new JScrollPane(spawnList); listScroller.setPreferredSize(new Dimension(420, 240)); addButton.addActionListener(e -> addCurrent()); deleteButton.addActionListener(e -> deleteOne()); applyButton.addActionListener(e -> applyOne()); clearButton.addActionListener(e -> clear()); panel.addWideItem(listScroller); panel.addItems(addButton, deleteButton); panel.addItems(applyButton, clearButton); setContentPane(panel); setTitle("Spawn Manager"); setIconImage(ImageIO.read(getClass().getResource("/plus.png"))); setResizable(false); pack(); } public void addCurrent() { spawns.addSpawnAtRobot(); spawnList.setSelectedIndex(spawns.size() - 1); } public void deleteOne() { selectLastIfNone(); int index = spawnList.getSelectedIndex(); // Error handling happens in there. Can't trust JList apparently. spawns.remove(index); selectLastIfNone(); } public void applyOne() { selectLastIfNone(); Spawn spawn = spawnList.getSelectedValue(); if (spawn != null) { sandbox.loadSpawn(spawn); } } public void selectLastIfNone() { if (spawnList.getSelectedValue() == null) { spawnList.setSelectedIndex(spawns.size() - 1); } } public void clear() { spawns.clear(); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/evaluation/Spawns.java
src/asmcup/evaluation/Spawns.java
package asmcup.evaluation; import java.util.*; import javax.swing.ListModel; import javax.swing.event.*; import asmcup.genetics.Spawn; import asmcup.runtime.*; import asmcup.sandbox.*; public class Spawns implements ListModel<Spawn> { private ArrayList<Spawn> spawns = new ArrayList<>(); protected final Sandbox sandbox; ArrayList<ListDataListener> listeners = new ArrayList<>(); public Spawns(Sandbox sandbox) { this.sandbox = sandbox; } public AbstractCollection<Spawn> getIterable() { return new ArrayList<Spawn>(spawns); } public void addSpawnAtMouse() { Mouse mouse = sandbox.mouse; Robot robot = sandbox.getRobot(); World world = sandbox.getWorld(); Spawn spawn = new Spawn(mouse.getWorldX(), mouse.getWorldY(), robot.getFacing(), world.getSeed()); add(spawn); } public void addSpawnAtRobot() { Robot robot = sandbox.getRobot(); World world = sandbox.getWorld(); Spawn spawn = new Spawn(robot.getX(), robot.getY(), robot.getFacing(), world.getSeed()); add(spawn); } public boolean add(Spawn spawn) { spawns.add(spawn); notifyListeners(spawns.size()-1, spawns.size()-1); return true; } public Spawn remove(int index) { if (index < 0 || index >= spawns.size()) { return null; } Spawn ret = spawns.remove(index); notifyListeners(index, size()); return ret; } public void clear() { int previousSize = spawns.size(); spawns.clear(); notifyListeners(0, previousSize-1); } public int getCombinedSeed() { int seed = 0; for (Spawn spawn : spawns) { seed += spawn.seed; } return seed; } public int size() { return spawns.size(); } public int getSize() { return spawns.size(); } public Spawn getElementAt(int index) { if (index < 0 || index >= size()) { return null; } return spawns.get(index); } private void notifyListeners(int index0, int index1) { for (ListDataListener l : listeners) { // Yeah, lazy, I know. l.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, index0, index1)); } sandbox.redraw(); } @Override public void addListDataListener(ListDataListener l) { listeners.add(l); } @Override public void removeListDataListener(ListDataListener l) { listeners.remove(l); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/evaluation/Evaluator.java
src/asmcup/evaluation/Evaluator.java
package asmcup.evaluation; import java.util.HashSet; import asmcup.genetics.Spawn; import asmcup.runtime.Robot; import asmcup.runtime.World; import asmcup.vm.VM; //TODO: Add Evaluator test(s)! //- Evaluate same spawn x times public class Evaluator { final public boolean simplified; public int maxSimFrames; public int directionsPerSpawn; public int extraWorldCount; public int idleMax; public int idleIoMax; public int exploreReward; public int ramPenalty; public int goldReward; public int batteryReward; public int forceStack; public boolean temporal; public boolean forceIO; public long scoringCount = 0; public int baseSeed = 0; public Evaluator(boolean simplified) { this.simplified = simplified; maxSimFrames = 10 * 60; directionsPerSpawn = simplified ? 1 : 8; extraWorldCount = 0; idleMax = 0; idleIoMax = 0; exploreReward = simplified ? 0 : 4; ramPenalty = simplified ? 0 : 2; goldReward = 50; batteryReward = simplified ? 0 : 50; temporal = simplified ? false : true; forceIO = false; } // TODO: Make more transparent for threading... public float score(byte[] ram) { scoringCount = 0; Scorer scorer = new Scorer(); float score = 0.0f; for (int i = 0; i < extraWorldCount; i++) { score += scorer.calculate360(ram, Spawn.randomFromSeed(baseSeed + i)); } return score / Math.max(scoringCount, 1); } protected class Scorer { private Robot robot; private VM vm; private World world; private int lastGold; private int lastBattery; private HashSet<Integer> rammed; private HashSet<Integer> explored; private int lastExplored; public float calculate360(byte[] ram, Spawn spawn) { float score = 0.0f; for (float turn = 0; turn < 360f; turn += 360f / directionsPerSpawn) { score += calculate(ram, spawn, (float)Math.toRadians(turn)); } return score; } public float calculate(byte[] ram, Spawn spawn, float turn) { vm = new VM(ram.clone()); robot = new Robot(1, vm); world = spawn.getNewWorld(); world.addRobot(robot); robot.position(spawn.x, spawn.y); robot.setFacing(spawn.facing + turn); float score = 0.0f; lastGold = 0; lastBattery = robot.getBattery(); explored = new HashSet<>(); rammed = new HashSet<>(); lastExplored = 0; for (int frame = 0; frame < maxSimFrames; frame++) { world.tick(); if (violatesStackRules()) { break; } if (violatesIoRules()) { break; } if (robot.isDead()) { break; } float t = getTimeBenefitFactor(frame); score += rewardGoldCollection(t); score += rewardBatteryCollection(t); int tileKey = getTileKey(); score += rewardExploration(tileKey, t, frame); score -= penaliseRamming(tileKey, t); lastGold = robot.getGold(); lastBattery = robot.getBattery(); if (idledTooLong(frame)) { break; } if (ioIdledTooLong(frame)) { break; } score += 0.001f; } scoringCount++; return score; } private boolean violatesIoRules() { return forceIO && robot.getLastInvalidIO() > 0; } private boolean violatesStackRules() { if (forceStack <= 0) { return false; } int stackLimit = (0xFF - forceStack); int sp = vm.getStackPointer(); int pc = vm.getProgramCounter(); return sp < stackLimit || pc > stackLimit; } private float getTimeBenefitFactor(int frame) { return (temporal ? 1.0f - (float)frame / (float)maxSimFrames : 1.0f); } private float rewardGoldCollection(float t) { return (robot.getGold() == lastGold) ? 0 : t * goldReward; } private float rewardBatteryCollection(float t) { return (robot.getBattery() <= lastBattery) ? 0 : t * batteryReward; } private int getTileKey() { int col = (int)(robot.getX() / World.TILE_SIZE); int row = (int)(robot.getY() / World.TILE_SIZE); return col | (row << 16); } private float rewardExploration(int key, float t, int frame) { if (explored.add(key)) { lastExplored = frame; return t * exploreReward; } return 0; } private float penaliseRamming(int tileKey, float t) { if (ramPenalty == 0) { return 0; } if (robot.isRamming()) { if (rammed.add(tileKey)) { return t * ramPenalty; } else { return t * ramPenalty * 0.01f; } } return 0; } private boolean idledTooLong(int frame) { return idleMax > 0 && (frame - lastExplored) > idleMax; } private boolean ioIdledTooLong(int frame) { return idleIoMax > 0 && (frame - robot.getLastIO()) > idleIoMax; } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/evaluation/SpawnEvaluator.java
src/asmcup/evaluation/SpawnEvaluator.java
package asmcup.evaluation; import asmcup.genetics.Spawn; public class SpawnEvaluator extends Evaluator { final protected Spawns spawns; public SpawnEvaluator(Spawns spawns, boolean simplified) { super(simplified); this.spawns = spawns; } @Override public float score(byte[] ram) { baseSeed = spawns.getCombinedSeed(); float score = super.score(ram) * scoringCount; Scorer scorer = new Scorer(); for (Spawn spawn : spawns.getIterable()) { score += scorer.calculate360(ram, spawn); } return score / Math.max(scoringCount, 1); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/evaluation/EvaluatorWindow.java
src/asmcup/evaluation/EvaluatorWindow.java
package asmcup.evaluation; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import asmcup.sandbox.FrontPanel; import asmcup.sandbox.Sandbox; public class EvaluatorWindow extends JFrame { protected final Sandbox sandbox; public final SpawnEvaluator evaluator; public final EvaluatorFrontPanel evalPanel; public final FrontPanel panel = new FrontPanel(); protected JButton startButton = new JButton("Start"); protected JButton stopButton = new JButton("Stop"); protected JLabel scoreLabel = new JLabel("0"); public EvaluatorWindow(Sandbox sandbox) throws IOException { this.sandbox = sandbox; evaluator = new SpawnEvaluator(sandbox.spawns, true); evalPanel = new EvaluatorFrontPanel(evaluator); panel.addWideItem(evalPanel); panel.addItems(startButton, stopButton); panel.addRow("ROM score:", scoreLabel); startButton.addActionListener(e -> evaluate()); stopButton.addActionListener(e -> stop()); setContentPane(panel); setTitle("User Bot Evaluator"); setResizable(false); setIconImage(ImageIO.read(getClass().getResource("/gauge.png"))); pack(); } public void evaluate() { evalPanel.updateEvaluator(); if (!quickScoring()) { // TODO: Threading, don't want to block the UI. // Bit difficult with how Evaluator works though. } // (else) float score = evaluator.score(sandbox.getROM()); scoreLabel.setText(String.valueOf(score)); } public void stop() { } protected boolean quickScoring() { return evaluator.maxSimFrames * evaluator.extraWorldCount < 2000; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/evaluation/EvaluatorFrontPanel.java
src/asmcup/evaluation/EvaluatorFrontPanel.java
package asmcup.evaluation; import javax.swing.*; import asmcup.sandbox.*; public class EvaluatorFrontPanel extends FrontPanel { protected final Evaluator evaluator; // Note: These initial values are not authoritative, the ones in Evaluator are. protected JSpinner frameSpinner = createSpinner(10 * 60, 1, 10 * 60 * 60 * 24); protected JSpinner extraWorldSpinner = createSpinner(0, 0, 100); protected JSpinner orientationSpinner = createSpinner(0, 0, 100); protected JSpinner idleSpinner = createSpinner(0, 0, 1000 * 1000); protected JSpinner idleIoSpinner = createSpinner(0, 0, 1000 * 1000); protected JSpinner exploreSpinner = createSpinner(4, -1000, 1000); protected JSpinner rammingSpinner = createSpinner(2, -1000, 1000); protected JSpinner goldSpinner = createSpinner(50, -1000, 1000); protected JSpinner batterySpinner = createSpinner(100, -1000, 1000); protected JCheckBox temporalCheckBox = createCheckBox(); protected JSpinner stackSpinner = createSpinner(0, 0, 256); protected JCheckBox ioCheckBox = createCheckBox(); public EvaluatorFrontPanel(Evaluator evaluator) { this.evaluator = evaluator; setBorder(BorderFactory.createTitledBorder("Evaluation Metrics")); addRow("Random Tests:", extraWorldSpinner, "Bots are evaluated in this many additional random worlds"); addRow("Orientations:", orientationSpinner, "Amount of facing directions evaluated for each start point"); addRow("Frames:", frameSpinner, "Maximum number of frames for the simulation (10 frames = 1 second)"); addRow("Gold Reward:", goldSpinner, "Number of points earned by collecting a gold item"); addRow("Battery Reward:", batterySpinner, "Number of points earned by collecting a battery item"); addRow("Explore Reward:", exploreSpinner, "Number of points earned by touching a new tile"); addRow("Collide Penalty:", rammingSpinner, "Number of points lost by ramming a tile for the first time"); if (!evaluator.simplified) { addRow("Idle Timeout:", idleSpinner, "Number of frames without movement before a bot is killed (0 is disabled)"); addRow("IO Idle Timeout:", idleIoSpinner, "Number of frames without IO before a bot is killed (0 is disabled)"); addRow("Force Stack:", stackSpinner, "Kill a bot if the stack pointer ever goes beyond this (0 is disabled)"); addRow("Force IO:", ioCheckBox, "Kill a bot if it ever generates an invalid IO command"); } addRow("Early Reward:", temporalCheckBox, "Scale points so earlier activity is worth more"); updateSliders(); } public void updateSliders() { extraWorldSpinner.setValue(evaluator.extraWorldCount); orientationSpinner.setValue(evaluator.directionsPerSpawn); frameSpinner.setValue(evaluator.maxSimFrames); goldSpinner.setValue(evaluator.goldReward); batterySpinner.setValue(evaluator.batteryReward); exploreSpinner.setValue(evaluator.exploreReward); idleSpinner.setValue(evaluator.idleMax); idleIoSpinner.setValue(evaluator.idleIoMax); rammingSpinner.setValue(evaluator.ramPenalty); stackSpinner.setValue(evaluator.forceStack); ioCheckBox.setSelected(evaluator.forceIO); temporalCheckBox.setSelected(evaluator.temporal); } public void updateEvaluator() { evaluator.extraWorldCount = getInt(extraWorldSpinner); evaluator.directionsPerSpawn = getInt(orientationSpinner); evaluator.maxSimFrames = getInt(frameSpinner); evaluator.goldReward = getInt(goldSpinner); evaluator.batteryReward = getInt(batterySpinner); evaluator.exploreReward = getInt(exploreSpinner); evaluator.idleMax = getInt(idleSpinner); evaluator.idleIoMax = getInt(idleIoSpinner); evaluator.ramPenalty = getInt(rammingSpinner); evaluator.forceStack = getInt(stackSpinner); evaluator.forceIO = ioCheckBox.isSelected(); evaluator.temporal = temporalCheckBox.isSelected(); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/compiler/VMFuncTable.java
src/asmcup/compiler/VMFuncTable.java
package asmcup.compiler; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import asmcup.vm.VMFuncs; public class VMFuncTable { private static final Map<String, Integer> funcs; private static final Map<Integer, String> reverse; static { funcs = new HashMap<>(); reverse = new HashMap<>(); for (Field field : VMFuncs.class.getDeclaredFields()) { try { bind(field); } catch (Exception e) { throw new RuntimeException("Failed to access static member via reflection"); } } } private static void bind(Field field) throws Exception { String s = field.getName(); if (!s.startsWith("F_")) { return; } int value = field.getInt(null); s = s.substring("F_".length()).toLowerCase(); bind(s, value); } private static void bind(String name, int code) { funcs.put(name, code); reverse.put(code, name); } public static int parse(String s) { return funcs.get(s.toLowerCase().trim()); } public static String unparse(int index) { return reverse.get(index); } public static boolean exists(String name) { return funcs.containsKey(name.toLowerCase().trim()); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/compiler/RobotConstsTable.java
src/asmcup/compiler/RobotConstsTable.java
package asmcup.compiler; import java.lang.reflect.Field; import java.util.*; import asmcup.runtime.Robot; public class RobotConstsTable { private static final Map<String, Integer> consts; static { consts = new HashMap<>(); for (Field field : Robot.class.getDeclaredFields()) { if (isConst(field.getName())) { try { add(field); } catch (Exception e) { throw new RuntimeException("Failed to access static member via reflection"); } } } } private static boolean isConst(String name) { return name.startsWith("IO_") || name.startsWith("SENSOR_"); } private static void add(Field field) throws Exception { consts.put(field.getName(), field.getInt(null)); } public static boolean contains(String s) { return consts.containsKey(s); } public static int get(String s) { return consts.get(s); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/compiler/Compiler.java
src/asmcup/compiler/Compiler.java
package asmcup.compiler; import java.util.*; import asmcup.vm.VMConsts; public class Compiler implements VMConsts { protected ArrayList<Statement> statements; protected HashMap<String, Integer> labels; protected byte[] ram; protected int pc; protected int bytesUsed = 0; protected int currentLine = 0; protected void init() { ram = new byte[256]; labels = new HashMap<>(); statements = new ArrayList<>(); pc = 0; bytesUsed = 0; } protected void write8(int value) { ram[pc] = (byte)(value & 0xFF); pc = (pc + 1) & 0xFF; ++bytesUsed; } protected void writeOp(int op, int data) { if ((op >> 2) != 0) { throw new IllegalArgumentException("Opcode is greater than 2-bits"); } if ((data >> 6) != 0) { throw new IllegalArgumentException("Opcode data is greater than 6-bits"); } write8(op | (data << 2)); } protected void write16(int value) { write8(value & 0xFF); write8(value >> 8); } protected void write32(int value) { write16(value & 0xFFFF); write16(value >> 16); } protected void writeFloat(float value) { write32(Float.floatToRawIntBits(value)); } public byte[] compile(String[] lines) { init(); try { for (String line : lines) { currentLine++; parseLine(line); } } catch (IllegalArgumentException e) { rethrowWithLine(e, currentLine); } pc = 0; for (Statement statement : statements) { pc += statement.measure(); } pc = 0; for (Statement statement : statements) { statement.compile(); } labels.clear(); statements.clear(); labels = null; statements = null; pc = 0; byte[] compiled = ram; ram = null; return compiled; } public byte[] compile(String source) { return compile(source.split("\n")); } protected void parseLine(String line) { line = line.trim(); if (line.isEmpty()) { return; } line = parseComments(line); line = parseLabels(line); if (line.isEmpty()) { return; } String[] parts = line.split("\\s+", 2); if (parts.length <= 0) { return; } String cmd = parts[0].toLowerCase().trim(); String[] args = parseArgs(parts.length > 1 ? parts[1] : ""); parseStatement(cmd, args); } protected void parseStatement(String cmd, String[] args) { switch (cmd) { case "db": case "db8": db(args); break; case "dbf": dbf(args); break; case "push8": push8(args); break; case "push8r": push8r(args); break; case "pop8": pop8(args); break; case "pop8r": pop8r(args); break; case "pushf": pushf(args); break; case "popf": popf(args); break; case "jne": case "jnz": jnz(args); break; case "jnzr": case "jner": jnzr(args); break; case "jmp": jmp(args); break; default: func(cmd, args); break; } } final static byte[] NO_DATA = {}; protected void func(String cmd, String[] args) { if (!VMFuncTable.exists(cmd)) { throw new IllegalArgumentException("Unknown function " + cmd); } if (args.length > 0) { throw new IllegalArgumentException("Too many arguments (0 expected)"); } immediate(OP_FUNC, VMFuncTable.parse(cmd), NO_DATA); } protected void db(String[] args) { statements.add(new Statement(currentLine) { public int measureImpl() { return args.length; } public void compileImpl() { for (String s : args) { write8(parseLiteralByte(s)); } } }); } protected void dbf(String[] args) { statements.add(new Statement(currentLine) { public int measureImpl() { return args.length * 4; } public void compileImpl() { for (String s : args) { writeFloat(parseLiteralFloat(s)); } } }); } protected void push8(String[] args) { String s = expectOne(args); if (isLiteral(s)) { pushLiteral8(s); } else if (s.startsWith("&")) { s = s.substring(1); if (!isSymbol(s)) { throw new IllegalArgumentException("Invalid label: " + s); } reference(OP_PUSH, MAGIC_PUSH_BYTE_IMMEDIATE, s); } else { reference(OP_PUSH, MAGIC_PUSH_BYTE_MEMORY, s); } } protected void pushLiteral8(String s) { switch (parseLiteralByte(s)) { case 0: immediate(OP_FUNC, F_C_0, NO_DATA); break; case 1: immediate(OP_FUNC, F_C_1, NO_DATA); break; case 2: immediate(OP_FUNC, F_C_2, NO_DATA); break; case 3: immediate(OP_FUNC, F_C_3, NO_DATA); break; case 4: immediate(OP_FUNC, F_C_4, NO_DATA); break; case 255: immediate(OP_FUNC, F_C_255, NO_DATA); break; default: immediate(OP_PUSH, MAGIC_PUSH_BYTE_IMMEDIATE, s); break; } } protected void push8r(String[] args) { relative(OP_PUSH, args); } protected void pop8(String[] args) { String s = expectOne(args); if (isIndirect(s)) { s = s.substring(1, s.length() - 1); reference(OP_POP, MAGIC_POP_BYTE_INDIRECT, s); } else { reference(OP_POP, MAGIC_POP_BYTE, s); } } protected void pop8r(String[] args) { relative(OP_POP, args); } protected void pushf(String[] args) { String s = expectOne(args); if (isLiteral(s)) { pushLiteralFloat(s); } else { pushMemoryFloat(s); } } protected void pushMemoryFloat(String args) { reference(OP_PUSH, MAGIC_PUSH_FLOAT_MEMORY, args); } protected void pushLiteralFloat(String s) { float f = parseLiteralFloat(s); if (f == -1.0f) { immediate(OP_FUNC, F_C_M1F, NO_DATA); } else if (f == 0.0f) { immediate(OP_FUNC, F_C_0F, NO_DATA); } else if (f == 1.0f) { immediate(OP_FUNC, F_C_1F, NO_DATA); } else if (f == 2.0f) { immediate(OP_FUNC, F_C_2F, NO_DATA); } else if (f == 3.0f) { immediate(OP_FUNC, F_C_3F, NO_DATA); } else if (Float.isInfinite(f) && f > 0) { immediate(OP_FUNC, F_C_INF, NO_DATA); } else { immediateFloat(OP_PUSH, MAGIC_PUSH_FLOAT_IMMEDIATE, s); } } protected void popf(String[] args) { String s = expectOne(args); if (isIndirect(s)) { s = s.substring(1, s.length() - 1); reference(OP_POP, MAGIC_POP_FLOAT_INDIRECT, s); } else { reference(OP_POP, MAGIC_POP_FLOAT, s); } } protected void jnz(String[] args) { String s = expectOne(args); if (isIndirect(s)) { throw new IllegalArgumentException("jnz cannot be indirect"); } else { reference(OP_BRANCH, MAGIC_BRANCH_IMMEDIATE, s); } } protected void jnzr(String[] args) { relative(OP_BRANCH, args); } protected void jmp(String[] args) { String s = expectOne(args); if (isIndirect(s)) { s = s.substring(1, s.length() - 1); reference(OP_BRANCH, MAGIC_BRANCH_INDIRECT, s); } else { reference(OP_BRANCH, MAGIC_BRANCH_ALWAYS, s); } } public static boolean isLiteral(String s) { return s.startsWith("#"); } public static boolean isSymbol(String s) { return s.matches("^[a-zA-Z_]+[a-zA-Z_0-9]*$"); } public static boolean isIndirect(String s) { return isEnclosed(s, "(", ")") || isEnclosed(s, "[", "]"); } public static boolean isEnclosed(String s, String start, String end) { if (s.startsWith(start)) { if (!s.endsWith(end)) { throw new IllegalArgumentException(String.format("Expected '%s'", end)); } return true; } return false; } public static String expectOne(String[] args) { if (args.length != 1) { throw new IllegalArgumentException("Wrong number of arguments (1 expected, " + args.length + " received)"); } return args[0]; } protected static String parseComments(String line) { int pos = line.indexOf(';'); if (pos < 0) { return line.trim(); } return line.substring(0, pos).trim(); } protected String parseLabels(String line) { int pos; while ((pos = line.indexOf(':')) >= 0) { if (pos == 0) { throw new IllegalArgumentException("Expected label name"); } String name = line.substring(0, pos).trim(); if (!isSymbol(name)) { throw new IllegalArgumentException("Invalid label name: " + name); } statements.add(new Label(name, currentLine)); line = line.substring(pos + 1).trim(); } return line.trim(); } protected static final String[] EMPTY_ARGS = {}; protected static String[] parseArgs(String arguments) { if (arguments.trim().isEmpty()) { return EMPTY_ARGS; } String[] args = arguments.split(","); for (int i=0; i < args.length; i++) { args[i] = args[i].trim(); } return args; } protected static int parseLiteralByte(String s) { if (!isLiteral(s)) { throw new IllegalArgumentException("Expected #"); } return parseByteValue(s.substring(1)); } protected static int parseByteValue(String s) { if (RobotConstsTable.contains(s)) { return RobotConstsTable.get(s) & 0xFF; } try { if (s.startsWith("$")) { return Integer.parseInt(s.substring(1), 16) & 0xFF; } return Integer.parseInt(s, 10) & 0xFF; } catch (NumberFormatException e) { // Accommodate for recent change to float literals try { Float.parseFloat(s); } catch (NumberFormatException ef) { // Ok, this simply isn't a number. throw new IllegalArgumentException(String.format("Invalid value: %s", s)); } // It's a valid float but not an int. Maybe the user meant a literal? throw new IllegalArgumentException(String.format("Invalid value: %s" + "%nNote: Float literals must begin with '#'." + " This is a recent change that might cause the problem", s)); } } protected static float parseLiteralFloat(String s) { if (!isLiteral(s)) { throw new IllegalArgumentException("Float literals must begin with '#'." + " This is a recent change that might cause the problem"); } try { return Float.parseFloat(s.substring(1)); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("Invalid float value: %s", s)); } } protected int getAddress(String s) { int addr; if (isLiteral(s)) { throw new IllegalArgumentException("Cannot address a literal"); } if (isSymbol(s)) { if (!labels.containsKey(s)) { throw new IllegalArgumentException( String.format("Cannot find label '%s'", s)); } addr = labels.get(s); } else { addr = parseByteValue(s); } return addr; } protected void reference(int op, int data, String s) { statements.add(new Statement(currentLine) { public int measureImpl() { return 2; } public void compileImpl() { int addr = getAddress(s); writeOp(op, data); write8(addr); } }); } protected void reference(int op, int data, String[] args) { reference(op, data, expectOne(args)); } protected void immediate(int op, int data, byte[] payload) { statements.add(new Statement(currentLine) { public int measureImpl() { return 1 + payload.length; } public void compileImpl() { writeOp(op, data); for (byte b : payload) { write8(b); } } }); } protected void immediate(int op, int data, String[] args) { immediate(op, data, expectOne(args)); } protected void immediate(int op, int data, String s) { byte[] payload = new byte[] { (byte)parseLiteralByte(s) }; immediate(op, data, payload); } protected void immediateFloat(int op, int data, String s) { statements.add(new Statement(currentLine) { public int measureImpl() { return 5; } public void compileImpl() { writeOp(op, data); writeFloat(parseLiteralFloat(s)); } }); } protected void relative(int op, String s) { if (isLiteral(s)) { throw new IllegalArgumentException("Cannot address a literal for relative instruction"); } statements.add(new Statement(currentLine) { public int measureImpl() { return 1; } public void compileImpl() { int addr = getAddress(s); // Allowed range: -32 to 31 int r = addr - (pc + 1); int data = (r + 32) & 0xFF; // Allowed range now: 0 to 63 if ((data >> 6) != 0 || (data == 31) || // (and not one of the magics) (data == 32) || (data == 33) || ((data == 0) && (op != OP_BRANCH))) { throw new IllegalArgumentException("Unacceptable target address distance"); } writeOp(op, data); } }); } protected void relative(int op, String[] args) { relative(op, expectOne(args)); } /** * Returns the current line number. Useful for display a compiler error * @return current line number the compiler is looking at */ public int getCurrentLine() { return currentLine; } private void rethrowWithLine(IllegalArgumentException e, int currentLine) { String messageWithLine = String.format("%s on line %d", e.getMessage(), currentLine); throw new IllegalArgumentException(messageWithLine, e); } /** * @return the number of bytes used */ public int getBytesUsed() { return bytesUsed; } protected abstract class Statement { public final int line; public Statement(int line) { this.line = line; } public int measure() { try { return measureImpl(); } catch (IllegalArgumentException e) { rethrowWithLine(e, line); return 0; } } public void compile() { try { compileImpl(); } catch (IllegalArgumentException e) { rethrowWithLine(e, line); } } protected abstract int measureImpl(); protected abstract void compileImpl(); } protected class Label extends Statement { final String name; public Label(String name, int line) { super(line); this.name = name; } public int measureImpl() { if (labels.containsKey(name)) { throw new IllegalArgumentException(String.format("Redefined label '%s'", name)); } labels.put(name, pc); return 0; } public void compileImpl() { } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/src/asmcup/compiler/Main.java
src/asmcup/compiler/Main.java
package asmcup.compiler; import java.io.*; import java.nio.file.*; import java.util.List; public class Main { public static void main(String[] args) throws IOException { if (args.length < 2) { System.err.printf("USAGE: asmcup-compile <in> <out>%n"); System.exit(1); return; } File inFile = new File(args[0]); File outFile = new File(args[1]); String[] lines = readLines(inFile.toPath()); FileOutputStream output = new FileOutputStream(outFile); Compiler compiler = new Compiler(); byte[] program = compiler.compile(lines); output.write(program); output.close(); } protected static String[] readLines(Path path) throws IOException { List<String> list = Files.readAllLines(path); return list.toArray(new String[list.size()]); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/test/asmcup/decompiler/DecompilerTest.java
test/asmcup/decompiler/DecompilerTest.java
package asmcup.decompiler; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import asmcup.compiler.Compiler; import static org.junit.Assert.*; public class DecompilerTest { private Decompiler decompiler = null; private final ByteArrayOutputStream out = new ByteArrayOutputStream(); @Before public void setUp() throws UnsupportedEncodingException { decompiler = new Decompiler(new PrintStream(out, false, "UTF-8")); } @Test public void testDump() throws UnsupportedEncodingException { decompiler.dump(0xff, "blabla"); assertEquals(String.format("Lff: blabla%n"), out.toString("UTF-8")); } @Test public void testDecompile() throws UnsupportedEncodingException { // This code is not sensible and does not produce a good or valid program byte[] ram = (new Compiler()).compile(getProgram( "start:", "push8 #0", "push8 #42", "pushf #42.0", "pushf start", "popf $fa", "pop8 $fb", "push8 $fc", "jmp start", "jnz start", "jmp ($cc)", "popf ($a)", "pop8 [$b]", "pushf $ab" )); decompiler.decompile(ram); assertEquals(getProgram( // "start:" label produces no output! "L00: c_0", "L01: push8 #$2a", "L03: pushf #4.200000000e+01", "L08: pushf $00", "L0a: popf $fa", "L0c: pop8 $fb", "L0e: push8 $fc", "L10: jmp $00", "L12: jnz $00", "L14: jmp [$cc]", "L16: popf [$0a]", "L18: pop8 [$0b]", "L1a: pushf $ab" ), out.toString("UTF-8")); } @Test public void testIdentityByteConstants() throws UnsupportedEncodingException { byte[] ram = (new Compiler()).compile(getProgram( "push8 #-1", "push8 #0", "push8 #1", "push8 #2", "push8 #3", "push8 #4", "push8 #5", "push8 #6", "push8 #255", "push8 #256", "push8 #257", "push8 #-1000", "push8 #1001" )); checkDecompileCompileIdentity(ram); } @Test public void testIdentityFloatConstants() throws UnsupportedEncodingException { byte[] ram = (new Compiler()).compile(getProgram( "pushf #1.0", "pushf #-0.0", "pushf #42", "pushf #NaN", "pushf #0.1", "pushf #7.0", "pushf #7.0e20", "pushf #13.37e-20", "pushf #Infinity", "pushf #-Infinity" )); checkDecompileCompileIdentity(ram); } @Test public void testFuzzedPattern0() throws UnsupportedEncodingException { testFuzzedWithPadding(0); } @Test public void testFuzzedPattern1() throws UnsupportedEncodingException { testFuzzedWithPadding(1); } @Test public void testFuzzedPattern4() throws UnsupportedEncodingException { testFuzzedWithPadding(4); } public void testFuzzedWithPadding(int pad) throws UnsupportedEncodingException { int step = pad + 1; byte[] ram = new byte[256]; int instruction = 0; for (int repeats = 0; repeats < step; repeats++) { for (int i = 0; i < 256; i++) { if (i % step == 0) { ram[i] = (byte)(instruction++ & 0xFF); } else { ram[i] = 0; } } checkDecompileCompileIdentity(ram); } } private void checkDecompileCompileIdentity(byte[] ram) throws UnsupportedEncodingException { Compiler compiler = new Compiler(); out.reset(); decompiler.decompile(ram); byte[] newRam = compiler.compile(out.toString("UTF-8")); for (int i = 0; i < 256; i++) { assertEquals(String.format("Memory differs at %02x", i), ram[i], newRam[i]); } } private static String getProgram(String... lines) { StringBuilder ret = new StringBuilder(); for (String line : lines) { ret.append(line); ret.append(System.lineSeparator()); } return ret.toString(); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/test/asmcup/runtime/TileTest.java
test/asmcup/runtime/TileTest.java
package asmcup.runtime; import org.junit.Test; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; public class TileTest { @Test public void testIsSolid() { Map<Integer, Boolean> map = new HashMap<Integer, Boolean>() {{ put(TILE.GROUND, false); put(TILE.HAZARD, false); put(TILE.WALL, true); put(TILE.OBSTACLE, true); put(TILE.FLOOR, false); }}; World world = new World(); for (Map.Entry<Integer, Boolean> entry : map.entrySet()) { world.setTileXY(0, 0, entry.getKey()); assertEquals("Failed key:" + entry.getKey(), entry.getValue(), world.isSolid(0, 0)); assertEquals("Failed key:" + entry.getKey(), entry.getValue(), !world.canRobotGoTo(World.TILE_HALF, World.TILE_HALF)); } } @Test public void testIsSpawnable() { Map<Integer, Boolean> map = new HashMap<Integer, Boolean>() {{ put(TILE.GROUND, true); put(TILE.HAZARD, false); put(TILE.WALL, false); put(TILE.OBSTACLE, false); put(TILE.FLOOR, true); }}; World world = new World(); for (Map.Entry<Integer, Boolean> entry : map.entrySet()) { world.setTileXY(0, 0, entry.getKey()); assertEquals("Failed entry: " + entry.getKey(), entry.getValue(), world.canSpawnRobotAt(World.TILE_HALF, World.TILE_HALF)); } } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/test/asmcup/runtime/ItemTest.java
test/asmcup/runtime/ItemTest.java
package asmcup.runtime; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ItemTest { @Test public void testWithinDistance() { Item item = new Item.Gold(42); item.position(42f, 42f); final int distance = 20; for (int i = 42 - distance; i < 42 + distance; ++i) { assertTrue("Failed: (" + i + ",42)", item.withinDistance(i, 42)); assertTrue("Failed: (42, " + i + ")", item.withinDistance(42, i)); } } @Test public void testCollectGold() { Robot robot = new Robot(42); Item.Gold gold = new Item.Gold(10); assertEquals(0, robot.getGold()); gold.collect(robot); assertEquals(10, robot.getGold()); } @Test public void testCollectBattery() { Robot robot = new Robot(42); Item.Battery battery = new Item.Battery(10); robot.battery = 0; assertEquals(0, robot.getBattery()); battery.collect(robot); assertEquals(1000, robot.getBattery()); } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/test/asmcup/runtime/RobotTest.java
test/asmcup/runtime/RobotTest.java
package asmcup.runtime; import asmcup.vm.VM; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; public class RobotTest { Robot robot = null; @Before public void setUp() { robot = new Robot(42); robot.position(42, 21); } @Test public void testAccelerometer() { World world = generateEmptyWorld((int)robot.getX(), (int)robot.getY(), 50); // Read Accelerometer VM vm = robot.getVM(); vm.push8(Robot.IO_ACCELEROMETER); vm.setIO(true); robot.handleIO(world); // We did not drive, so we should expect 0 values. float x = vm.popFloat(); float y = vm.popFloat(); assertEquals(0, x, 0.001f); assertEquals(0, y, 0.001f); assertEquals(x, y, 0.001f); // Drive a little bit robot.setMotor(1.0f); robot.setSteer(0.5f); robot.tickHardware(world); vm.push8(Robot.IO_ACCELEROMETER); vm.setIO(true); robot.handleIO(world); // We drove, so we should not expect 0 values. x = vm.popFloat(); y = vm.popFloat(); assertNotEquals(0f, x, 0.001f); assertNotEquals(0f, y, 0.001f); assertNotEquals(x, y, 0.001f); } @Test public void testSteer() { World world = new World(); float previous = robot.getFacing(); robot.tickSteer(world); assertEquals("Robot steered", previous, robot.getFacing(), 0.0001f); robot.setSteer(1.0f); robot.tickSteer(world); assertTrue("Robot did not steer.", previous < robot.getFacing()); } @Test public void testMotor() { World world = generateEmptyWorld((int)robot.getX(), (int)robot.getY(), 50); float x = robot.getX(); float y = robot.getY(); robot.setMotor(1.0f); robot.setFacing(0.5f); robot.tickMotor(world); assertNotEquals(x, robot.getX(), 0.00001f); assertNotEquals(y, robot.getY(), 0.00001f); } @Test public void testIOMotor() { World world = new World(); VM vm = robot.getVM(); vm.pushFloat(0.5f); vm.push8(Robot.IO_MOTOR); vm.setIO(true); robot.handleIO(world); assertEquals(0.5f, robot.getMotor(), 0.0001f); vm.pushFloat(1.5f); vm.push8(Robot.IO_MOTOR); vm.setIO(true); robot.handleIO(world); assertEquals(1.0f, robot.getMotor(), 0.0001f); } @Test public void testIOSteer() { World world = new World(); VM vm = robot.getVM(); vm.pushFloat(0.5f); vm.push8(Robot.IO_STEER); vm.setIO(true); robot.handleIO(world); assertEquals(0.5f, robot.getSteer(), 0.0001f); vm.pushFloat(1.5f); vm.push8(Robot.IO_STEER); vm.setIO(true); robot.handleIO(world); assertEquals(1.0f, robot.getSteer(), 0.0001f); } @Test public void testIOOverclock() { World world = new World(); VM vm = robot.getVM(); vm.push8(200); vm.push8(Robot.IO_OVERCLOCK); vm.setIO(true); robot.handleIO(world); assertEquals(100, robot.getOverclock()); vm.push8(50); vm.push8(Robot.IO_OVERCLOCK); vm.setIO(true); robot.handleIO(world); assertEquals(50, robot.getOverclock()); } @Test public void testIOBattery() { World world = new World(); VM vm = robot.getVM(); robot.battery = Robot.BATTERY_MAX; vm.push8(Robot.IO_BATTERY); vm.setIO(true); robot.handleIO(world); assertEquals(1.0f, vm.popFloat(), 0.0001f); } @Test public void testIOLazer() { World world = new World(); VM vm = robot.getVM(); vm.pushFloat(1.0f); vm.push8(Robot.IO_LASER); vm.setIO(true); robot.handleIO(world); assertEquals(1.0f, robot.getLazer(), 0.0001f); } @Test public void testIOCompass() { World world = new World(); VM vm = robot.getVM(); robot.setFacing(0.0f); vm.push8(Robot.IO_COMPASS); vm.setIO(true); robot.handleIO(world); assertEquals(0.0f, vm.popFloat(), 0.0001f); robot.setFacing((float) Math.PI * 2); vm.push8(Robot.IO_COMPASS); vm.setIO(true); robot.handleIO(world); assertEquals(0.0f, vm.popFloat(), 0.0001f); } @Test public void testMark() { World world = new World(); VM vm = robot.getVM(); vm.push8(0); vm.push8(42); vm.push8(Robot.IO_MARK); vm.setIO(true); robot.handleIO(world); vm.push8(0); vm.push8(Robot.IO_MARK_READ); vm.setIO(true); robot.handleIO(world); assertEquals(42, vm.pop8()); // Test reading mark, when not marked robot.position(100, 100); vm.push8(0); vm.push8(Robot.IO_MARK_READ); vm.setIO(true); robot.handleIO(world); assertEquals(0, vm.pop8()); } @Test public void testMarkOffset() { World world = new World(); VM vm = robot.getVM(); // Mark offset 0 vm.push8(0); vm.push8(42); vm.push8(Robot.IO_MARK); vm.setIO(true); robot.handleIO(world); // Mark offset 1 vm.push8(1); vm.push8(4); vm.push8(Robot.IO_MARK); vm.setIO(true); robot.handleIO(world); // Read both vm.push8(1); vm.push8(Robot.IO_MARK_READ); vm.setIO(true); robot.handleIO(world); assertEquals(4, vm.pop8()); vm.push8(0); vm.push8(Robot.IO_MARK_READ); vm.setIO(true); robot.handleIO(world); assertEquals(42, vm.pop8()); } @Test public void testSensorNothing() { World world = generateEmptyWorld((int)robot.getX(), (int)robot.getY(), Robot.RAY_RANGE + 10); world.addRobot(robot); VM vm = robot.getVM(); vm.push8(Robot.IO_SENSOR); vm.setIO(true); robot.handleIO(world); assertEquals(vm.pop8() & 0b111111, 0); assertEquals(vm.popFloat(), Robot.RAY_RANGE, 5.0f); } @Test public void testSensorWall() { testSensorHitTile(TILE.WALL, Robot.SENSOR_WALL); } @Test public void testSensorObstacle() { testSensorHitTile(TILE.OBSTACLE, Robot.SENSOR_OBSTACLE); } @Test public void testSensorHazard() { testSensorHitTile(TILE.HAZARD, Robot.SENSOR_HAZARD); } protected void testSensorHitTile(int tile, int expectedSensorValue) { World world = generateEmptyWorld((int)robot.getX(), (int)robot.getY(), 100); world.addRobot(robot); VM vm = robot.getVM(); float xOffset = 60.0f; world.setTileXY(robot.getX() + xOffset, robot.getY(), tile); vm.push8(Robot.IO_SENSOR); vm.setIO(true); robot.handleIO(world); // Saw a wall... assertEquals(vm.pop8() & 0b111111, expectedSensorValue); // ...closeby. assertEquals(vm.popFloat(), xOffset, World.TILE_SIZE); } @Test public void testSensorOtherBot() { World world = generateEmptyWorld((int)robot.getX(), (int)robot.getY(), 50); world.addRobot(robot); VM vm = robot.getVM(); float xOffset = 30.0f; Robot dummy = new Robot(13); dummy.position(robot.getX() + xOffset, robot.getY()); world.addRobot(dummy); vm.push8(Robot.IO_SENSOR); vm.setIO(true); robot.handleIO(world); // Saw a robot... assertEquals(vm.pop8() & 0b111111, Robot.SENSOR_ROBOT); // ...closeby. assertEquals(vm.popFloat(), xOffset, Robot.COLLIDE_RANGE); } @Test public void testBeamAngle() { World world = generateEmptyWorld((int)robot.getX(), (int)robot.getY(), 50); VM vm = robot.getVM(); // Face west robot.setFacing(0); // Beam south? vm.pushFloat(1.0f); vm.push8(Robot.IO_BEAM_DIRECTION); vm.setIO(true); robot.handleIO(world); assertEquals((float)Math.PI/2, robot.getBeamAngle(), 0.0001f); // Face north robot.setFacing(-(float)Math.PI/2); // Beam north-west? vm.pushFloat(-0.5f); vm.push8(Robot.IO_BEAM_DIRECTION); vm.setIO(true); robot.handleIO(world); assertEquals((float)-Math.PI * 0.75f, robot.getBeamAngle(), 0.0001f); } @Test public void testLazerDamage() { World world = generateEmptyWorld((int)robot.getX(), (int)robot.getY(), 50); Robot dummy = new Robot(13); dummy.position(robot.getX() + 30, robot.getY()); world.addRobot(robot); world.addRobot(dummy); int initialBattery = dummy.getBattery(); robot.setLazer(1.0f); robot.tick(world); assert(dummy.getBattery() < initialBattery); } private World generateEmptyWorld(int x, int y, int radius) { World world = new World(); for (int i = x - radius; i < x + radius; i += World.TILE_SIZE) { for (int j = y - radius; j < y + radius; j += World.TILE_SIZE) { world.setTileXY(i, j, TILE.GROUND); } } return world; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/test/asmcup/vm/VMTest.java
test/asmcup/vm/VMTest.java
package asmcup.vm; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.*; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.junit.Assert.assertEquals; public class VMTest { private VM vm = null; @Before public void setUp() { vm = new VM(); } @Test(expected = IllegalArgumentException.class) public void testCtorWithRamError() { new VM(new byte[255]); } @Test public void testCtorWithRam() { byte[] ram = new byte[256]; vm = new VM(ram); assert(vm.getMemory() == ram); // point to the same array } @Test public void testSave() throws IOException { byte[] ram = new byte[256]; for (int i = 0; i < ram.length; ++i) { ram[i] = (byte) i; } vm = new VM(ram); ByteArrayOutputStream baos = new ByteArrayOutputStream(260); DataOutputStream out = new DataOutputStream(baos); vm.save(out); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); VM saved = new VM(new DataInputStream(bais)); Assert.assertEquals(vm, saved); } @Test public void testWrite8() { vm.write8(0, 0xff); assertEquals((byte) 0xff, vm.getMemory()[0]); assertEquals(0x00, vm.getMemory()[1]); // We're not overflowing vm = new VM(); vm.write8(0, 0xcace); assertEquals((byte) 0xce, vm.getMemory()[0]); // we're only writing one byte assertEquals(0x00, vm.getMemory()[1]); } @Test public void testWrite16() { ByteBuffer bb = getByteBuffer(vm.getMemory()); vm.write16(0, 0xffff); assertEquals((short) 0xffff, bb.getShort(0)); assertEquals(0x00, bb.getShort(2)); // We're not overflowing vm = new VM(); bb = getByteBuffer(vm.getMemory()); vm.write16(0, 0xfaceb00c); assertEquals((short) 0xb00c, bb.getShort(0)); // we're only writing two bytes assertEquals(0x00, bb.getShort(2)); } @Test public void testWrite32() { ByteBuffer bb = getByteBuffer(vm.getMemory()); vm.write32(0, 0xffffffff); assertEquals(0xffffffff, bb.getInt(0)); assertEquals(0x00, bb.getInt(4)); // We're not overflowing } @Test public void testWriteFloat() { ByteBuffer bb = getByteBuffer(vm.getMemory()); vm.writeFloat(0, 1.23456f); assertEquals(1.23456f, bb.getFloat(0), 0.1); assertEquals(0x00, bb.getInt(4)); // We're not overflowing } @Test public void testRead8() { vm.write8(0, 0xff); vm.write8(1, 0xee); assertEquals(0xff, vm.read8()); assertEquals(0xff, vm.read8(0)); assertEquals(0xee, vm.read8()); // increasing pc assertEquals(0xff, vm.read8(0)); } @Test public void testRead8Indirect() { vm.write8(0, 42); vm.write8(42, 0xff); assertEquals(0xff, vm.read8indirect()); } @Test public void testRead16() { vm.write16(0, 0xffff); assertEquals(0xffff, vm.read16()); } @Test public void testRead32() { vm.write32(0, 0xffffffff); assertEquals(0xffffffff, vm.read32()); } @Test public void testReadFloat() { vm.writeFloat(0, 1.23456f); assertEquals(1.23456f, vm.readFloat(), 0.00001f); } @Test public void testReadFloatIndirect() { vm.write8(0, 42); vm.writeFloat(42, 1.23456f); assertEquals(1.23456f, vm.readFloatIndirect(), 0.0001f); } @Test public void testPush8() { vm.push8(0xff); vm.push8(0xee); assertEquals(0xee, vm.pop8()); assertEquals(0xff, vm.pop8()); } @Test public void testPush16() { vm.push16(0xffff); vm.push16(0xeeee); assertEquals(0xeeee, vm.pop16()); assertEquals(0xffff, vm.pop16()); } @Test public void testPush32() { vm.push32(0xffffffff); vm.push32(0xeeeeeeee); assertEquals(0xeeeeeeee, vm.pop32()); assertEquals(0xffffffff, vm.pop32()); } @Test public void testPushFloat() { vm.pushFloat(1.23456f); vm.pushFloat(2.7182f); assertEquals(2.7182f, vm.popFloat(), 0.0001f); assertEquals(1.23456f, vm.popFloat(), 0.0001f); } @Test public void testStackPointer() { assertEquals(0xff, vm.getStackPointer()); vm.push8(0xff); assertEquals(0xfe, vm.getStackPointer()); vm.push8(0xff); vm.pop8(); assertEquals(0xfe, vm.getStackPointer()); vm.pop8(); assertEquals(0xff, vm.getStackPointer()); } @Test public void testStackOpsAdd() { vm.push8(13); vm.push8(37); vm.op_func(VMFuncs.F_ADD8); Assert.assertEquals(vm.pop8(), 50); } @Test public void testStackOpsXor() { vm.push8(0b001101); vm.push8(0b010111); vm.op_func(VMFuncs.F_XOR); Assert.assertEquals(vm.pop8(), 0b011010); } @Test public void testStackOpsDup8() { vm.push8(0x2A); vm.op_func(VMFuncs.F_DUP8); Assert.assertEquals(vm.pop8(), 0x2A); Assert.assertEquals(vm.pop8(), 0x2A); } @Test public void testStackOpsDupf() { vm.pushFloat(0.1f); vm.op_func(VMFuncs.F_DUPF); // Yes, binary equivalence should remain. Assert.assertTrue(vm.popFloat() == 0.1f); Assert.assertTrue(vm.popFloat() == 0.1f); } @Test public void testStackOpsSubroutine() { int startPC = vm.getProgramCounter(); vm.push8(0xab); vm.op_func(VMFuncs.F_JSR); Assert.assertEquals(vm.getProgramCounter(), 0xab); vm.op_func(VMFuncs.F_RET); Assert.assertEquals(vm.getProgramCounter(), startPC); } @Test public void testFetch8() { vm.push8(13); vm.push8(37); vm.push8(1); vm.op_func(VMFuncs.F_FT8); Assert.assertTrue(vm.pop8() == 13); } @Test public void testFetchFloat() { vm.pushFloat(1.3f); vm.pushFloat(3.7f); vm.push8(4); vm.op_func(VMFuncs.F_FTF); Assert.assertTrue(vm.popFloat() == 1.3f); } /** * Returns a little endian byte buffer for given ram * @param ram ram to wrap byte buffer around * @return little endian byte buffer */ private ByteBuffer getByteBuffer(byte[] ram) { ByteBuffer bb = ByteBuffer.wrap(ram); bb.order(ByteOrder.LITTLE_ENDIAN); return bb; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
asmcup/runtime
https://github.com/asmcup/runtime/blob/5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12/test/asmcup/compiler/CompilerTest.java
test/asmcup/compiler/CompilerTest.java
package asmcup.compiler; import org.junit.Before; import org.junit.Test; import java.nio.ByteBuffer; import java.nio.ByteOrder; import static org.junit.Assert.*; public class CompilerTest { private Compiler compiler = null; @Before public void setUp() { compiler = new Compiler(); compiler.init(); } @Test public void testUndefinedLabel() { try { compiler.compile("push8 notfoundlabel"); fail("Compiler did not fail on undefined label."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Cannot find label 'notfoundlabel'")); } } @Test public void testUndefinedFunction() { try { compiler.compile("undefinedfunction #0"); fail("Compiler did not fail on undefined function."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Unknown function undefinedfunction")); } } @Test public void testRedefinedLabel() { try { compiler.compile("label:\nlabel:"); fail("Compiler did not fail on redefined label."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Redefined label 'label'")); } } @Test public void testCurrentLine() { try { compiler.compile("valid:\n\nundefinedfunction #0"); fail("Compiler did not fail on undefined function."); } catch (IllegalArgumentException e) { assertEquals(3, compiler.getCurrentLine()); } } @Test public void testBytesUsed() { compiler.compile("push8 #1"); assertEquals(1, compiler.getBytesUsed()); // turned into c_1 compiler.init(); compiler.compile("push8 #42"); assertEquals(2, compiler.getBytesUsed()); // one byte opcode, one byte literal 42 compiler.init(); compiler.compile("push8 #1\npush8 #0"); assertEquals(2, compiler.getBytesUsed()); // 1 byte c_1, 1 byte c_0 compiler.init(); compiler.compile("start:end:"); assertEquals(0, compiler.getBytesUsed()); compiler.init(); compiler.compile("start: \n jmp start"); assertEquals(2, compiler.getBytesUsed()); // 1 byte opcode, 1 byte label addr } @Test public void testOutputSize() { assertEquals(256, compiler.compile("").length); assertEquals(256, compiler.compile(stringRepeat("push8 #0\n", 10)).length); // No error when overflowing? assertEquals(256, compiler.compile(stringRepeat("push8 #0\n", 290)).length); } @Test public void testTooFewArguments() { try { compiler.compile("push8"); fail("Compiler did not fail on missing argument."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Wrong number of arguments")); } } @Test public void testTooManyArguments() { try { compiler.compile("push8 #12, #13"); fail("Compiler did not fail on too many arguments."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Wrong number of arguments")); } } @Test public void testUnexpectedArgument() { try { compiler.compile("ret #12"); fail("Compiler did not fail on unexpected argument."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Too many arguments")); } } @Test public void testAcceptWhitespace() { byte[] ram1 = compiler.compile("\t push8 \t #0 \t"); byte[] ram2 = compiler.compile("push8 #0"); assert(ramEquals(ram1, ram2)); } @Test public void testWrite8() { compiler.write8(0xff); assertEquals((byte) 0xff, compiler.ram[0]); assertEquals(0x00, compiler.ram[1]); // We're not overflowing compiler.init(); compiler.write8(0xcace); assertEquals((byte) 0xce, compiler.ram[0]); // we're only writing one byte assertEquals(0x00, compiler.ram[1]); // check pc compiler.write8(0xb00c); assertEquals(0x0c, compiler.ram[1]); } @Test public void testWrite16() { ByteBuffer bb = getByteBuffer(compiler.ram); compiler.write16(0xffff); assertEquals((short) 0xffff, bb.getShort(0)); assertEquals(0x00, bb.getShort(2)); // We're not overflowing compiler.init(); bb = getByteBuffer(compiler.ram); compiler.write16(0xfaceb00c); assertEquals((short) 0xb00c, bb.getShort(0)); // we're only writing two bytes assertEquals(0x00, bb.getShort(2)); // check pc compiler.write16(0xb00c); assertEquals((short) 0xb00c, bb.getShort(2)); } @Test public void testWrite32() { ByteBuffer bb = getByteBuffer(compiler.ram); compiler.write32(0xffffffff); assertEquals(0xffffffff, bb.getInt(0)); assertEquals(0x00, bb.getInt(4)); // We're not overflowing // check pc compiler.write32(0xfaceb00c); assertEquals(0xfaceb00c, bb.getInt(4)); } @Test public void testWriteFloat() { ByteBuffer bb = getByteBuffer(compiler.ram); compiler.writeFloat(1.23456f); assertEquals(1.23456f, bb.getFloat(0), 0.1); assertEquals(0x00, bb.getInt(4)); // We're not overflowing // check pc compiler.writeFloat(2.7182f); assertEquals(2.7182f, bb.getFloat(4), 0.1); } @Test(expected = IllegalArgumentException.class) public void testWriteOpcodeTooLarge() { compiler.writeOp(0b100, 0); } @Test(expected = IllegalArgumentException.class) public void testWriteOpcodeDataTooLarge() { compiler.writeOp(0, 0b1000000); } @Test public void testWriteOpcode() { compiler.writeOp(0b11, 0b111111); assertEquals((byte) 0xff, compiler.ram[0]); compiler.writeOp(0, 0); assertEquals((byte) 0, compiler.ram[1]); compiler.writeOp(0b11, 0b000000); assertEquals((byte) 0b00000011, compiler.ram[2]); compiler.writeOp(0b00, 0b111111); assertEquals((byte) 0b11111100, compiler.ram[3]); } @Test(expected = IllegalArgumentException.class) public void testParseLiteralError() { Compiler.parseLiteralByte("notaliteral"); } @Test(expected = IllegalArgumentException.class) public void testParseLiteralNAN() { Compiler.parseLiteralByte("#nan"); } @Test public void testParseLiteral() { assertEquals(42, Compiler.parseLiteralByte("#42")); } @Test public void testParseLiteralHex() { assertEquals(0xff, Compiler.parseLiteralByte("#$ff")); } @Test public void testParseLiteralNegative() { assertEquals(0xff, Compiler.parseLiteralByte("#-1")); } @Test public void testParseLiteralFloats() { assertEquals(1.23456f, Compiler.parseLiteralFloat("#1.23456"), 0.0001); assertEquals(12000f, Compiler.parseLiteralFloat("#12e3"), 0.1); } @Test public void testParseIndirection() { assertTrue(Compiler.isIndirect("[anything]")); assertTrue(Compiler.isIndirect("(anything)")); } @Test public void testPushes() { compiler.compile("push8 #13 \n push8 37 \n push8 #$ab \n push8 $cd \n" + "pushf #1.2 \n pushf 12 \n pushf $34"); } public void testPushesRelative() { compiler.compile("label: dbf #0.0 \n push8r label"); compiler.compile("push8r 5 \n push8r $fa"); } @Test public void testPops() { compiler.compile("pop8 37 \n pop8 $ab \n popf 13 \n popf $3d"); } @Test public void testPopsRelative() { compiler.compile("label: dbf #0.0 \n pop8r label"); compiler.compile("pop8r 7 \n pop8r $fa"); } @Test public void testPopsIndirect() { compiler.compile("pop8 [13] \n pop8 [$cd] \n popf [13] \n popf [$cd]"); } @Test public void testJumps() { compiler.compile("jmp 37 \n jnz 13 \n jmp [11]"); compiler.compile("jmp $37 \n jnz $13 \n jmp [$11]"); } @Test public void testJumpsRelative() { compiler.compile("label: dbf #0.0 \n jnzr label"); compiler.compile("jnzr 07 \n jnzr $fa"); } @Test public void testPushrLiteralFail() { try { compiler.compile("push8r #1"); fail("Compiler did not fail on referencing a literal."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Cannot address a literal")); } } @Test public void testPopLiteralFail() { try { compiler.compile("pop8 #1"); fail("Compiler did not fail on referencing a literal."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Cannot address a literal")); } } @Test public void testNonLiteralFloatDbf() { try { compiler.compile("dbf 13.1"); fail("Compiler did not fail on non-literal float."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Float literals must")); } } @Test public void testNonLiteralFloatPushf() { try { compiler.compile("pushf 13.1"); fail("Compiler did not fail on non-literal float."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Invalid value")); } } @Test public void testIllegalFloatPush8() { try { compiler.compile("push8 #13.1"); fail("Compiler did not fail on push8 with a float."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Invalid value")); } } @Test public void testIllegalIndirect() { try { compiler.compile("push8 [0]"); fail("Compiler did not fail on indirect push."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Invalid value")); } } @Test public void testPush8LabelAddress() { byte[] ram = compiler.compile("db8 #0 \n labelAt1: db8 #0 \n push8 &labelAt1"); // Note: If the compiler ever figures out that this can be collapsed to // one of the constant functions, this test will fail. assertEquals(1, ram[3]); } @Test public void testPush8NonlabelAddress() { try { compiler.compile("push8 &2"); fail("Compiler did not fail on invalid label referencing."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Invalid label")); } } @Test public void testParseComments() { assertEquals("not a comment", Compiler.parseComments(" not a comment")); assertEquals("text before", Compiler.parseComments("text before ; this comment")); assertEquals("multiple", Compiler.parseComments("multiple ; comment ; another")); } @Test public void testParseLabels() { assertEquals("", compiler.parseLabels("start:")); assertEquals(1, compiler.statements.size()); assertEquals("", compiler.parseLabels(" two:more:")); assertEquals(3, compiler.statements.size()); assertEquals("", compiler.parseLabels(" with : spaces\t: ")); assertEquals(5, compiler.statements.size()); assertEquals("kein label", compiler.parseLabels("kein label")); } @Test public void testInvalidLabelSpaces() { try { compiler.parseLabels("label with spaces:"); fail("Compiler did not fail on invalid label name."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Invalid label name")); } } @Test public void testInvalidLabelNumbers() { try { compiler.parseLabels("123labelsMustntStartWithNumbers:"); fail("Compiler did not fail on invalid label name."); } catch (IllegalArgumentException e) { assert(e.getMessage().startsWith("Invalid label name")); } } @Test public void testParseArgs() { // Parse args assumes that parseLabels and parseComments already ran. assertArrayEquals(new String[]{}, Compiler.parseArgs("")); assertArrayEquals(new String[]{"argument1"}, Compiler.parseArgs("argument1")); assertArrayEquals(new String[]{"one argument"}, Compiler.parseArgs("one argument")); assertArrayEquals(new String[]{"two", "arguments"}, Compiler.parseArgs("two, arguments")); } @Test public void testOverflowCode() { for (int i = 0; i < 256; ++i) { compiler.write8(0xff); // Fill ram to 100% } compiler.write8(42); // should overflow to addr 0 assertEquals(42, compiler.ram[0]); } /** * Returns a little endian byte buffer for given ram * @param ram ram to wrap byte buffer around * @return little endian byte buffer */ private ByteBuffer getByteBuffer(byte[] ram) { ByteBuffer bb = ByteBuffer.wrap(ram); bb.order(ByteOrder.LITTLE_ENDIAN); return bb; } /** * Repeats str * * @param str string to repeat * @param times number of times * @return repeated string */ private static String stringRepeat(String str, int times) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < times; ++i) { builder.append(str); } return builder.toString(); } private static boolean ramEquals(byte[] a, byte[] b) { if (a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } }
java
MIT
5e1f5eb8c2c2598cd52e211b77f65ad0d198fe12
2026-01-05T02:41:15.014063Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/model/TestFileInfo.java
smart-common/src/test/java/org/smartdata/model/TestFileInfo.java
/** * 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.smartdata.model; import org.junit.Assert; import org.junit.Test; public class TestFileInfo { private class ChildFileInfo extends FileInfo { public ChildFileInfo( String path, long fileId, long length, boolean isdir, short blockReplication, long blocksize, long modificationTime, long accessTime, short permission, String owner, String group, byte storagePolicy, byte erasureCodingPolicy) { super( path, fileId, length, isdir, blockReplication, blocksize, modificationTime, accessTime, permission, owner, group, storagePolicy, erasureCodingPolicy); } } @Test public void testEquals() throws Exception { //Case 1: FileInfo fileInfo = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", " ", (byte) 1, (byte) 0); Assert.assertEquals(true, fileInfo.equals(fileInfo)); //Case 2: FileInfo fileInfo1 = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", " ", (byte) 1, (byte) 0); Assert.assertEquals(true, fileInfo.equals(fileInfo1)); //Case 3: FileInfo fileInfo2 = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 1, null, " ", (byte) 1, (byte) 0); Assert.assertEquals(false, fileInfo.equals(fileInfo2)); Assert.assertEquals(false, fileInfo2.equals(fileInfo)); //Case 4: FileInfo fileInfo3 = new FileInfo(null, 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", " ", (byte) 1, (byte) 0); Assert.assertEquals(false, fileInfo.equals(fileInfo3)); Assert.assertEquals(false, fileInfo3.equals(fileInfo)); //Case 5: FileInfo fileInfo4 = new FileInfo(null, 1, 1, true, (short) 1, 1, 1, 1, (short) 1, " ", null, (byte) 1, (byte) 0); Assert.assertEquals(false, fileInfo.equals(fileInfo4)); Assert.assertEquals(false, fileInfo4.equals(fileInfo)); //Case 6: FileInfo fileInfo5 = new FileInfo(" ", 1, 1, true, (short) 1, 1, 1, 1, (short) 2, " ", " ", (byte) 1, (byte) 0); Assert.assertEquals(false, fileInfo.equals(fileInfo5)); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/model/TestCompressionFileState.java
smart-common/src/test/java/org/smartdata/model/TestCompressionFileState.java
/** * 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.smartdata.model; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.IOException; public class TestCompressionFileState { private CompressionFileState compressionFileState; private final String fileName = "/testFile"; private final int bufferSize = 10; private final String compressionImpl = "snappy"; private final long originalLength = 86; private final long compressedLength = 34; private final Long[] originalPos = {0L, 10L, 20L, 30L, 40L, 50L, 60L, 70L, 80L}; private final Long[] compressedPos = {0L, 4L, 10L, 13L, 19L, 22L, 25L, 28L, 32L}; @Before public void init() { CompressionFileState.Builder builder = CompressionFileState.newBuilder(); compressionFileState = builder .setFileStage(FileState.FileStage.DONE) .setFileName(fileName) .setBufferSize(bufferSize) .setCompressImpl(compressionImpl) .setOriginalLength(originalLength) .setCompressedLength(compressedLength) .setOriginalPos(originalPos) .setCompressedPos(compressedPos) .build(); } @Test public void testBasicVariables() { Assert.assertEquals(FileState.FileStage.DONE, compressionFileState.getFileStage()); Assert.assertEquals(fileName, compressionFileState.getPath()); Assert.assertEquals(bufferSize, compressionFileState.getBufferSize()); Assert.assertEquals(compressionImpl, compressionFileState.getCompressionImpl()); Assert.assertEquals(originalLength, compressionFileState.getOriginalLength()); Assert.assertEquals(compressedLength, compressionFileState.getCompressedLength()); Assert.assertArrayEquals(originalPos, compressionFileState.getOriginalPos()); Assert.assertArrayEquals(compressedPos, compressionFileState.getCompressedPos()); } @Test public void testGetPosIndex() { int index; // Original offset index = compressionFileState.getPosIndexByOriginalOffset(-1); Assert.assertEquals(0, index); index = compressionFileState.getPosIndexByOriginalOffset(0); Assert.assertEquals(0, index); index = compressionFileState.getPosIndexByOriginalOffset(3); Assert.assertEquals(0, index); index = compressionFileState.getPosIndexByOriginalOffset(39); Assert.assertEquals(3, index); index = compressionFileState.getPosIndexByOriginalOffset(50); Assert.assertEquals(5, index); index = compressionFileState.getPosIndexByOriginalOffset(85); Assert.assertEquals(8, index); index = compressionFileState.getPosIndexByOriginalOffset(90); Assert.assertEquals(8, index); // Compressed offset index = compressionFileState.getPosIndexByCompressedOffset(-1); Assert.assertEquals(0, index); index = compressionFileState.getPosIndexByCompressedOffset(0); Assert.assertEquals(0, index); index = compressionFileState.getPosIndexByCompressedOffset(3); Assert.assertEquals(0, index); index = compressionFileState.getPosIndexByCompressedOffset(18); Assert.assertEquals(3, index); index = compressionFileState.getPosIndexByCompressedOffset(22); Assert.assertEquals(5, index); index = compressionFileState.getPosIndexByCompressedOffset(33); Assert.assertEquals(8, index); index = compressionFileState.getPosIndexByCompressedOffset(90); Assert.assertEquals(8, index); } @Test public void testGetTrunkSize() { long trunkSize; try { // Original trunk size trunkSize = compressionFileState.getOriginTrunkSize(1); Assert.assertEquals(10, trunkSize); trunkSize = compressionFileState.getOriginTrunkSize(8); Assert.assertEquals(6, trunkSize); // Compressed trunk size trunkSize = compressionFileState.getCompressedTrunkSize(1); Assert.assertEquals(6, trunkSize); trunkSize = compressionFileState.getCompressedTrunkSize(8); Assert.assertEquals(2, trunkSize); } catch (IOException e) { throw new RuntimeException(e); } // Wrong index try { trunkSize = compressionFileState.getOriginTrunkSize(-1); } catch (IOException e) { e.printStackTrace(); } } @Test public void testLocateCompressionTrunk() throws IOException { CompressionTrunk compressionTrunk; // Original offset compressionTrunk = compressionFileState.locateCompressionTrunk(false, 12); Assert.assertEquals(1, compressionTrunk.getIndex()); Assert.assertEquals(10L, compressionTrunk.getOriginOffset()); Assert.assertEquals(10L, compressionTrunk.getOriginLength()); Assert.assertEquals(4L, compressionTrunk.getCompressedOffset()); Assert.assertEquals(6L, compressionTrunk.getCompressedLength()); compressionTrunk = compressionFileState.locateCompressionTrunk(false, 40); Assert.assertEquals(4, compressionTrunk.getIndex()); Assert.assertEquals(40L, compressionTrunk.getOriginOffset()); Assert.assertEquals(10L, compressionTrunk.getOriginLength()); Assert.assertEquals(19L, compressionTrunk.getCompressedOffset()); Assert.assertEquals(3L, compressionTrunk.getCompressedLength()); compressionTrunk = compressionFileState.locateCompressionTrunk(false, 85); Assert.assertEquals(8, compressionTrunk.getIndex()); Assert.assertEquals(80L, compressionTrunk.getOriginOffset()); Assert.assertEquals(6L, compressionTrunk.getOriginLength()); Assert.assertEquals(32L, compressionTrunk.getCompressedOffset()); Assert.assertEquals(2L, compressionTrunk.getCompressedLength()); // Compressed offset compressionTrunk = compressionFileState.locateCompressionTrunk(true, 6); Assert.assertEquals(1, compressionTrunk.getIndex()); Assert.assertEquals(10L, compressionTrunk.getOriginOffset()); Assert.assertEquals(10L, compressionTrunk.getOriginLength()); Assert.assertEquals(4L, compressionTrunk.getCompressedOffset()); Assert.assertEquals(6L, compressionTrunk.getCompressedLength()); compressionTrunk = compressionFileState.locateCompressionTrunk(true, 19); Assert.assertEquals(4, compressionTrunk.getIndex()); Assert.assertEquals(40L, compressionTrunk.getOriginOffset()); Assert.assertEquals(10L, compressionTrunk.getOriginLength()); Assert.assertEquals(19L, compressionTrunk.getCompressedOffset()); Assert.assertEquals(3L, compressionTrunk.getCompressedLength()); compressionTrunk = compressionFileState.locateCompressionTrunk(true, 33); Assert.assertEquals(8, compressionTrunk.getIndex()); Assert.assertEquals(80L, compressionTrunk.getOriginOffset()); Assert.assertEquals(6L, compressionTrunk.getOriginLength()); Assert.assertEquals(32L, compressionTrunk.getCompressedOffset()); Assert.assertEquals(2L, compressionTrunk.getCompressedLength()); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/model/TestActionInfo.java
smart-common/src/test/java/org/smartdata/model/TestActionInfo.java
/** * 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.smartdata.model; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.Random; public class TestActionInfo { @Test public void testEquals() throws Exception { //Case 1 Assert.assertEquals(true, new ActionInfo().equals(new ActionInfo())); //Case 2 Random random = new Random(); ActionInfo actionInfo = new ActionInfo(random.nextLong(), random.nextLong(), " ", new HashMap<String, String>(), " ", " ", random.nextBoolean(), random.nextLong(), random.nextBoolean(), random.nextLong(), random.nextFloat()); Assert.assertEquals(true, actionInfo.equals(actionInfo)); //Case 3 Assert.assertEquals(false, actionInfo.equals(new Object())); Assert.assertEquals(false, new Object().equals(actionInfo)); //Case4 Assert.assertEquals(false, actionInfo.equals(null)); //Case5 ActionInfo actionInfo1 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), "test", "test", true, 1, true, 1, 1.1f); ActionInfo actionInfo2 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), "test", "test", true, 1, true, 1, 1.1f); Assert.assertEquals(true, actionInfo1.equals(actionInfo2)); //Case6 actionInfo1 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), "test", "test", true, 1, true, 1, 1.1f); actionInfo2 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), "", "test", true, 1, true, 1, 1.1f); Assert.assertEquals(false, actionInfo1.equals(actionInfo2)); //Case7 actionInfo1 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), null, "test", true, 1, true, 1, 1.1f); actionInfo2 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), null, "test", true, 1, true, 1, 1.1f); Assert.assertEquals(true, actionInfo1.equals(actionInfo2)); //Case8 actionInfo1 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), null, "test", true, 1, true, 1, 1.1f); actionInfo2 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), " ", "test", true, 1, true, 1, 1.1f); Assert.assertEquals(false, actionInfo1.equals(actionInfo2)); //Case9 actionInfo1 = new ActionInfo(1, 1, "test", new HashMap<String, String>(), "", "test", true, 1, true, 1, 1.1f); actionInfo2 = new ActionInfo(1, 1, "test", null, " ", "test", true, 1, true, 1, 1.1f); Assert.assertEquals(false, actionInfo1.equals(actionInfo2)); Assert.assertEquals(false, actionInfo2.equals(actionInfo1)); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/model/TestCmdletInfo.java
smart-common/src/test/java/org/smartdata/model/TestCmdletInfo.java
/** * 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.smartdata.model; import org.junit.Assert; import org.junit.Test; import java.util.Random; public class TestCmdletInfo { @Test public void testEquals() throws Exception { //Case 2 Random random = new Random(); CmdletInfo cmdletInfo = new CmdletInfo( random.nextLong(), random.nextLong(), CmdletState.NOTINITED, " ", random.nextLong(), random.nextLong()); Assert.assertEquals(true, cmdletInfo.equals(cmdletInfo)); //Case 3 Assert.assertEquals(false, cmdletInfo.equals(new Object())); Assert.assertEquals(false, new Object().equals(cmdletInfo)); //Case 4 Assert.assertEquals(false, cmdletInfo.equals(null)); //Case 5 CmdletInfo cmdletInfo1 = new CmdletInfo(1, 1, CmdletState.CANCELLED, "test", 1, 1); CmdletInfo cmdletInfo2 = new CmdletInfo(1, 1, CmdletState.CANCELLED, "test", 1, 1); Assert.assertEquals(true, cmdletInfo1.equals(cmdletInfo2)); //Case 6 cmdletInfo1 = new CmdletInfo(1, 1, CmdletState.CANCELLED, null, 1, 1); cmdletInfo2 = new CmdletInfo(1, 1, CmdletState.CANCELLED, "test", 1, 1); Assert.assertEquals(false, cmdletInfo1.equals(cmdletInfo2)); Assert.assertEquals(false, cmdletInfo2.equals(cmdletInfo1)); //Case 7 cmdletInfo1 = new CmdletInfo(1, 1, CmdletState.CANCELLED, null, 1, 1); cmdletInfo2 = new CmdletInfo(1, 1, CmdletState.CANCELLED, null, 1, 1); Assert.assertEquals(true, cmdletInfo1.equals(cmdletInfo2)); //Case 8 cmdletInfo1 = new CmdletInfo(1, 1, null, "test", 1, 1); cmdletInfo2 = new CmdletInfo(1, 1, CmdletState.CANCELLED, "test", 1, 1); Assert.assertEquals(false, cmdletInfo1.equals(cmdletInfo2)); //Case 9 cmdletInfo1 = new CmdletInfo(1, 1, null, "test", 1, 1); cmdletInfo2 = new CmdletInfo(1, 1, null, "test", 1, 1); Assert.assertEquals(true, cmdletInfo1.equals(cmdletInfo2)); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/model/TestRuleInfo.java
smart-common/src/test/java/org/smartdata/model/TestRuleInfo.java
/** * 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.smartdata.model; import org.junit.Assert; import org.junit.Test; public class TestRuleInfo { @Test public void testEquals() throws Exception { //Case 1: Assert.assertEquals(true, new RuleInfo().equals(new RuleInfo())); //Case 2: RuleInfo ruleInfo = new RuleInfo(1, 1, "", RuleState.ACTIVE, 1, 1, 1); Assert.assertEquals(true, ruleInfo.equals(ruleInfo)); //Case 3: RuleInfo ruleInfo1 = new RuleInfo(1, 1, "", null, 1, 1, 1); Assert.assertEquals(false, ruleInfo.equals(ruleInfo1)); Assert.assertEquals(false, ruleInfo1.equals(ruleInfo)); //Case 4: RuleInfo ruleInfo2 = new RuleInfo(1, 1, null, RuleState.ACTIVE, 1, 1, 1); Assert.assertEquals(false, ruleInfo.equals(ruleInfo2)); Assert.assertEquals(false, ruleInfo2.equals(ruleInfo)); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/utils/TestStringUtil.java
smart-common/src/test/java/org/smartdata/utils/TestStringUtil.java
/** * 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.smartdata.utils; import org.junit.Assert; import org.junit.Test; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Tests for StringUtil. */ public class TestStringUtil { @Test public void testCmdletString() throws Exception { Map<String, Integer> strs = new HashMap<>(); strs.put("int a b -c d -e f \"gg ' kk ' ff\" \" mn \"", 9); strs.put("cat /dir/file ", 2); List<String> items; for (String str : strs.keySet()) { items = StringUtil.parseCmdletString(str); Assert.assertTrue(strs.get(str) == items.size()); System.out.println(items.size() + " -> " + str); } } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/utils/TestSecurityUtil.java
smart-common/src/test/java/org/smartdata/utils/TestSecurityUtil.java
package org.smartdata.utils; import org.apache.kerby.kerberos.kerb.server.SimpleKdcServer; import org.apache.kerby.kerberos.kerb.type.ticket.TgtTicket; import org.apache.kerby.util.NetworkUtil; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import javax.security.auth.Subject; import java.io.File; /** * Test for JaasLoginUtil. */ public class TestSecurityUtil { private SimpleKdcServer kdcServer; private String serverHost = "localhost"; private int serverPort = -1; private final String keytabFileName = "smart.keytab"; private final String principal = "ssmroot@EXAMPLE.COM"; private final String ticketCacheFileName = "smart.cc"; @Before public void setupKdcServer() throws Exception { kdcServer = new SimpleKdcServer(); kdcServer.setKdcHost(serverHost); kdcServer.setAllowUdp(false); kdcServer.setAllowTcp(true); serverPort = NetworkUtil.getServerPort(); kdcServer.setKdcTcpPort(serverPort); kdcServer.init(); kdcServer.start(); } private File generateKeytab(String keytabFileName, String principal) throws Exception { File keytabFile = new File(keytabFileName); kdcServer.createAndExportPrincipals(keytabFile, principal); return new File(keytabFileName); } @Test public void loginUsingKeytab() throws Exception { File keytabFile = generateKeytab(keytabFileName, principal); Subject subject = SecurityUtil.loginUsingKeytab(principal, keytabFile); Assert.assertEquals(principal, subject.getPrincipals().iterator().next().getName()); System.out.println("Login successful for user: " + subject.getPrincipals().iterator().next()); } @Test public void loginUsingTicket() throws Exception { File keytabFile = generateKeytab(keytabFileName, principal); TgtTicket tgtTicket = kdcServer.getKrbClient().requestTgt(principal, keytabFile); File ticketCacheFile = new File(ticketCacheFileName); kdcServer.getKrbClient().storeTicket(tgtTicket, ticketCacheFile); Subject subject = SecurityUtil.loginUsingTicketCache(principal, ticketCacheFileName); Assert.assertEquals(principal, subject.getPrincipals().iterator().next().getName()); System.out.println("Login successful for user: " + subject.getPrincipals().iterator().next()); } @After public void tearDown() throws Exception { File keytabFile = new File(keytabFileName); if (keytabFile.exists()) { keytabFile.delete(); } File ticketCacheFile = new File(ticketCacheFileName); if (ticketCacheFile.exists()) { ticketCacheFile.delete(); } if (kdcServer != null) { kdcServer.stop(); } } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/test/java/org/smartdata/conf/TestReconfigurable.java
smart-common/src/test/java/org/smartdata/conf/TestReconfigurable.java
/** * 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.smartdata.conf; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; public class TestReconfigurable { public static final String PROPERTY1 = "property1"; public static final String PROPERTY2 = "property2"; private class TestReconf extends ReconfigurableBase { private String value1 = "oldValue1"; private String value2 = "oldValue2"; @Override public void reconfigureProperty(String property, String newVal) throws ReconfigureException { if (property.equals(PROPERTY1) && !newVal.equals(this.value1)) { this.value1 = newVal; } } @Override public List<String> getReconfigurableProperties() { return Arrays.asList(PROPERTY1); } public String getValue1() { return value1; } public String getValue2() { return value2; } } @Test public void testReconf() throws Exception { Assert.assertEquals(0, ReconfigurableRegistry.getAllReconfigurableProperties().size()); TestReconf reconf = new TestReconf(); Assert.assertEquals(1, ReconfigurableRegistry.getAllReconfigurableProperties().size()); ReconfigurableRegistry.applyReconfigurablePropertyValue( PROPERTY1, "newValue1"); ReconfigurableRegistry.applyReconfigurablePropertyValue( PROPERTY2, "newValue2"); Assert.assertEquals("newValue1", reconf.getValue1()); Assert.assertEquals("oldValue2", reconf.getValue2()); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/SmartServiceState.java
smart-common/src/main/java/org/smartdata/SmartServiceState.java
/** * 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.smartdata; public enum SmartServiceState { SAFEMODE(0), ACTIVE(1), DISABLED(2); private int value; SmartServiceState(int value) { this.value = value; } public static SmartServiceState fromValue(int v) { for (SmartServiceState s : values()) { if (s.getValue() == v) { return s; } } return null; } public int getValue() { return value; } public String getName() { return toString(); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/AbstractService.java
smart-common/src/main/java/org/smartdata/AbstractService.java
/** * 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.smartdata; public abstract class AbstractService implements SmartService { private SmartContext context; public AbstractService() { this(null); } public AbstractService(SmartContext context) { this.context = context; } public SmartContext getContext() { return context; } public void setContext(SmartContext context) { this.context = context; } public boolean inSafeMode() { return false; } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/SmartService.java
smart-common/src/main/java/org/smartdata/SmartService.java
/** * 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.smartdata; import java.io.IOException; public interface SmartService { enum State { INITING, INITED, STARTING, STARTED, STOPPING, STOPPED, JOINING, JOINED } /** * Init. * @return * @throws IOException */ void init() throws IOException; /** * After start call, all services and public calls should work. * @return * @throws IOException */ void start() throws IOException; /** * After stop call, all states in database will not be changed anymore. * @throws IOException */ void stop() throws IOException; }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/SmartContext.java
smart-common/src/main/java/org/smartdata/SmartContext.java
/** * 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.smartdata; import org.smartdata.conf.SmartConf; /** * SSM context for running an action. */ public class SmartContext { private SmartConf conf; public SmartContext() { this.conf = new SmartConf(); } public SmartContext(SmartConf conf) { this.conf = conf; } public SmartConf getConf() { return conf; } public void setConf(SmartConf conf) { this.conf = conf; } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/SmartConstants.java
smart-common/src/main/java/org/smartdata/SmartConstants.java
/** * 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.smartdata; import java.util.HashMap; import java.util.Map; public class SmartConstants { public static final String SMART_HDFS_STATES_UPDATE_SERVICE_IMPL = "org.smartdata.hdfs.HdfsStatesUpdateService"; public static final String SMART_ALLUXIO_STATES_UPDATE_SERVICE_IMPL = "org.smartdata.alluxio.AlluxioStatesUpdateService"; public static final String SMART_HDFS_ACTION_SCHEDULER_SERVICE_IMPL = "org.smartdata.hdfs.scheduler.MoverScheduler, " + "org.smartdata.hdfs.scheduler.CopyScheduler, " + "org.smartdata.hdfs.scheduler.Copy2S3Scheduler," + "org.smartdata.hdfs.scheduler.SmallFileScheduler," + "org.smartdata.hdfs.scheduler.CompressionScheduler," + "org.smartdata.hdfs.scheduler.ErasureCodingScheduler," + "org.smartdata.hdfs.scheduler.CacheScheduler"; public static final String SMART_HDFS_LAST_INOTIFY_TXID = "smart_hadoop_last_inotify_txid"; public static final String SMART_ALLUXIO_LAST_ENTRY_SN = "smart_alluxio_last_entry_sn"; public static final String SMART_CLIENT_PROTOCOL_NAME = "org.smartdata.protocol.SmartClientProtocol"; public static final String SMART_ADMIN_PROTOCOL_NAME = "org.smartdata.protocol.SmartAdminProtocol"; public static final String SMART_CLIENT_DISABLED_ID_FILE = "/tmp/SMART_CLIENT_DISABLED_ID_FILE"; public static final String NUMBER_OF_SMART_AGENT = "number_of_smart_agent_in_agents_file"; public static final String SYSTEM_FOLDER = "/system/"; public static final String SMART_SERVER_ID_FILE = SYSTEM_FOLDER + "ssm.id"; public static final String MOVER_ID_PATH = SYSTEM_FOLDER + "mover.id"; public static final String SMART_FILE_STATE_XATTR_NAME = "user.ssmFileState"; public static final String AGENT_CMDLET_SERVICE_NAME = "AgentCmdletService"; public static final byte STORAGE_POLICY_UNDEF_ID = 0; public static final String STORAGE_POLICY_UNDEF_NAME = "UNDEF"; public static final byte STORAGE_POLICY_COLD_ID = 2; public static final String STORAGE_POLICY_COLD_NAME = "COLD"; public static final byte STORAGE_POLICY_WARM_ID = 5; public static final String STORAGE_POLICY_WARM_NAME = "WARM"; public static final byte STORAGE_POLICY_HOT_ID = 7; public static final String STORAGE_POLICY_HOT_NAME = "HOT"; public static final byte STORAGE_POLICY_ONE_SSD_ID = 10; public static final String STORAGE_POLICY_ONE_SSD_NAME = "ONE_SSD"; public static final byte STORAGE_POLICY_ALL_SSD_ID = 12; public static final String STORAGE_POLICY_ALL_SSD_NAME = "ALL_SSD"; public static final byte STORAGE_POLICY_LAZY_PERSIST_ID = 15; public static final String STORAGE_POLICY_LAZY_PERSIST_NAME = "LAZY_PERSIST"; public static final Map<Byte, String> STORAGE_POLICY_MAP = new HashMap<>(); static { STORAGE_POLICY_MAP.put(STORAGE_POLICY_UNDEF_ID, STORAGE_POLICY_UNDEF_NAME); STORAGE_POLICY_MAP.put(STORAGE_POLICY_COLD_ID, STORAGE_POLICY_COLD_NAME); STORAGE_POLICY_MAP.put(STORAGE_POLICY_WARM_ID, STORAGE_POLICY_WARM_NAME); STORAGE_POLICY_MAP.put(STORAGE_POLICY_HOT_ID, STORAGE_POLICY_HOT_NAME); STORAGE_POLICY_MAP.put(STORAGE_POLICY_ONE_SSD_ID, STORAGE_POLICY_ONE_SSD_NAME); STORAGE_POLICY_MAP.put(STORAGE_POLICY_ALL_SSD_ID, STORAGE_POLICY_ALL_SSD_NAME); STORAGE_POLICY_MAP.put(STORAGE_POLICY_LAZY_PERSIST_ID, STORAGE_POLICY_LAZY_PERSIST_NAME); } public static final String SMART_FILE_CHECKSUM_XATTR_NAME = "user.checksum"; public static final String FS_HDFS_IMPL = "fs.hdfs.impl"; public static final String SMART_FILE_SYSTEM = "org.smartdata.hadoop.filesystem.SmartFileSystem"; public static final String DISTRIBUTED_FILE_SYSTEM = "org.apache.hadoop.hdfs.DistributedFileSystem"; public static final String REPLICATION_CODEC_NAME = "replication"; }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/SmartFilePermission.java
smart-common/src/main/java/org/smartdata/SmartFilePermission.java
/** * 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.smartdata; import org.smartdata.model.FileInfo; /** * Handling file permission info conveniently. */ public class SmartFilePermission { private short permission; private String owner; private String group; public SmartFilePermission(FileInfo fileInfo) { this.permission = fileInfo.getPermission(); this.owner = fileInfo.getOwner(); this.group = fileInfo.getGroup(); } public String getOwner() { return owner; } public String getGroup() { return group; } public short getPermission() { return permission; } @Override public int hashCode() { return permission ^ owner.hashCode() ^ group.hashCode(); } @Override public boolean equals(Object filePermission) { if (this == filePermission) { return true; } if (filePermission instanceof SmartFilePermission) { SmartFilePermission anPermissionInfo = (SmartFilePermission) filePermission; return ((this.permission == anPermissionInfo.permission)) && this.owner.equals(anPermissionInfo.owner) && this.group.equals(anPermissionInfo.group); } return false; } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/BloomFilter.java
smart-common/src/main/java/org/smartdata/BloomFilter.java
/** * 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.smartdata; import java.util.ArrayList; import java.util.BitSet; import java.util.List; public class BloomFilter { private static final int BIT_SIZE = 1 << 28; private final int[] seeds = new int[] { 3, 5, 7, 11, 13, 31, 37, 61 }; private BitSet bitSet = new BitSet(BIT_SIZE); private BloomHash[] bloomHashes = new BloomHash[seeds.length]; private List<String> whiteList = new ArrayList<>(); public BloomFilter() { for (int i = 0; i < seeds.length; i++) { bloomHashes[i] = new BloomHash(BIT_SIZE, seeds[i]); } } /** * Add element to bloom filter. * * @param element the element */ public void addElement(String element) { if (element == null) { return; } whiteList.remove(element); // Add element to bit set for (BloomHash bloomHash : bloomHashes) { bitSet.set(bloomHash.hash(element)); } } /** * Delete element to bloom filter. * * @param element the excluded element */ public void deleteElement(String element) { whiteList.add(element); } /** * Check if bloom filter contains the value. * * @param value the value to be checked */ public boolean contains(String value) { if (value == null) { return false; } if (whiteList.contains(value)) { return false; } for (BloomHash bloomHash : bloomHashes) { if (!bitSet.get(bloomHash.hash(value))) { return false; } } return true; } private class BloomHash { private int size; private int seed; private BloomHash(int cap, int seed) { this.size = cap; this.seed = seed; } /** * Calculate the index of value in bit set through hash. */ private int hash(String value) { int result = 0; int len = value.length(); for (int i = 0; i < len; i++) { result = seed * result + value.charAt(i); } return (size - 1) & result; } } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/SmartPolicyProvider.java
smart-common/src/main/java/org/smartdata/SmartPolicyProvider.java
/** * 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.smartdata; import org.apache.hadoop.security.authorize.PolicyProvider; import org.apache.hadoop.security.authorize.Service; import org.smartdata.conf.SmartConfKeys; import org.smartdata.protocol.SmartAdminProtocol; import org.smartdata.protocol.SmartClientProtocol; /** * {@link PolicyProvider} for SSM protocols. */ public class SmartPolicyProvider extends PolicyProvider { private static final Service[] ssmServices = new Service[] { new Service(SmartConfKeys.SMART_SECURITY_CLIENT_PROTOCOL_ACL, SmartClientProtocol.class), new Service(SmartConfKeys.SMART_SECURITY_ADMIN_PROTOCOL_ACL, SmartAdminProtocol.class) }; @Override public Service[] getServices() { return ssmServices; } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/AgentService.java
smart-common/src/main/java/org/smartdata/AgentService.java
/** * 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.smartdata; import java.io.Serializable; /** * AgentService is a message-driven long running service. */ public abstract class AgentService extends AbstractService { /** * @param message should be one instance of classes declared in getAcceptableMessageTypes below * @throws Exception */ public abstract void execute(Message message) throws Exception; /** * This must be the same as that returned by {@link Message#getServiceName} below. */ public abstract String getServiceName(); public interface Message extends Serializable { String getServiceName(); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/versioninfo/VersionInfoWrite.java
smart-common/src/main/java/org/smartdata/versioninfo/VersionInfoWrite.java
/** * 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.smartdata.versioninfo; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.URL; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Properties; import java.util.TimeZone; public class VersionInfoWrite { private File directory = new File(""); private String pom = directory.getAbsolutePath() + "/smart-common/pom.xml"; public void execute() { Properties prop = new Properties(); InputStream in = null; OutputStream output = null; URL resourceUrl = this.getClass().getResource("/"); if (resourceUrl == null) { throw new RuntimeException("Cannot find resource file common-versionInfo.properties."); } String s = resourceUrl.getPath() + "common-versionInfo.properties"; try { in = new FileInputStream(s); prop.load(in); output = new FileOutputStream(s); prop.setProperty("version", getVersionInfo(pom)); prop.setProperty("revision", getCommit()); prop.setProperty("user", getUser()); prop.setProperty("date", getBuildTime()); prop.setProperty("url", getUri()); prop.setProperty("branch", getBranch()); prop.store(output, new Date().toString()); } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } } private String getBuildTime() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); return dateFormat.format(new Date()); } private String getVersionInfo(String fileName) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse(fileName); NodeList parentList = doc.getElementsByTagName("parent"); Element parent = (Element) parentList.item(0); NodeList versionList = parent.getElementsByTagName("version"); if (versionList == null) { return "Not found"; } return versionList.item(0).getFirstChild().getNodeValue(); } private String getUri() { List<String> list = execCmd("git remote -v"); String uri = "Unknown"; for (String s : list) { if (s.startsWith("origin") && s.endsWith("(fetch)")) { uri = s.substring("origin".length()); uri = uri.substring(0, uri.length() - "(fetch)".length()); break; } } return uri.trim(); } private String getCommit() { List<String> list = execCmd("git log -n 1"); String commit = "Unknown"; for (String s : list) { if (s.startsWith("commit")) { commit = s.substring("commit".length()); break; } } return commit.trim(); } private String getUser() { List<String> list = execCmd("whoami"); String user = "Unknown"; for (String s : list) { user = s.trim(); break; } return user; } private String getBranch() { List<String> list = execCmd("git branch"); String branch = "Unknown"; for (String s : list) { if (s.startsWith("*")) { branch = s.substring("*".length()).trim(); break; } } return branch; } private List<String> execCmd(String cmd) { String command = "/bin/sh -c " + cmd; List<String> list = new ArrayList<String>(); try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd, null, null); InputStream stderr = proc.getInputStream(); InputStreamReader isr = new InputStreamReader(stderr, "UTF-8"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { list.add(line); } } catch (Exception e) { e.printStackTrace(); } return list; } public static void main(String[] args) { VersionInfoWrite w = new VersionInfoWrite(); w.execute(); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/versioninfo/SsmVersionInfo.java
smart-common/src/main/java/org/smartdata/versioninfo/SsmVersionInfo.java
/** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.smartdata.versioninfo; import java.util.Properties; public class SsmVersionInfo { private static Properties prop = new VersionInfoRead("common").getProperties(); private SsmVersionInfo() { } public static String getVersion() { return prop.getProperty("version", "Unknown"); } public static String getRevision() { return prop.getProperty("revision", "Unknown"); } public static String getTime() { return prop.getProperty("date", "Unknown"); } public static String getUser() { return prop.getProperty("user", "Unknown"); } public static String getUrl() { return prop.getProperty("url", "Unknown"); } public static String getBranch() { return prop.getProperty("branch", "Unknown"); } public static String getHadoopVersion() { return prop.getProperty("hadoopVersion", "Unknown"); } public static int getHadoopVersionMajor() { String str = getHadoopVersion(); if ("Unknown".equals(str)) { return -1; } String[] vals = str.split("\\."); if (vals.length > 0) { try { return Integer.valueOf(vals[0]); } catch (Exception e) { } } return -1; } public static String infoString() { return String.format("SSM %s\n" + "Subversion %s\n" + "Last commit %s on branch %s\n" + "Compiled by %s on %s\n" + "Compiled for hadoop %s", getVersion(), getUrl(), getRevision(), getBranch(), getUser(), getTime(), getHadoopVersion()); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/versioninfo/VersionInfoRead.java
smart-common/src/main/java/org/smartdata/versioninfo/VersionInfoRead.java
/** * 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.smartdata.versioninfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class VersionInfoRead { Properties prop = new Properties(); public static final Logger LOG = LoggerFactory.getLogger(VersionInfoRead.class); public VersionInfoRead(String component) { InputStream in = null; String s = component + "-versionInfo.properties"; try { in = Thread.currentThread().getContextClassLoader().getResourceAsStream(s); prop.load(in); } catch (Exception e) { LOG.error("" + e); } finally { try { in.close(); } catch (IOException e) { LOG.error(e.getLocalizedMessage()); } } } public Properties getProperties() { return prop; } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (String p : prop.stringPropertyNames()) { sb.append(p).append("=").append(prop.getProperty(p)).append("\n"); } return sb.toString(); } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/model/CompressionFileState.java
smart-common/src/main/java/org/smartdata/model/CompressionFileState.java
/** * 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.smartdata.model; import java.io.IOException; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * A class to maintain info of compressed files. */ public class CompressionFileState extends FileState implements Serializable { private int bufferSize; private String compressionImpl; private long originalLength; private long compressedLength; private Long[] originalPos; private Long[] compressedPos; public CompressionFileState(String fileName, FileStage stage) { // default bufferSize=1024 * 1024 // snappy, Zlib this(fileName, 1024 * 1024, "snappy", 0, 0, new Long[0], new Long[0], stage); } public CompressionFileState(String fileName, int bufferSize) { this(fileName, bufferSize, "snappy", 0, 0, new Long[0], new Long[0]); } public CompressionFileState(String fileName, int bufferSize, String compressionImpl, Long[] originalPos, Long[] compressedPos) { this(fileName, bufferSize, compressionImpl, 0, 0, originalPos, compressedPos); } public CompressionFileState(String fileName, int bufferSize, String compressionImpl, long originalLength, long compressedLength) { this(fileName, bufferSize, compressionImpl, originalLength, compressedLength, new Long[0], new Long[0]); } public CompressionFileState(String fileName, int bufferSize, String compressionImpl) { this(fileName, bufferSize, compressionImpl, 0, 0, new Long[0], new Long[0]); } public CompressionFileState(String fileName, int bufferSize, long originalLength, long compressedLength, Long[] originalPos, Long[] compressedPos) { this(fileName, bufferSize, "snappy", originalLength, compressedLength, originalPos, compressedPos, FileStage.DONE); } public CompressionFileState(String fileName, int bufferSize, Long[] originalPos, Long[] compressedPos) { this(fileName, bufferSize, "snappy", 0, 0, originalPos, compressedPos); } public CompressionFileState(String fileName, int bufferSize, String compressionImpl, long originalLength, long compressedLength, Long[] originalPos, Long[] compressedPos) { this(fileName, bufferSize, compressionImpl, originalLength, compressedLength, originalPos, compressedPos, FileStage.DONE); } public CompressionFileState(String fileName, int bufferSize, String compressionImpl, long originalLength, long compressedLength, Long[] originalPos, Long[] compressedPos, FileStage stage) { super(fileName, FileType.COMPRESSION, stage); this.bufferSize = bufferSize; this.compressionImpl = compressionImpl; this.originalLength = originalLength; this.compressedLength = compressedLength; this.originalPos = originalPos; this.compressedPos = compressedPos; } public int getBufferSize() { return bufferSize; } public void setBufferSize(int bufferSize) { this.bufferSize = bufferSize; } public long getOriginalLength() { return originalLength; } public long getCompressedLength() { return compressedLength; } public void setOriginalLength(long length) { originalLength = length; } public void setCompressedLength(long length) { compressedLength = length; } public Long[] getOriginalPos() { return originalPos; } public Long[] getCompressedPos() { return compressedPos; } public String getCompressionImpl() { return compressionImpl; } public void setCompressionImpl(String compressionImpl) { this.compressionImpl = compressionImpl; } /** * Get the index of originalPos and compressedPos of the given original offset. * * @param offset the offset of original file * @return the index of the compression trunk where the offset locates */ public int getPosIndexByOriginalOffset(long offset) { int trunkIndex = Arrays.binarySearch(originalPos, offset); if (trunkIndex < -1) { trunkIndex = -trunkIndex - 2; } else if (trunkIndex == -1) { trunkIndex = 0; } return trunkIndex; } /** * Get the index of originalPos and compressedPos of the given compressed offset. * * @param offset the offset of compressed file * @return the index of the compression trunk where the offset locates */ public int getPosIndexByCompressedOffset(long offset) { int trunkIndex = Arrays.binarySearch(compressedPos, offset); if (trunkIndex < -1) { trunkIndex = -trunkIndex - 2; } else if (trunkIndex == -1) { trunkIndex = 0; } return trunkIndex; } /** * Locate the compression trunk with the given offset (either origin or compressed). * * @param compressed true for compressed offset, false for origin offset * @param offset * @return the compression trunk where the offset locates * @throws IOException */ public CompressionTrunk locateCompressionTrunk(boolean compressed, long offset) throws IOException { int index = compressed ? getPosIndexByCompressedOffset(offset) : getPosIndexByOriginalOffset(offset); CompressionTrunk compressionTrunk = new CompressionTrunk(index); compressionTrunk.setCompressionImpl(compressionImpl); compressionTrunk.setOriginOffset(originalPos[index]); compressionTrunk.setOriginLength(getOriginTrunkSize(index)); compressionTrunk.setCompressedOffset(compressedPos[index]); compressionTrunk.setCompressedLength(getCompressedTrunkSize(index)); return compressionTrunk; } /** * Get original trunk size with the given index. * * @param index * @return */ public long getOriginTrunkSize(int index) throws IOException { if (index >= originalPos.length || index < 0) { throw new IOException("Trunk index out of bound"); } long trunkSize = 0; if (index == originalPos.length - 1) { trunkSize = originalLength - originalPos[index]; } else { trunkSize = originalPos[index + 1] - originalPos[index]; } return trunkSize; } /** * Get the compressed trunk size with the given index. * * @param index * @return */ public long getCompressedTrunkSize(int index) throws IOException { if (index >= compressedPos.length || index < 0) { throw new IOException("Trunk index out of bound"); } long trunkSize = 0; if (index == compressedPos.length - 1) { trunkSize = compressedLength - compressedPos[index]; } else { trunkSize = compressedPos[index + 1] - compressedPos[index]; } return trunkSize; } public void setPositionMapping(Long[] originalPos, Long[] compressedPos) throws IOException{ if (originalPos.length != compressedPos.length) { throw new IOException("Input of position mapping is incorrect : " + "originalPos.length != compressedPos.length"); } this.originalPos = originalPos; this.compressedPos = compressedPos; } public static Builder newBuilder() { return Builder.create(); } public static class Builder { private String fileName = null; private int bufferSize = 0; private String compressImpl = "snappy"; private long originalLength; private long compressedLength; private Long[] originalPos; private Long[] compressedPos; private FileStage fileStage; public static Builder create() { return new Builder(); } public Builder setFileName(String fileName) { this.fileName = fileName; return this; } public Builder setBufferSize(int bufferSize) { this.bufferSize = bufferSize; return this; } public Builder setCompressImpl(String compressImpl) { this.compressImpl = compressImpl; return this; } public Builder setOriginalLength(long originalLength) { this.originalLength = originalLength; return this; } public Builder setCompressedLength(long compressedLength) { this.compressedLength = compressedLength; return this; } public Builder setOriginalPos(Long[] originalPos) { this.originalPos = originalPos; return this; } public Builder setOriginalPos(List<Long> originalPos) { this.originalPos = originalPos.toArray(new Long[0]); return this; } public Builder setCompressedPos(Long[] compressedPos) { this.compressedPos = compressedPos; return this; } public Builder setCompressedPos(List<Long> compressedPos) { this.compressedPos = compressedPos.toArray(new Long[0]); return this; } public Builder setFileStage(FileStage fileStage) { this.fileStage = fileStage; return this; } public CompressionFileState build() { return new CompressionFileState(fileName, bufferSize, compressImpl, originalLength, compressedLength, originalPos, compressedPos, fileStage); } } }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false
Intel-bigdata/SSM
https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-common/src/main/java/org/smartdata/model/ExecutorType.java
smart-common/src/main/java/org/smartdata/model/ExecutorType.java
/** * 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.smartdata.model; public enum ExecutorType { LOCAL, REMOTE_SSM, AGENT }
java
Apache-2.0
e0c90f054687a18c4e095547ac5e31b8b313b3ef
2026-01-05T02:41:11.405497Z
false