Skip to main content
summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'bundles/org.eclipse.equinox.p2.artifact.repository/src/org')
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/AbstractBufferingStep.java104
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/Messages.java27
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/messages.properties13
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java84
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/Messages.java32
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/messages.properties16
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java95
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java33
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java25
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java138
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java77
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java580
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java153
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java71
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java283
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java365
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java79
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java104
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties54
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java127
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java77
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/KeyIndex.java84
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java138
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java80
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java1069
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java144
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java517
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/UniversalUniqueIdentifier.java349
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/Messages.java28
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java128
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java205
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ZipVerifierStep.java43
-rw-r--r--bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/messages.properties14
33 files changed, 0 insertions, 5336 deletions
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/AbstractBufferingStep.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/AbstractBufferingStep.java
deleted file mode 100644
index 17e7b4138..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/AbstractBufferingStep.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 compeople AG and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * compeople AG (Stefan Liebig) - initial API and implementation
- * IBM Corporation - ongoing development
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.processing;
-
-import java.io.*;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.equinox.internal.p2.artifact.repository.Activator;
-import org.eclipse.equinox.internal.p2.core.helpers.FileUtils;
-import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep;
-import org.eclipse.osgi.util.NLS;
-
-public abstract class AbstractBufferingStep extends ProcessingStep {
- private static final String WORK_DIR_PREFIX = "work"; //$NON-NLS-1$
- private static final String WORK_DIR_SUFFIX = ""; //$NON-NLS-1$
- protected static final String JAR_SUFFIX = ".jar"; //$NON-NLS-1$
- protected static final String INCOMING_ROOT = "p2.optimizers.incoming"; //$NON-NLS-1$
- protected static final String RESULT_ROOT = "p2.optimizers.result"; //$NON-NLS-1$
- protected static final String PREDECESSOR_ROOT = "p2.optimizers.predecessor"; //$NON-NLS-1$
-
- protected OutputStream incomingStream;
- private File workDir;
-
- protected AbstractBufferingStep() {
- super();
- }
-
- public void write(int b) throws IOException {
- OutputStream stream = getOutputStream();
- stream.write(b);
- }
-
- protected OutputStream getOutputStream() throws IOException {
- if (incomingStream != null)
- return incomingStream;
- // if buffering, store input stream in temporary file
- incomingStream = createIncomingStream();
- return incomingStream;
- }
-
- protected abstract OutputStream createIncomingStream() throws IOException;
-
- public void close() throws IOException {
- // When we go to close we must have seen all the content we are going to see.
- // If no one wrote to the temp stream then we return an error. If there is
- // content then close the temporary stream and perform the processing.
- // Performing the step should result in the new content being written to
- // the destination. Make sure we delete the temporary file if any.
- try {
- if (incomingStream != null) {
- incomingStream.close();
- // if canceled then skip processing
- if (getStatus() != null && getStatus().getSeverity() != IStatus.CANCEL)
- performProcessing();
- } else {
- setStatus(new Status(IStatus.ERROR, Activator.ID, Messages.Empty_stream));
- }
- } finally {
- incomingStream = null;
- cleanupTempFiles();
- cleanupWorkDir();
- }
-
- super.close();
- // TODO need to get real status here. sometimes the optimizers do not give
- // any reasonable return status
- // COMMENT status is initially set to OK!
- }
-
- protected abstract void performProcessing() throws IOException;
-
- protected void cleanupTempFiles() {
- }
-
- private void cleanupWorkDir() throws IOException {
- if (workDir != null) {
- FileUtils.deleteAll(workDir);
- // TODO try twice since there seems to be some cases where the dir is not
- // deleted the first time. At least on Windows...
- FileUtils.deleteAll(workDir);
- }
- }
-
- protected File getWorkDir() throws IOException {
- if (workDir != null)
- return workDir;
- workDir = File.createTempFile(WORK_DIR_PREFIX, WORK_DIR_SUFFIX);
- if (!workDir.delete())
- throw new IOException(NLS.bind(Messages.Can_not_delete_temp_dir, workDir));
- if (!workDir.mkdirs())
- throw new IOException(NLS.bind(Messages.Can_not_create_temp_dir, workDir));
- return workDir;
- }
-
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/Messages.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/Messages.java
deleted file mode 100644
index 52285b00f..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/Messages.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others. All rights reserved. This
- * program and the accompanying materials are made available under the terms of
- * the Eclipse Public License v1.0 which accompanies this distribution, and is
- * available at http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: IBM Corporation - initial API and implementation
- ******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.processing;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.artifact.processing.messages"; //$NON-NLS-1$
-
- public static String Can_not_create_temp_dir;
- public static String Can_not_delete_temp_dir;
- public static String Empty_stream;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/messages.properties b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/messages.properties
deleted file mode 100644
index b95da029f..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processing/messages.properties
+++ /dev/null
@@ -1,13 +0,0 @@
-###############################################################################
-# Copyright (c) 2005, 2008 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-Can_not_create_temp_dir=Cannot create temporary working directory {0}.
-Can_not_delete_temp_dir=Cannot create temporary working directory {1}.
-Empty_stream=Empty intermediate incoming stream. Probably zero length input.
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java
deleted file mode 100644
index 49aa609a2..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/MD5Verifier.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2008 compeople AG and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * compeople AG (Stefan Liebig) - initial API and implementation
- * IBM Corporation - ongoing development
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.processors.md5;
-
-import java.io.IOException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.equinox.internal.p2.artifact.repository.Activator;
-import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep;
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor;
-import org.eclipse.osgi.util.NLS;
-
-public class MD5Verifier extends ProcessingStep {
-
- protected String expectedMD5;
- private MessageDigest md5;
-
- public MD5Verifier() {
- super();
- }
-
- public MD5Verifier(String expected) {
- super();
- this.expectedMD5 = expected;
- basicInitialize(null);
- }
-
- //This handle the case where the MD5 verification is initiated by a processing step
- public void initialize(IProvisioningAgent agent, IProcessingStepDescriptor descriptor, IArtifactDescriptor context) {
- super.initialize(agent, descriptor, context);
- String data = descriptor.getData();
- if (IArtifactDescriptor.DOWNLOAD_MD5.equals(data))
- expectedMD5 = context.getProperty(IArtifactDescriptor.DOWNLOAD_MD5);
- else if (IArtifactDescriptor.ARTIFACT_MD5.equals(data))
- expectedMD5 = context.getProperty(IArtifactDescriptor.ARTIFACT_MD5);
- else
- expectedMD5 = data;
- basicInitialize(descriptor);
- }
-
- private void basicInitialize(IProcessingStepDescriptor descriptor) {
- int code = (descriptor == null) ? IStatus.ERROR : descriptor.isRequired() ? IStatus.ERROR : IStatus.INFO;
- if (expectedMD5 == null || expectedMD5.length() != 32)
- setStatus(new Status(code, Activator.ID, NLS.bind(Messages.Error_invalid_hash, expectedMD5)));
- try {
- md5 = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
- } catch (NoSuchAlgorithmException e) {
- setStatus(new Status(code, Activator.ID, Messages.Error_MD5_unavailable, e));
- }
- }
-
- public void write(int b) throws IOException {
- md5.update((byte) b);
- getDestination().write(b);
- }
-
- public void close() throws IOException {
- byte[] digest = md5.digest();
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < digest.length; i++) {
- if ((digest[i] & 0xFF) < 0x10)
- buf.append('0');
- buf.append(Integer.toHexString(digest[i] & 0xFF));
- }
-
- // if the hashes don't line up set the status to error.
- if (!buf.toString().equals(expectedMD5))
- setStatus(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.Error_unexpected_hash, expectedMD5, buf)));
- super.close();
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/Messages.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/Messages.java
deleted file mode 100644
index 41616abbf..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/Messages.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.equinox.internal.p2.artifact.processors.md5;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.artifact.processors.md5.messages"; //$NON-NLS-1$
-
- public static String Error_invalid_hash;
- public static String Error_MD5_unavailable;
- public static String Error_unexpected_hash;
- public static String warning_differentMD5;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- //empty
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/messages.properties b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/messages.properties
deleted file mode 100644
index f82bb997a..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/md5/messages.properties
+++ /dev/null
@@ -1,16 +0,0 @@
-###############################################################################
-# Copyright (c) 2008, 2009 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-Error_invalid_hash=MD5 value not available or incorrect size, {0}.
-Error_MD5_unavailable=Could not create MD5 algorithm.
-Error_unexpected_hash=MD5 hash is not as expected. Expected: {0} and found {1}.
-
-warning_differentMD5=The repositories {0} and {1} have different MD5 sums for the artifact [{2}]. \ No newline at end of file
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java
deleted file mode 100644
index fa96f4b42..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/processors/pack200/Pack200ProcessorStep.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2009 compeople AG and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * compeople AG (Stefan Liebig) - initial API and implementation
- * IBM Corporation - ongoing development
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.processors.pack200;
-
-import java.io.*;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.equinox.internal.p2.artifact.processing.AbstractBufferingStep;
-import org.eclipse.equinox.internal.p2.artifact.repository.Activator;
-import org.eclipse.equinox.internal.p2.core.helpers.FileUtils;
-import org.eclipse.equinox.internal.p2.jarprocessor.UnpackStep;
-import org.eclipse.equinox.internal.p2.jarprocessor.Utils;
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor;
-import org.eclipse.internal.provisional.equinox.p2.jarprocessor.JarProcessorExecutor;
-import org.eclipse.internal.provisional.equinox.p2.jarprocessor.JarProcessorExecutor.Options;
-
-/**
- * The Pack200Unpacker expects an input containing ".jar.pack.gz" data.
- */
-public class Pack200ProcessorStep extends AbstractBufferingStep {
- public static final String PACKED_SUFFIX = ".pack.gz"; //$NON-NLS-1$
- private static boolean detailedResult = false;
-
- private File incoming;
-
- protected OutputStream createIncomingStream() throws IOException {
- incoming = File.createTempFile(INCOMING_ROOT, JAR_SUFFIX + PACKED_SUFFIX);
- return new BufferedOutputStream(new FileOutputStream(incoming));
- }
-
- public void initialize(IProvisioningAgent agent, IProcessingStepDescriptor descriptor, IArtifactDescriptor context) {
- super.initialize(agent, descriptor, context);
- if (!UnpackStep.canUnpack()) {
- IStatus status = null;
- if (detailedResult) {
- status = new Status(IStatus.ERROR, Activator.ID, "Unpack facility not configured."); //$NON-NLS-1$
- detailedResult = true;
- } else {
- String[] locations = Utils.getPack200Commands("unpack200"); //$NON-NLS-1$
- StringBuffer locationTried = new StringBuffer(100);
- for (int i = 0; i < locations.length; i++) {
- locationTried.append(locations[i]).append(", "); //$NON-NLS-1$
- }
- status = new Status(IStatus.ERROR, Activator.ID, "Unpack facility not configured. The locations searched for unpack200 are: " + locationTried); //$NON-NLS-1$
- }
- setStatus(status);
- }
- }
-
- protected void cleanupTempFiles() {
- super.cleanupTempFiles();
- if (incoming != null)
- incoming.delete();
- }
-
- protected void performProcessing() throws IOException {
- File resultFile = null;
- try {
- resultFile = process();
- // now write the processed content to the destination
- if (resultFile.length() > 0) {
- InputStream resultStream = new BufferedInputStream(new FileInputStream(resultFile));
- FileUtils.copyStream(resultStream, true, getDestination(), false);
- } else {
- setStatus(new Status(IStatus.ERROR, Activator.ID, "Unpacking fails because intermediate file is empty: " + resultFile)); //$NON-NLS-1$
- }
- } finally {
- if (resultFile != null)
- resultFile.delete();
- }
- }
-
- protected File process() throws IOException {
- Options options = new Options();
- options.unpack = true;
- // TODO use false here assuming that all content is conditioned. Need to revise this
- options.processAll = false;
- options.input = incoming;
- options.outputDir = getWorkDir().getPath();
- options.verbose = false;
- new JarProcessorExecutor().runJarProcessor(options);
- return new File(getWorkDir(), incoming.getName().substring(0, incoming.getName().length() - PACKED_SUFFIX.length()));
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java
deleted file mode 100644
index 043ba761d..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Activator.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import org.osgi.framework.BundleActivator;
-import org.osgi.framework.BundleContext;
-
-public class Activator implements BundleActivator {
- public static final String ID = "org.eclipse.equinox.p2.artifact.repository"; //$NON-NLS-1$
- public static final String REPO_PROVIDER_XPT = ID + '.' + "artifactRepositories"; //$NON-NLS-1$
-
- private static BundleContext context;
-
- public static BundleContext getContext() {
- return Activator.context;
- }
-
- public void start(BundleContext aContext) throws Exception {
- Activator.context = aContext;
- }
-
- public void stop(BundleContext aContext) throws Exception {
- Activator.context = null;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java
deleted file mode 100644
index 6a0a01505..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryComponent.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager;
-
-/**
- * Service factory providing {@link IArtifactRepositoryManager} instances.
- */
-public class ArtifactRepositoryComponent implements IAgentServiceFactory {
-
- public Object createService(IProvisioningAgent agent) {
- return new ArtifactRepositoryManager(agent);
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java
deleted file mode 100644
index 155f09f15..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRepositoryManager.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Genuitec LLC - various bug fixes
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import java.net.URI;
-import java.util.HashMap;
-import java.util.Map;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
-import org.eclipse.equinox.internal.p2.repository.helpers.AbstractRepositoryManager;
-import org.eclipse.equinox.internal.p2.repository.helpers.LocationProperties;
-import org.eclipse.equinox.p2.core.*;
-import org.eclipse.equinox.p2.metadata.IArtifactKey;
-import org.eclipse.equinox.p2.repository.IRepository;
-import org.eclipse.equinox.p2.repository.artifact.*;
-import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory;
-
-/**
- * Default implementation of {@link IArtifactRepositoryManager}.
- *
- * TODO the current assumption that the "location" is the dir/root limits us to
- * having just one repository in a given URL..
- */
-public class ArtifactRepositoryManager extends AbstractRepositoryManager<IArtifactKey> implements IArtifactRepositoryManager {
-
- public ArtifactRepositoryManager(IProvisioningAgent agent) {
- super(agent);
- }
-
- public void addRepository(IArtifactRepository repository) {
- super.addRepository(repository, true, null);
- }
-
- public IArtifactRequest createMirrorRequest(IArtifactKey key, IArtifactRepository destination, Map<String, String> destinationDescriptorProperties, Map<String, String> destinationRepositoryProperties) {
- return new MirrorRequest(key, destination, destinationDescriptorProperties, destinationRepositoryProperties);
- }
-
- public IArtifactRepository createRepository(URI location, String name, String type, Map<String, String> properties) throws ProvisionException {
- return (IArtifactRepository) doCreateRepository(location, name, type, properties);
- }
-
- public IArtifactRepository getRepository(URI location) {
- return (IArtifactRepository) basicGetRepository(location);
- }
-
- protected IRepository<IArtifactKey> factoryCreate(URI location, String name, String type, Map<String, String> properties, IExtension extension) throws ProvisionException {
- ArtifactRepositoryFactory factory = (ArtifactRepositoryFactory) createExecutableExtension(extension, EL_FACTORY);
- if (factory == null)
- return null;
- factory.setAgent(agent);
- return factory.create(location, name, type, properties);
- }
-
- protected IRepository<IArtifactKey> factoryLoad(URI location, IExtension extension, int flags, SubMonitor monitor) throws ProvisionException {
- ArtifactRepositoryFactory factory = (ArtifactRepositoryFactory) createExecutableExtension(extension, EL_FACTORY);
- if (factory == null)
- return null;
- factory.setAgent(agent);
- return factory.load(location, flags, monitor.newChild(10));
- }
-
- protected String getBundleId() {
- return Activator.ID;
- }
-
- protected String getDefaultSuffix() {
- return "artifacts.xml"; //$NON-NLS-1$
- }
-
- protected String getRepositoryProviderExtensionPointId() {
- return Activator.REPO_PROVIDER_XPT;
- }
-
- /**
- * Restores metadata repositories specified as system properties.
- */
- protected String getRepositorySystemProperty() {
- return "eclipse.p2.artifactRepository"; //$NON-NLS-1$
- }
-
- protected int getRepositoryType() {
- return IRepository.TYPE_ARTIFACT;
- }
-
- public IArtifactRepository loadRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
- return loadRepository(location, 0, monitor);
- }
-
- public IArtifactRepository loadRepository(URI location, int flags, IProgressMonitor monitor) throws ProvisionException {
- return (IArtifactRepository) loadRepository(location, monitor, null, flags);
- }
-
- public IArtifactRepository refreshRepository(URI location, IProgressMonitor monitor) throws ProvisionException {
- return (IArtifactRepository) basicRefreshRepository(location, monitor);
- }
-
- protected String[] getPreferredRepositorySearchOrder(LocationProperties properties) {
- return properties.getArtifactFactorySearchOrder();
- }
-
- /**
- * Restore the download cache
- */
- protected void restoreSpecialRepositories() {
- // TODO while recreating, we may want to have proxies on repo instead of the real repo object to limit what is activated.
- IAgentLocation location = (IAgentLocation) getAgent().getService(IAgentLocation.SERVICE_NAME);
- if (location == null)
- // TODO should do something here since we are failing to restore.
- return;
- URI cacheLocation = URIUtil.append(location.getDataArea("org.eclipse.equinox.p2.core"), "cache/"); //$NON-NLS-1$ //$NON-NLS-2$
-
- try {
- loadRepository(cacheLocation, null);
- return;
- } catch (ProvisionException e) {
- // log but still continue and try to create a new one
- if (e.getStatus().getCode() != ProvisionException.REPOSITORY_NOT_FOUND)
- LogHelper.log(new Status(IStatus.ERROR, Activator.ID, "Error occurred while loading download cache.", e)); //$NON-NLS-1$
- }
- try {
- Map<String, String> properties = new HashMap<String, String>(1);
- properties.put(IRepository.PROP_SYSTEM, Boolean.TRUE.toString());
- createRepository(cacheLocation, "download cache", TYPE_SIMPLE_REPOSITORY, properties); //$NON-NLS-1$
- } catch (ProvisionException e) {
- LogHelper.log(e);
- }
- }
-
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java
deleted file mode 100644
index 2248eab30..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/ArtifactRequest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.p2.metadata.IArtifactKey;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest;
-
-/**
- * Base class for all requests on an {@link IArtifactRepository}.
- */
-public abstract class ArtifactRequest implements IArtifactRequest {
- private static final Status DEFAULT_STATUS = new Status(IStatus.ERROR, Activator.ID, "default"); //$NON-NLS-1$
- protected IArtifactKey artifact;
- protected String resolvedKey;
- protected IArtifactRepository source;
- protected IStatus result = DEFAULT_STATUS;
-
- public ArtifactRequest(IArtifactKey key) {
- artifact = key;
- // TODO do we need to make this configurable? for now set default request handler to ECF
- }
-
- public IArtifactKey getArtifactKey() {
- return artifact;
- }
-
- /**
- * Returns the result of the previous call to {@link #perform(IArtifactRepository, IProgressMonitor)},
- * or <code>null</code> if perform has never been called.
- *
- * @return The result of the previous perform call.
- */
- public IStatus getResult() {
- if (result == DEFAULT_STATUS)
- return new Status(IStatus.ERROR, Activator.ID, "No repository found containing: " + getArtifactKey().toString());
-
- return result;
- }
-
- protected IArtifactRepository getSourceRepository() {
- return source;
- }
-
- /**
- * Performs the artifact request, and sets the result status.
- *
- * @param sourceRepository the repository to download the artifact from
- * @param monitor a progress monitor, or <code>null</code> if progress
- * reporting is not desired
- */
- abstract public void perform(IArtifactRepository sourceRepository, IProgressMonitor monitor);
-
- /**
- * Sets the result of an invocation of {@link #perform(IArtifactRepository, IProgressMonitor)}.
- * This method is called by subclasses to set the result status for
- * this request.
- *
- * @param value The result status
- */
- protected void setResult(IStatus value) {
- result = value;
- }
-
- protected void setSourceRepository(IArtifactRepository value) {
- source = value;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java
deleted file mode 100644
index 928d34b19..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepository.java
+++ /dev/null
@@ -1,580 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Sonatype Inc - ongoing development
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import java.io.*;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
-import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryIO;
-import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState;
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.core.ProvisionException;
-import org.eclipse.equinox.p2.metadata.IArtifactKey;
-import org.eclipse.equinox.p2.query.*;
-import org.eclipse.equinox.p2.repository.*;
-import org.eclipse.equinox.p2.repository.artifact.*;
-import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository;
-import org.eclipse.osgi.util.NLS;
-
-public class CompositeArtifactRepository extends AbstractArtifactRepository implements ICompositeRepository<IArtifactKey> {
-
- static final public String REPOSITORY_TYPE = CompositeArtifactRepository.class.getName();
- static final private Integer REPOSITORY_VERSION = new Integer(1);
- static final public String XML_EXTENSION = ".xml"; //$NON-NLS-1$
- static final public String JAR_EXTENSION = ".jar"; //$NON-NLS-1$
- static final public String CONTENT_FILENAME = "compositeArtifacts"; //$NON-NLS-1$
- public static final String PI_REPOSITORY_TYPE = "compositeArtifactRepository"; //$NON-NLS-1$
-
- // keep a list of the child URIs. they can be absolute or relative. they may or may not point
- // to a valid reachable repo
- private List<URI> childrenURIs = new ArrayList<URI>();
- // keep a list of the repositories that we have successfully loaded
- private List<ChildInfo> loadedRepos = new ArrayList<ChildInfo>();
- private IArtifactRepositoryManager manager;
- private boolean disableSave;
-
- /**
- * Create a Composite repository in memory.
- * @return the repository or null if unable to create one
- */
- public static CompositeArtifactRepository createMemoryComposite(IProvisioningAgent agent) {
- if (agent == null)
- return null;
- IArtifactRepositoryManager manager = (IArtifactRepositoryManager) agent.getService(IArtifactRepositoryManager.SERVICE_NAME);
- if (manager == null)
- return null;
- try {
- //create a unique URI
- long time = System.currentTimeMillis();
- URI repositoryURI = new URI("memory:" + String.valueOf(time)); //$NON-NLS-1$
- while (manager.contains(repositoryURI))
- repositoryURI = new URI("memory:" + String.valueOf(++time)); //$NON-NLS-1$
-
- CompositeArtifactRepository result = (CompositeArtifactRepository) manager.createRepository(repositoryURI, repositoryURI.toString(), IArtifactRepositoryManager.TYPE_COMPOSITE_REPOSITORY, null);
- manager.removeRepository(repositoryURI);
- return result;
- } catch (ProvisionException e) {
- LogHelper.log(e);
- // just return null
- } catch (URISyntaxException e) {
- // just return null
- }
- return null;
- }
-
- private IArtifactRepositoryManager getManager() {
- return manager;
- }
-
- /**
- * This is only called by the parser when loading a repository.
- */
- CompositeArtifactRepository(IArtifactRepositoryManager manager, CompositeRepositoryState state) {
- super(manager.getAgent(), state.getName(), state.getType(), state.getVersion(), state.getLocation(), state.getDescription(), state.getProvider(), state.getProperties());
- this.manager = manager;
- for (int i = 0; i < state.getChildren().length; i++)
- addChild(state.getChildren()[i], false);
- }
-
- /**
- * @noreference This constructor is not intended to be referenced by clients.
- */
- protected CompositeArtifactRepository(IArtifactRepositoryManager manager, URI location, String repositoryName, Map<String, String> properties) {
- super(manager.getAgent(), repositoryName, REPOSITORY_TYPE, REPOSITORY_VERSION.toString(), location, null, null, properties);
- this.manager = manager;
- save();
- }
-
- /*
- * Create and return a new repository state object which represents this repository.
- * It will be used while persisting the repository to disk.
- */
- public CompositeRepositoryState toState() {
- CompositeRepositoryState result = new CompositeRepositoryState();
- result.setName(getName());
- result.setType(getType());
- result.setVersion(getVersion());
- result.setLocation(getLocation());
- result.setDescription(getDescription());
- result.setProvider(getProvider());
- result.setProperties(getProperties());
- // it is important to directly access the field so we have the relative URIs
- result.setChildren(childrenURIs.toArray(new URI[childrenURIs.size()]));
- return result;
- }
-
- /*
- * Add the given object to the specified list if it doesn't already exist
- * in it. Return a boolean value indicating whether or not the object was
- * actually added.
- */
- private static <T> boolean add(List<T> list, T obj) {
- return list.contains(obj) ? false : list.add(obj);
- }
-
- public static URI getActualLocation(URI base, boolean compress) {
- return getActualLocation(base, compress ? JAR_EXTENSION : XML_EXTENSION);
- }
-
- private static URI getActualLocation(URI base, String extension) {
- return URIUtil.append(base, CONTENT_FILENAME + extension);
- }
-
- private boolean isLocal() {
- return "file".equalsIgnoreCase(getLocation().getScheme()); //$NON-NLS-1$
- }
-
- public boolean isModifiable() {
- return isLocal();
- }
-
- public void addChild(URI childURI) {
- addChild(childURI, true);
- }
-
- private void addChild(URI childURI, boolean save) {
- URI absolute = URIUtil.makeAbsolute(childURI, getLocation());
- if (childrenURIs.contains(childURI) || childrenURIs.contains(absolute))
- return;
- childrenURIs.add(childURI);
- if (save)
- save();
- try {
- IArtifactRepository repo = load(childURI);
- loadedRepos.add(new ChildInfo(repo));
- } catch (ProvisionException e) {
- LogHelper.log(e);
- }
- }
-
- // public boolean addChild(URI childURI, String comparatorID) {
- // try {
- // IArtifactRepository repo = load(childURI);
- // if (isSane(repo, comparatorID)) {
- // addChild(childURI);
- // //Add was successful
- // return true;
- // }
- // } catch (ProvisionException e) {
- // LogHelper.log(e);
- // }
- //
- // //Add was not successful
- // return false;
- // }
-
- public void removeChild(URI childURI) {
- boolean removed = childrenURIs.remove(childURI);
- // if the child wasn't there make sure and try the other permutation
- // (absolute/relative) to see if it really is in the list.
- URI other = childURI.isAbsolute() ? URIUtil.makeRelative(childURI, getLocation()) : URIUtil.makeAbsolute(childURI, getLocation());
- if (!removed)
- childrenURIs.remove(other);
-
- if (removed) {
- // we removed the child from the list so remove the associated repo object as well
- ChildInfo found = null;
- for (ChildInfo current : loadedRepos) {
- URI repoLocation = current.repo.getLocation();
- if (URIUtil.sameURI(childURI, repoLocation) || URIUtil.sameURI(other, repoLocation)) {
- found = current;
- break;
- }
- }
- if (found != null)
- loadedRepos.remove(found);
- save();
- }
- }
-
- public void removeAllChildren() {
- childrenURIs.clear();
- loadedRepos.clear();
- save();
- }
-
- public List<URI> getChildren() {
- List<URI> result = new ArrayList<URI>();
- for (URI uri : childrenURIs)
- result.add(URIUtil.makeAbsolute(uri, getLocation()));
- return result;
- }
-
- public List<IArtifactRepository> getLoadedChildren() {
- List<IArtifactRepository> result = new ArrayList<IArtifactRepository>(loadedRepos.size());
- for (ChildInfo info : loadedRepos) {
- result.add(info.repo);
- }
- return result;
- }
-
- /**
- * Composite repositories should be unable to directly modify their child repositories
- */
- public synchronized void addDescriptor(IArtifactDescriptor descriptor) {
- throw new UnsupportedOperationException(Messages.exception_unsupportedAddToComposite);
- }
-
- /**
- * Composite repositories should be unable to directly modify their child repositories
- */
- public void addDescriptors(IArtifactDescriptor[] descriptors) {
- throw new UnsupportedOperationException(Messages.exception_unsupportedAddToComposite);
- }
-
- /**
- * Composite repositories should be unable to directly modify their child repositories
- */
- public void removeDescriptor(IArtifactKey key) {
- throw new UnsupportedOperationException(Messages.exception_unsupportedRemoveFromComposite);
- }
-
- /**
- * Composite repositories should be unable to directly modify their child repositories
- */
- public void removeDescriptor(IArtifactDescriptor descriptor) {
- throw new UnsupportedOperationException(Messages.exception_unsupportedRemoveFromComposite);
- }
-
- /**
- * Composite repositories should be unable to directly modify their child repositories
- */
- public synchronized void removeAll() {
- throw new UnsupportedOperationException(Messages.exception_unsupportedRemoveFromComposite);
- }
-
- /**
- * Composite repositories should be unable to directly modify their child repositories,
- * Composite repositories should not have their own content.
- * Therefore, they should not be allowed to have OutputStreams
- */
- public OutputStream getOutputStream(IArtifactDescriptor descriptor) {
- throw new UnsupportedOperationException(Messages.exception_unsupportedGetOutputStream);
- }
-
- public boolean contains(IArtifactKey key) {
- for (ChildInfo current : loadedRepos) {
- if (current.isGood() && current.repo.contains(key))
- return true;
- }
- return false;
- }
-
- public boolean contains(IArtifactDescriptor descriptor) {
- for (ChildInfo current : loadedRepos) {
- if (current.isGood() && current.repo.contains(descriptor))
- return true;
- }
- return false;
- }
-
- public IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) {
- ArrayList<IArtifactDescriptor> result = new ArrayList<IArtifactDescriptor>();
- for (ChildInfo current : loadedRepos) {
- if (current.isGood()) {
- IArtifactDescriptor[] tempResult = current.repo.getArtifactDescriptors(key);
- for (int i = 0; i < tempResult.length; i++)
- add(result, tempResult[i]);
- }
- }
- return result.toArray(new IArtifactDescriptor[result.size()]);
- }
-
- public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) {
- SubMonitor subMonitor = SubMonitor.convert(monitor, requests.length);
- MultiStatus multiStatus = new MultiStatus(Activator.ID, IStatus.OK, Messages.message_childrenRepos, null);
- for (ChildInfo childInfo : loadedRepos) {
- if (requests.length == 0)
- break;
- IArtifactRepository current = childInfo.repo;
- IArtifactRequest[] applicable = getRequestsForRepository(current, requests);
- IStatus dlStatus = current.getArtifacts(applicable, subMonitor.newChild(requests.length));
- multiStatus.add(dlStatus);
- if (dlStatus.getSeverity() == IStatus.CANCEL)
- return multiStatus;
- requests = filterUnfetched(requests);
- subMonitor.setWorkRemaining(requests.length);
-
- if (monitor.isCanceled())
- return Status.CANCEL_STATUS;
- }
- return multiStatus;
- }
-
- public IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- return getRawOrNormalArtifact(descriptor, destination, monitor, false);
- }
-
- public IStatus getRawArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- return getRawOrNormalArtifact(descriptor, destination, monitor, true);
- }
-
- private IStatus getRawOrNormalArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor, boolean raw) {
- for (Iterator<ChildInfo> childIterator = loadedRepos.iterator(); childIterator.hasNext();) {
- ChildInfo current = childIterator.next();
- if (current.isGood() && current.repo.contains(descriptor)) {
- // Child hasn't failed & contains descriptor
- IStatus status = raw ? current.repo.getRawArtifact(descriptor, destination, monitor) : current.repo.getArtifact(descriptor, destination, monitor);
- if (status.isOK()) {
- //we are done with this artifact so forgive bad children so they can try again on next artifact
- resetChildFailures();
- return Status.OK_STATUS;
- }
- // Download failed
- if (status.getCode() == CODE_RETRY || status.getCode() == IStatus.CANCEL)
- // Child has mirrors & wants to be retried, or we were canceled
- return status;
- // Child has failed us, mark it bad
- current.setBad(true);
- // If more children are available, set retry
- if (childIterator.hasNext())
- return new MultiStatus(Activator.ID, CODE_RETRY, new IStatus[] {status}, NLS.bind(Messages.retryRequest, current.repo.getLocation(), descriptor.getArtifactKey()), null);
- // Nothing that can be done, pass child's failure on
- resetChildFailures();
- return status;
- }
- if (monitor.isCanceled())
- return Status.CANCEL_STATUS;
- }
- return new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.artifact_not_found, descriptor));
- }
-
- /**
- * Rests the failure state on all children to 'good'. This is done after a successful
- * download to ensure that children who failed to obtain one artifact get a chance
- * on the next artifact.
- */
- private void resetChildFailures() {
- for (ChildInfo current : loadedRepos)
- current.setBad(false);
- }
-
- private IArtifactRequest[] filterUnfetched(IArtifactRequest[] requests) {
- ArrayList<IArtifactRequest> filteredRequests = new ArrayList<IArtifactRequest>();
- for (int i = 0; i < requests.length; i++) {
- if (requests[i].getResult() == null || !requests[i].getResult().isOK()) {
- filteredRequests.add(requests[i]);
- }
- }
-
- IArtifactRequest[] filteredArtifactRequests = new IArtifactRequest[filteredRequests.size()];
- filteredRequests.toArray(filteredArtifactRequests);
- return filteredArtifactRequests;
- }
-
- private IArtifactRequest[] getRequestsForRepository(IArtifactRepository repository, IArtifactRequest[] requests) {
- ArrayList<IArtifactRequest> applicable = new ArrayList<IArtifactRequest>();
- for (int i = 0; i < requests.length; i++) {
- if (repository.contains(requests[i].getArtifactKey()))
- applicable.add(requests[i]);
- }
- return applicable.toArray(new IArtifactRequest[applicable.size()]);
- }
-
- /**
- * This method is only protected for testing purposes
- *
- * @nooverride This method is not intended to be re-implemented or extended by clients.
- * @noreference This method is not intended to be referenced by clients.
- */
- protected void save() {
- if (disableSave)
- return;
- if (!isModifiable())
- return;
- boolean compress = "true".equalsIgnoreCase(getProperty(PROP_COMPRESSED)); //$NON-NLS-1$
- OutputStream os = null;
- try {
- URI actualLocation = getActualLocation(getLocation(), false);
- File artifactsFile = URIUtil.toFile(actualLocation);
- File jarFile = URIUtil.toFile(getActualLocation(getLocation(), true));
- if (!compress) {
- if (jarFile.exists()) {
- jarFile.delete();
- }
- if (!artifactsFile.exists()) {
- // create parent folders
- artifactsFile.getParentFile().mkdirs();
- }
- os = new FileOutputStream(artifactsFile);
- } else {
- if (artifactsFile.exists()) {
- artifactsFile.delete();
- }
- if (!jarFile.exists()) {
- if (!jarFile.getParentFile().exists())
- jarFile.getParentFile().mkdirs();
- jarFile.createNewFile();
- }
- JarOutputStream jOs = new JarOutputStream(new FileOutputStream(jarFile));
- jOs.putNextEntry(new JarEntry(new Path(artifactsFile.getAbsolutePath()).lastSegment()));
- os = jOs;
- }
- super.setProperty(IRepository.PROP_TIMESTAMP, Long.toString(System.currentTimeMillis()));
- new CompositeRepositoryIO().write(toState(), os, PI_REPOSITORY_TYPE);
- } catch (IOException e) {
- LogHelper.log(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_WRITE, NLS.bind(Messages.io_failedWrite, getLocation()), e));
- }
- }
-
- private IArtifactRepository load(URI repoURI) throws ProvisionException {
- // make sure we are dealing with an absolute location
- repoURI = URIUtil.makeAbsolute(repoURI, getLocation());
- boolean loaded = getManager().contains(repoURI);
- IArtifactRepository repo = getManager().loadRepository(repoURI, null);
- if (!loaded) {
- //set enabled to false so repositories do not get polled twice
- getManager().setEnabled(repoURI, false);
- //set repository to system to hide from users
- getManager().setRepositoryProperty(repoURI, IRepository.PROP_SYSTEM, String.valueOf(true));
- }
- return repo;
- }
-
- // /**
- // * A method to check if the content of a repository is consistent with the other children by
- // * comparing content using the artifactComparator specified by the comparatorID
- // * @param toCheckRepo the repository to check
- // * @param comparatorID
- // * @return <code>true</code> if toCheckRepo is consistent, <code>false</code> if toCheckRepo
- // * contains an equal descriptor to that of a child and they refer to different artifacts on disk.
- // */
- // private boolean isSane(IArtifactRepository toCheckRepo, String comparatorID) {
- // IArtifactComparator comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID);
- // for (ChildInfo childInfo : loadedRepos) {
- // IArtifactRepository current = childInfo.repo;
- // if (!current.equals(toCheckRepo)) {
- // if (!isSane(toCheckRepo, current, comparator))
- // return false;
- // }
- // }
- // return true;
- // }
- //
- // /*
- // * Check the two given repositories against each other using the given comparator.
- // */
- // private boolean isSane(IArtifactRepository one, IArtifactRepository two, IArtifactComparator comparator) {
- // IQueryResult<IArtifactKey> toCheckKeys = one.query(ArtifactKeyQuery.ALL_KEYS, null);
- // for (Iterator<IArtifactKey> iterator = toCheckKeys.iterator(); iterator.hasNext();) {
- // IArtifactKey key = iterator.next();
- // if (!two.contains(key))
- // continue;
- // IArtifactDescriptor[] toCheckDescriptors = one.getArtifactDescriptors(key);
- // IArtifactDescriptor[] currentDescriptors = two.getArtifactDescriptors(key);
- // for (int j = 0; j < toCheckDescriptors.length; j++) {
- // if (!two.contains(toCheckDescriptors[j]))
- // continue;
- // for (int k = 0; k < currentDescriptors.length; k++) {
- // if (currentDescriptors[k].equals(toCheckDescriptors[j])) {
- // IStatus compareResult = comparator.compare(two, currentDescriptors[k], two, toCheckDescriptors[j]);
- // if (!compareResult.isOK()) {
- // LogHelper.log(compareResult);
- // return false;
- // }
- // break;
- // }
- // }
- // }
- // }
- // return true;
- // }
- //
- // /**
- // * A method that verifies that all children with matching artifact descriptors contain the same set of bytes
- // * The verification is done using the artifactComparator specified by comparatorID
- // * Assumes more valuable logging and output is the responsibility of the artifactComparator implementation.
- // * @param comparatorID
- // * @returns true if the repository is consistent, false if two equal descriptors refer to different artifacts on disk.
- // */
- // private boolean validate(String comparatorID) {
- // IArtifactComparator comparator = ArtifactComparatorFactory.getArtifactComparator(comparatorID);
- // ChildInfo[] repos = loadedRepos.toArray(new ChildInfo[loadedRepos.size()]);
- // for (int outer = 0; outer < repos.length; outer++) {
- // for (int inner = outer + 1; inner < repos.length; inner++) {
- // if (!isSane(repos[outer].repo, repos[inner].repo, comparator))
- // return false;
- // }
- // }
- // return true;
- // }
-
- private static class ChildInfo {
- IArtifactRepository repo;
- boolean good = true;
-
- ChildInfo(IArtifactRepository IArtifactRepository) {
- this.repo = IArtifactRepository;
- }
-
- void setBad(boolean bad) {
- good = !bad;
- }
-
- boolean isGood() {
- return good;
- }
- }
-
- public IQueryResult<IArtifactKey> query(IQuery<IArtifactKey> query, IProgressMonitor monitor) {
- // Query all the all the repositories this composite repo contains
- List<IArtifactRepository> repos = new ArrayList<IArtifactRepository>();
- for (ChildInfo info : loadedRepos) {
- if (info.isGood())
- repos.add(info.repo);
- }
- IQueryable<IArtifactKey> queryable = QueryUtil.compoundQueryable(repos);
- return queryable.query(query, monitor);
- }
-
- public IQueryable<IArtifactDescriptor> descriptorQueryable() {
- // Query all the all the repositories this composite repo contains
- List<IQueryable<IArtifactDescriptor>> repos = new ArrayList<IQueryable<IArtifactDescriptor>>();
- for (ChildInfo info : loadedRepos) {
- if (info.isGood())
- repos.add(info.repo.descriptorQueryable());
- }
- return QueryUtil.compoundQueryable(repos);
- }
-
- public IStatus executeBatch(IRunnableWithProgress runnable, IProgressMonitor monitor) {
- IStatus result = null;
- synchronized (this) {
- try {
- disableSave = true;
- runnable.run(monitor);
- } catch (OperationCanceledException oce) {
- return new Status(IStatus.CANCEL, Activator.ID, oce.getMessage(), oce);
- } catch (Throwable e) {
- result = new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e);
- } finally {
- disableSave = false;
- try {
- save();
- } catch (Exception e) {
- if (result != null)
- result = new MultiStatus(Activator.ID, IStatus.ERROR, new IStatus[] {result}, e.getMessage(), e);
- else
- result = new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e);
- }
- }
- }
- if (result == null)
- result = Status.OK_STATUS;
- return result;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java
deleted file mode 100644
index 180ed0137..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/CompositeArtifactRepositoryFactory.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Sonatype Inc - ongoing development
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import java.io.*;
-import java.net.URI;
-import java.util.Map;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.core.helpers.Tracing;
-import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryIO;
-import org.eclipse.equinox.internal.p2.persistence.CompositeRepositoryState;
-import org.eclipse.equinox.internal.p2.repository.CacheManager;
-import org.eclipse.equinox.p2.core.ProvisionException;
-import org.eclipse.equinox.p2.repository.IRepositoryManager;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager;
-import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory;
-import org.eclipse.osgi.util.NLS;
-
-public class CompositeArtifactRepositoryFactory extends ArtifactRepositoryFactory {
-
- private static final String JAR_EXTENSION = ".jar"; //$NON-NLS-1$
- private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$
- private static final String PROTOCOL_FILE = "file"; //$NON-NLS-1$
-
- private IArtifactRepositoryManager getManager() {
- if (getAgent() != null)
- return (IArtifactRepositoryManager) getAgent().getService(IArtifactRepositoryManager.SERVICE_NAME);
- return null;
- }
-
- /**
- * Returns a file in the local file system that contains the contents of the
- * metadata repository at the given location.
- */
- private File getLocalFile(URI location, IProgressMonitor monitor) throws IOException, ProvisionException {
- File localFile = null;
- URI jarLocation = CompositeArtifactRepository.getActualLocation(location, true);
- URI xmlLocation = CompositeArtifactRepository.getActualLocation(location, false);
- // If the repository is local, we can return the repository file directly
- if (PROTOCOL_FILE.equals(xmlLocation.getScheme())) {
- //look for a compressed local file
- localFile = URIUtil.toFile(jarLocation);
- if (localFile.exists())
- return localFile;
- //look for an uncompressed local file
- localFile = URIUtil.toFile(xmlLocation);
- if (localFile.exists())
- return localFile;
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null));
- }
- //file is not local, create a cache of the repository metadata
- CacheManager cache = (CacheManager) getAgent().getService(CacheManager.SERVICE_NAME);
- if (cache == null)
- throw new IllegalArgumentException("Cache manager service not available"); //$NON-NLS-1$
- localFile = cache.createCache(location, CompositeArtifactRepository.CONTENT_FILENAME, monitor);
- if (localFile == null) {
- //there is no remote file in either form
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null));
- }
- return localFile;
- }
-
- public IArtifactRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException {
- long time = 0;
- final String debugMsg = "Restoring artifact repository "; //$NON-NLS-1$
- if (Tracing.DEBUG_METADATA_PARSING) {
- Tracing.debug(debugMsg + location);
- time = -System.currentTimeMillis();
- }
-
- SubMonitor sub = SubMonitor.convert(monitor, 400);
- try {
- //non local repos are not modifiable
- if (!PROTOCOL_FILE.equals(location.getScheme()) && (flags & IRepositoryManager.REPOSITORY_HINT_MODIFIABLE) > 0)
- return null;
-
- File localFile = getLocalFile(location, sub.newChild(300));
- InputStream inStream = new BufferedInputStream(new FileInputStream(localFile));
- JarInputStream jarStream = null;
- try {
- //if reading from a jar, obtain a stream on the entry with the actual contents
- if (localFile.getAbsolutePath().endsWith(JAR_EXTENSION)) {
- jarStream = new JarInputStream(inStream);
- JarEntry jarEntry = jarStream.getNextJarEntry();
- String entryName = CompositeArtifactRepository.CONTENT_FILENAME + XML_EXTENSION;
- while (jarEntry != null && (!entryName.equals(jarEntry.getName()))) {
- jarEntry = jarStream.getNextJarEntry();
- }
-
- //there is a jar but the entry is missing or invalid, so treat this as an invalid repository
- if (jarEntry == null)
- throw new IOException(NLS.bind(Messages.io_invalidLocation, location.getPath()));
- }
- //parse the repository descriptor file
- sub.setWorkRemaining(100);
- InputStream descriptorStream = jarStream != null ? jarStream : inStream;
- CompositeRepositoryIO io = new CompositeRepositoryIO();
- CompositeRepositoryState resultState = io.read(localFile.toURL(), descriptorStream, CompositeArtifactRepository.PI_REPOSITORY_TYPE, sub.newChild(100));
- if (resultState.getLocation() == null)
- resultState.setLocation(location);
- CompositeArtifactRepository result = new CompositeArtifactRepository(getManager(), resultState);
- if (Tracing.DEBUG_METADATA_PARSING) {
- time += System.currentTimeMillis();
- Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$
- }
- return result;
- } finally {
- safeClose(jarStream);
- safeClose(inStream);
- }
- } catch (FileNotFoundException e) {
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, e));
- } catch (IOException e) {
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, e));
- } finally {
- if (monitor != null)
- monitor.done();
- }
- }
-
- public IArtifactRepository create(URI location, String name, String type, Map<String, String> properties) {
- return new CompositeArtifactRepository(getManager(), location, name, properties);
- }
-
- /**
- * Closes a stream, ignoring any secondary exceptions
- */
- private void safeClose(InputStream stream) {
- if (stream == null)
- return;
- try {
- stream.close();
- } catch (IOException e) {
- //ignore
- }
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java
deleted file mode 100644
index 72dedad7d..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/Messages.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.p2.artifact.repository.messages"; //$NON-NLS-1$
-
- public static String artifact_not_found;
- public static String available_already_in;
- public static String no_location;
- public static String downloading;
- public static String error_closing_stream;
- public static String io_failedRead;
- public static String io_failedWrite;
- public static String io_incompatibleVersion;
- public static String io_invalidLocation;
- public static String SignatureVerification_failedRead;
- public static String SignatureVerification_invalidContent;
- public static String SignatureVerification_invalidFileContent;
-
- public static String SignatureVerifier_OutOfMemory;
- public static String io_parseError;
- public static String mirroring;
- public static String repoMan_internalError;
- public static String repoFailedWrite;
-
- public static String sar_downloading;
- public static String sar_downloadJobName;
- public static String sar_failedMkdir;
- public static String sar_reportStatus;
-
- public static String mirror_alreadyExists;
- public static String message_childrenRepos;
- public static String exception_comparatorNotFound;
- public static String exception_noComparators;
- public static String exception_unsupportedAddToComposite;
-
- public static String exception_unsupportedGetOutputStream;
- public static String exception_unsupportedRemoveFromComposite;
-
- public static String MirrorLog_Console_Log;
- public static String MirrorLog_Exception_Occurred;
-
- public static String MirrorRequest_multipleDownloadProblems;
-
- public static String exception_unableToCreateParentDir;
-
- public static String folder_artifact_not_file_repo;
-
- public static String retryRequest;
-
- static {
- // initialize resource bundles
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- // Do not instantiate
- }
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java
deleted file mode 100644
index 1262780f2..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorRequest.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Compeople AG (Stefan Liebig) - various ongoing maintenance
- * Genuitec LLC - various bug fixes
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import java.io.*;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.HashMap;
-import java.util.Map;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactDescriptor;
-import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
-import org.eclipse.equinox.internal.p2.repository.RepositoryTransport;
-import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler;
-import org.eclipse.equinox.internal.provisional.p2.repository.IStateful;
-import org.eclipse.equinox.p2.core.ProvisionException;
-import org.eclipse.equinox.p2.metadata.IArtifactKey;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
-import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor;
-import org.eclipse.osgi.util.NLS;
-
-/**
- * A request to mirror (copy) an artifact into a given destination artifact repository.
- */
-public class MirrorRequest extends ArtifactRequest {
- /**
- * The name of a repository property on an artifact repository, indicating the base URI
- * to be used for reporting download statistics.
- */
- private static final String PROP_STATS_URI = "p2.statsURI"; //$NON-NLS-1$
-
- /**
- * The name of a property on an artifact descriptor, indicating the relative download URI
- * to be used to report download statistics for that artifact. The value of this property,
- * if present, is appended to the {@link #PROP_STATS_URI} to create the full URI
- * for reporting download statistics for that artifact.
- */
- private static final String PROP_DOWNLOAD_STATS = "download.stats"; //$NON-NLS-1$
-
- protected final IArtifactRepository target;
-
- private final Map<String, String> targetDescriptorProperties;
- private final Map<String, String> targetRepositoryProperties;
- protected IArtifactDescriptor descriptor;
-
- public MirrorRequest(IArtifactKey key, IArtifactRepository targetRepository, Map<String, String> targetDescriptorProperties, Map<String, String> targetRepositoryProperties) {
- super(key);
- target = targetRepository;
- if (targetDescriptorProperties == null || targetDescriptorProperties.isEmpty()) {
- this.targetDescriptorProperties = null;
- } else {
- this.targetDescriptorProperties = new HashMap<String, String>();
- this.targetDescriptorProperties.putAll(targetDescriptorProperties);
- }
-
- if (targetRepositoryProperties == null || targetRepositoryProperties.isEmpty()) {
- this.targetRepositoryProperties = null;
- } else {
- this.targetRepositoryProperties = new HashMap<String, String>();
- this.targetRepositoryProperties.putAll(targetRepositoryProperties);
- }
- }
-
- public void perform(IArtifactRepository sourceRepository, IProgressMonitor monitor) {
- monitor.subTask(NLS.bind(Messages.downloading, getArtifactKey().getId()));
- setSourceRepository(sourceRepository);
- // Do we already have the artifact in the target?
- if (target.contains(getArtifactKey())) {
- setResult(new Status(IStatus.OK, Activator.ID, NLS.bind(Messages.available_already_in, getArtifactKey())));
- return;
- }
-
- // if the request does not have a descriptor then try to fill one in by getting
- // the list of all and randomly picking one that appears to be optimized.
- IArtifactDescriptor optimized = null;
- IArtifactDescriptor canonical = null;
- if (descriptor == null) {
- IArtifactDescriptor[] descriptors = source.getArtifactDescriptors(getArtifactKey());
- if (descriptors.length > 0) {
- for (int i = 0; i < descriptors.length; i++) {
- if (descriptors[i].getProperty(IArtifactDescriptor.FORMAT) == null)
- canonical = descriptors[i];
- else if (ProcessingStepHandler.canProcess(descriptors[i]))
- optimized = descriptors[i];
- }
- boolean chooseCanonical = source.getLocation().getScheme().equals("file"); //$NON-NLS-1$
- // If the source repo is local then look for a canonical descriptor so we don't waste processing time.
- descriptor = chooseCanonical ? canonical : optimized;
- // if the descriptor is still null then we could not find our first choice of format so switch the logic.
- if (descriptor == null)
- descriptor = !chooseCanonical ? canonical : optimized;
- }
- }
-
- // if the descriptor is not set now then the repo does not have the requested artifact
- // TODO improve the reporting here. It may be the case that the repo has the artifact
- // but the client does not have a processor
- if (descriptor == null) {
- setResult(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.artifact_not_found, getArtifactKey())));
- return;
- }
-
- IArtifactDescriptor destinationDescriptor = getDestinationDescriptor(descriptor);
- IStatus status = transfer(destinationDescriptor, descriptor, monitor);
- // if ok, cancelled or transfer has already been done with the canonical form return with status set
- if (status.getSeverity() == IStatus.CANCEL) {
- setResult(status);
- return;
- }
- if (monitor.isCanceled()) {
- setResult(Status.CANCEL_STATUS);
- return;
- }
- if (status.isOK()) {
- setResult(status);
- return;
- }
-
- // failed, first remove possibly erroneously added descriptor
- if (target.contains(destinationDescriptor))
- target.removeDescriptor(destinationDescriptor);
-
- if (descriptor == canonical || canonical == null) {
- setResult(status);
- return;
- }
-
- IStatus canonicalStatus = transfer(getDestinationDescriptor(canonical), canonical, monitor);
- // To prevent the optimized transfer status severity from dominating the canonical, only merge
- // if the canonical severity is equal to or higher than the optimized transfer severity.
- if (canonicalStatus.getSeverity() < status.getSeverity())
- setResult(canonicalStatus);
- else
- setResult(new MultiStatus(Activator.ID, canonicalStatus.getCode() != 0 ? canonicalStatus.getCode() : status.getCode(), new IStatus[] {status, canonicalStatus}, Messages.MirrorRequest_multipleDownloadProblems, null));
- }
-
- private IArtifactDescriptor getDestinationDescriptor(IArtifactDescriptor sourceDescriptor) {
- // Get the descriptor to use to store the artifact
- // Since we are mirroring, ensure we clear out data from the original descriptor that may
- // not apply in the new repo location.
- // TODO this is brittle. perhaps the repo itself should do this? there are cases where
- // we really do need to give the repo the actual descriptor to use however...
- IArtifactDescriptor destinationDescriptor = target.createArtifactDescriptor(sourceDescriptor.getArtifactKey());
- // destinationDescriptor.setProcessingSteps(EMPTY_STEPS);
- // destinationDescriptor.setProperty(IArtifactDescriptor.DOWNLOAD_MD5, null);
- // destinationDescriptor.setProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE, null);
- // destinationDescriptor.setProperty(IArtifactDescriptor.FORMAT, null);
- if (targetDescriptorProperties != null && destinationDescriptor instanceof ArtifactDescriptor)
- ((ArtifactDescriptor) destinationDescriptor).addProperties(targetDescriptorProperties);
- if (targetRepositoryProperties != null && destinationDescriptor instanceof SimpleArtifactDescriptor)
- ((SimpleArtifactDescriptor) destinationDescriptor).addRepositoryProperties(targetRepositoryProperties);
- return destinationDescriptor;
- }
-
- /**
- * Keep retrying the source repository until it reports back that it will be impossible
- * to get the artifact from it.
- * @param destinationDescriptor
- * @param sourceDescriptor
- * @param monitor
- * @return the status of the transfer operation
- */
- protected IStatus transfer(IArtifactDescriptor destinationDescriptor, IArtifactDescriptor sourceDescriptor, IProgressMonitor monitor) {
- IStatus status = Status.OK_STATUS;
- // go until we get one (OK), there are no more mirrors to consider or the operation is cancelled.
- // TODO this needs to be redone with a much better mirror management scheme.
- do {
- status = transferSingle(destinationDescriptor, sourceDescriptor, monitor);
- } while (status.getSeverity() == IStatus.ERROR && status.getCode() == IArtifactRepository.CODE_RETRY);
- if (status.isOK())
- collectStats(sourceDescriptor, monitor);
- return status;
- }
-
- /**
- * Collect download statistics, if specified by the descriptor and the source repository
- */
- private void collectStats(IArtifactDescriptor sourceDescriptor, IProgressMonitor monitor) {
- final String statsProperty = sourceDescriptor.getProperty(PROP_DOWNLOAD_STATS);
- if (statsProperty == null)
- return;
- String statsRoot = sourceDescriptor.getRepository().getProperties().get(PROP_STATS_URI);
- if (statsRoot == null)
- return;
- URI statsURI;
- try {
- statsURI = URIUtil.append(new URI(statsRoot), statsProperty);
- } catch (URISyntaxException e) {
- LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Unable to report download statistics due to invalid URL: " + statsRoot + " suffix: " + statsProperty)); //$NON-NLS-1$ //$NON-NLS-2$
- return;
- }
- try {
- RepositoryTransport.getInstance().getLastModified(statsURI, monitor);
- } catch (FileNotFoundException e) {
- //ignore because it is expected that the statistics URI doesn't represent an existing file
- } catch (Exception e) {
- LogHelper.log(new Status(IStatus.WARNING, Activator.ID, "Failure reporting download statistics to URL: " + statsURI, e)); //$NON-NLS-1$
- }
- }
-
- private IStatus transferSingle(IArtifactDescriptor destinationDescriptor, IArtifactDescriptor sourceDescriptor, IProgressMonitor monitor) {
- OutputStream destination;
- try {
- destination = target.getOutputStream(destinationDescriptor);
- } catch (ProvisionException e) {
- return e.getStatus();
- }
-
- IStatus status = null;
- // Do the actual transfer
- try {
- status = getArtifact(sourceDescriptor, destination, monitor);
- if (destination instanceof IStateful && status != null && !status.isOK()) {
- IStatus destStatus = ((IStateful) destination).getStatus();
- IStatus root = extractRootCause(status);
- Throwable e = root != null ? root.getException() : null;
- ((IStateful) destination).setStatus(new MultiStatus(Activator.ID, status.getCode(), new IStatus[] {status, destStatus}, status.getMessage(), e));
- }
- } finally {
- try {
- destination.close();
- } catch (IOException e) {
- if (status != null && status.getSeverity() == IStatus.ERROR && status.getCode() == IArtifactRepository.CODE_RETRY)
- return new MultiStatus(Activator.ID, status.getCode(), new IStatus[] {status}, NLS.bind(Messages.error_closing_stream, getArtifactKey(), target.getLocation()), e);
- return new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.error_closing_stream, getArtifactKey(), target.getLocation()), e);
- }
- if (status != null && status.getSeverity() == IStatus.ERROR) {
- IStatus root = extractRootCause(status);
- if (root != null && FileNotFoundException.class == root.getException().getClass())
- return new Status(IStatus.ERROR, Activator.ID, status.getCode(), NLS.bind(Messages.artifact_not_found, getArtifactKey()), root.getException());
- }
- }
- return status;
- }
-
- protected IStatus getArtifact(IArtifactDescriptor sourceDescriptor, OutputStream destination, IProgressMonitor monitor) {
- return getSourceRepository().getArtifact(sourceDescriptor, destination, monitor);
- }
-
- /**
- * Extract the root cause. The root cause is the first severe non-MultiStatus status
- * containing an exception when searching depth first otherwise null.
- * @param status
- * @return root cause
- */
- private static IStatus extractRootCause(IStatus status) {
- if (status == null)
- return null;
- if (!status.isMultiStatus())
- return constraintStatus(status);
-
- IStatus[] children = ((MultiStatus) status).getChildren();
- if (children == null)
- return constraintStatus(status);
-
- for (int i = 0; i < children.length; i++) {
- IStatus deeper = extractRootCause(children[i]);
- if (deeper != null)
- return deeper;
- }
-
- return constraintStatus(status);
- }
-
- private static IStatus constraintStatus(IStatus status) {
- return status.getSeverity() == IStatus.ERROR && status.getException() != null ? status : null;
- }
-
- public String toString() {
- return Messages.mirroring + getArtifactKey() + " into " + target; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java
deleted file mode 100644
index 1fbd11df8..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/MirrorSelector.java
+++ /dev/null
@@ -1,365 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Cloudsmith Inc - bug fixes
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import java.io.FileNotFoundException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
-import org.eclipse.equinox.internal.p2.core.helpers.Tracing;
-import org.eclipse.equinox.internal.p2.repository.DownloadStatus;
-import org.eclipse.equinox.internal.p2.repository.RepositoryTransport;
-import org.eclipse.equinox.p2.repository.IRepository;
-import org.w3c.dom.*;
-import org.xml.sax.InputSource;
-
-/**
- * Mirror support class for repositories. This class implements
- * mirror support equivalent to the mirroring of update manager sites. A repository
- * optionally provides a mirror URL via the {@link IRepository#PROP_MIRRORS_URL} key.
- * The contents of the file at this URL is expected to be an XML document
- * containing a list of <mirror> elements. The mirrors are assumed to be already
- * sorted geographically with closer mirrors first.
- */
-public class MirrorSelector {
- private static final double LOG2 = Math.log(2);
-
- /**
- * Encapsulates information about a single mirror
- */
- public static class MirrorInfo implements Comparable<MirrorInfo> {
- private static final long PRIMARY_FAILURE_LINGER_TIME = 30000; // Retry again after 30 seconds
- private static final long SECONDARY_FAILURE_LINGER_TIME = 300000; // Wait 5 minutes
- private static final int ACCEPTABLE_FILE_NOT_FOUND_COUNT = 5; // Given an established connection, those are generally quick
- private static final Timer resetFailure = new Timer("Mirror failure timer", true); //$NON-NLS-1$
-
- long bytesPerSecond;
- int failureCount;
- int fileNotFoundCount;
- int totalFailureCount;
- private final int initialRank;
- String locationString;
-
- public MirrorInfo(String location, int initialRank) {
- this.initialRank = initialRank;
- this.locationString = location;
- if (!locationString.endsWith("/")) //$NON-NLS-1$
- locationString = locationString + "/"; //$NON-NLS-1$
- failureCount = 0;
- totalFailureCount = 0;
- bytesPerSecond = DownloadStatus.UNKNOWN_RATE;
- }
-
- /**
- * Comparison used to sort mirrors.
- */
- public synchronized int compareTo(MirrorInfo that) {
- synchronized (that) {
- double rank = 0.0;
- if (bytesPerSecond != that.bytesPerSecond) {
- if (bytesPerSecond != DownloadStatus.UNKNOWN_RATE && that.bytesPerSecond != DownloadStatus.UNKNOWN_RATE) {
- if (bytesPerSecond > that.bytesPerSecond)
- rank -= (double) bytesPerSecond / (double) that.bytesPerSecond;
- else
- rank += (double) that.bytesPerSecond / (double) bytesPerSecond;
- }
- }
-
- //less failures is better
- if (failureCount != that.failureCount) {
- if (failureCount > that.failureCount)
- rank += ((double) (failureCount + 1) / (double) (that.failureCount + 1)) * 2.0;
- else
- rank -= ((double) (that.failureCount + 1) / (double) (failureCount + 1)) * 2.0;
- }
-
- if (rank == 0.0)
- //trust that initial rank indicates geographical proximity
- rank = initialRank - that.initialRank;
-
- if (rank == 0.0)
- return 0;
-
- int intRank;
- intRank = (int) rank;
- if (intRank == 0)
- intRank = rank > 0 ? 1 : -1;
- return intRank;
- }
- }
-
- public synchronized String toString() {
- return "Mirror(" + locationString + ',' + failureCount + ',' + bytesPerSecond + ')'; //$NON-NLS-1$
- }
-
- public synchronized void decrementFailureCount() {
- if (failureCount > 0)
- failureCount--;
- }
-
- public synchronized void incrementFailureCount() {
- ++failureCount;
- ++totalFailureCount;
- if (totalFailureCount < 3) {
- resetFailure.schedule(new TimerTask() {
- @Override
- public void run() {
- decrementFailureCount();
- }
- }, totalFailureCount == 1 ? PRIMARY_FAILURE_LINGER_TIME : SECONDARY_FAILURE_LINGER_TIME);
- }
- }
-
- public synchronized void setBytesPerSecond(long newValue) {
- // Any non-positive value is treated as an unknown rate
- if (newValue <= 0)
- newValue = DownloadStatus.UNKNOWN_RATE;
-
- if (newValue > 0)
- // Back in commission
- failureCount = 0;
- bytesPerSecond = newValue;
- }
-
- public synchronized void incrementFileNotFoundCount() {
- if (++fileNotFoundCount > ACCEPTABLE_FILE_NOT_FOUND_COUNT) {
- incrementFailureCount();
- fileNotFoundCount = 0;
- }
- }
- }
-
- /**
- * The URI of the base repository being mirrored.
- */
- URI baseURI;
-
- MirrorInfo[] mirrors;
-
- private final IRepository<?> repository;
-
- private final Random random = new Random();
-
- /**
- * Constructs a mirror support class for the given repository. Mirrors are
- * not contacted and the mirrorsURL document is not parsed until a
- * mirror location request is sent.
- */
- public MirrorSelector(IRepository<?> repository) {
- this.repository = repository;
- try {
- String base = repository.getProperties().get(IRepository.PROP_MIRRORS_BASE_URL);
- if (base != null) {
- this.baseURI = new URI(base);
- } else {
- URI repositoryLocation = repository.getLocation();
- if (repositoryLocation != null)
- this.baseURI = repositoryLocation;
- }
- } catch (URISyntaxException e) {
- log("Error initializing mirrors for: " + repository.getLocation(), e); //$NON-NLS-1$
- }
- }
-
- /**
- * Parses the given mirror URL to obtain the list of mirrors. Returns the mirrors,
- * or null if mirrors could not be computed.
- *
- * Originally copied from DefaultSiteParser.getMirrors in org.eclipse.update.core
- */
- private MirrorInfo[] computeMirrors(String mirrorsURL, IProgressMonitor monitor) {
- try {
- String countryCode = Activator.getContext().getProperty("eclipse.p2.countryCode"); //$NON-NLS-1$
- if (countryCode == null || countryCode.trim().length() == 0)
- countryCode = Locale.getDefault().getCountry().toLowerCase();
- String timeZone = Activator.getContext().getProperty("eclipse.p2.timeZone"); //$NON-NLS-1$
- if (timeZone == null || timeZone.trim().length() == 0)
- timeZone = Integer.toString(new GregorianCalendar().get(Calendar.ZONE_OFFSET) / (60 * 60 * 1000));
-
- if (mirrorsURL.indexOf('?') != -1) {
- mirrorsURL = mirrorsURL + '&';
- } else {
- mirrorsURL = mirrorsURL + '?';
- }
- mirrorsURL = mirrorsURL + "countryCode=" + countryCode + "&timeZone=" + timeZone + "&format=xml"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
-
- DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
- DocumentBuilder builder = domFactory.newDocumentBuilder();
- Document document = null;
- // Use Transport to read the mirrors list (to benefit from proxy support, authentication, etc)
- RepositoryTransport transport = RepositoryTransport.getInstance();
- InputSource input = new InputSource(mirrorsURL);
- input.setByteStream(transport.stream(URIUtil.fromString(mirrorsURL), monitor));
- document = builder.parse(input);
- if (document == null)
- return null;
- NodeList mirrorNodes = document.getElementsByTagName("mirror"); //$NON-NLS-1$
- int mirrorCount = mirrorNodes.getLength();
- MirrorInfo[] infos = new MirrorInfo[mirrorCount + 1];
- for (int i = 0; i < mirrorCount; i++) {
- Element mirrorNode = (Element) mirrorNodes.item(i);
- String infoURL = mirrorNode.getAttribute("url"); //$NON-NLS-1$
- infos[i] = new MirrorInfo(infoURL, i);
- }
- //p2: add the base site as the last resort mirror so we can track download speed and failure rate
- infos[mirrorCount] = new MirrorInfo(baseURI.toString(), mirrorCount);
- return infos;
- } catch (Exception e) {
- // log if absolute url
- if (mirrorsURL != null && (mirrorsURL.startsWith("http://") //$NON-NLS-1$
- || mirrorsURL.startsWith("https://") //$NON-NLS-1$
- || mirrorsURL.startsWith("file://") //$NON-NLS-1$
- || mirrorsURL.startsWith("ftp://") //$NON-NLS-1$
- || mirrorsURL.startsWith("jar://"))) //$NON-NLS-1$
- log("Error processing mirrors URL: " + mirrorsURL, e); //$NON-NLS-1$
- return null;
- }
- }
-
- /**
- * Returns an equivalent location for the given artifact location in the base
- * repository. Always falls back to the given input location in case of failure
- * to compute mirrors. Never returns null.
- */
- public synchronized URI getMirrorLocation(URI inputLocation, IProgressMonitor monitor) {
- Assert.isNotNull(inputLocation);
- if (baseURI == null)
- return inputLocation;
- URI relativeLocation = baseURI.relativize(inputLocation);
- //if we failed to relativize the location, we can't select a mirror
- if (relativeLocation == null || relativeLocation.isAbsolute())
- return inputLocation;
- MirrorInfo selectedMirror = selectMirror(monitor);
- if (selectedMirror == null)
- return inputLocation;
- if (Tracing.DEBUG_MIRRORS)
- Tracing.debug("Selected mirror for artifact " + inputLocation + ": " + selectedMirror); //$NON-NLS-1$ //$NON-NLS-2$
- try {
- return new URI(selectedMirror.locationString + relativeLocation.getPath());
- } catch (URISyntaxException e) {
- log("Unable to make location " + inputLocation + " relative to mirror " + selectedMirror.locationString, e); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return inputLocation;
- }
-
- /**
- * Returns the mirror locations for this repository, or <code>null</code> if
- * they could not be computed.
- */
- private MirrorInfo[] initMirrors(IProgressMonitor monitor) {
- if (mirrors != null)
- return mirrors;
- String mirrorsURL = repository.getProperties().get(IRepository.PROP_MIRRORS_URL);
- if (mirrorsURL != null)
- mirrors = computeMirrors(mirrorsURL, monitor);
- return mirrors;
- }
-
- private void log(String message, Throwable exception) {
- LogHelper.log(new Status(IStatus.ERROR, Activator.ID, message, exception));
- }
-
- /**
- * Reports the result of a mirror download
- */
- public synchronized void reportResult(String toDownload, IStatus result) {
- if (mirrors == null)
- return;
- for (int i = 0; i < mirrors.length; i++) {
- MirrorInfo mirror = mirrors[i];
- if (toDownload.startsWith(mirror.locationString)) {
- if (!result.isOK() && result.getSeverity() != IStatus.CANCEL) {
- // Punishing a mirror harshly for a FileNotFoundException can be very wrong.
- // Some artifacts are not found on any mirror. When that's the case,
- // the best mirrors will be the first to receive that kind of punishment.
- //
- if (result.getException() instanceof FileNotFoundException)
- mirror.incrementFileNotFoundCount();
- else
- mirror.incrementFailureCount();
- }
- if (result instanceof DownloadStatus) {
- long oldRate = mirror.bytesPerSecond;
- long newRate = ((DownloadStatus) result).getTransferRate();
- //average old and new rate so one slow download doesn't ruin the mirror's reputation
- if (oldRate > 0)
- newRate = (oldRate + newRate) / 2;
- mirror.setBytesPerSecond(newRate);
- }
- if (Tracing.DEBUG_MIRRORS)
- Tracing.debug("Updated mirror " + mirror); //$NON-NLS-1$
- return;
- }
- }
- }
-
- /**
- * Return whether or not all the mirrors for this selector have proven to be invalid
- * @return whether or not there is a valid mirror in this selector.
- */
- public synchronized boolean hasValidMirror() {
- // return true if there is a mirror and it doesn't have multiple failures.
- if (mirrors == null || mirrors.length == 0)
- return false;
- Arrays.sort(mirrors);
- return mirrors[0].failureCount < 2;
- }
-
- /**
- * Selects a mirror from the given list of mirrors. Returns null if a mirror
- * could not be found.
- */
- private MirrorInfo selectMirror(IProgressMonitor monitor) {
- initMirrors(monitor);
- int mirrorCount;
- if (mirrors == null || (mirrorCount = mirrors.length) == 0)
- return null;
-
- MirrorInfo selected;
- if (mirrorCount == 1)
- selected = mirrors[0];
- else {
- Arrays.sort(mirrors);
- for (;;) {
- //this is a function that randomly selects a mirror based on a logarithmic
- //distribution. Mirror 0 has a 1/2 chance of being selected, mirror 1 has a 1/4 chance,
- // mirror 2 has a 1/8 chance, etc. This introduces some variation in the mirror
- //selection, while still heavily favoring better mirrors
- //the algorithm computes the most significant digit in a binary number by computing the base 2 logarithm
- //if the first digit is most significant, mirror 0 is selected, if the second is most significant, mirror 1 is selected, etc
- int highestMirror = Math.min(15, mirrorCount);
- int result = (int) (Math.log(random.nextInt(1 << highestMirror) + 1) / LOG2);
- if (result >= highestMirror || result < 0)
- result = highestMirror - 1;
-
- int mirrorIndex = highestMirror - 1 - result;
- selected = mirrors[mirrorIndex];
-
- // If the ranking of the selected mirror is significantly worse then the top ranked
- // mirror, then we consider this a bad choice and reiterate.
- if (mirrorIndex == 0 || mirrors[0].compareTo(selected) < 4)
- // This is good enough
- break;
- }
- }
-
- //for now, don't tolerate mirrors with multiple failures
- if (selected.failureCount > 1)
- return null;
- return selected;
- }
-
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java
deleted file mode 100644
index 740775e83..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/RawMirrorRequest.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import java.io.OutputStream;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.artifact.processors.md5.MD5Verifier;
-import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository;
-import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep;
-import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStepHandler;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
-import org.eclipse.osgi.util.NLS;
-
-public class RawMirrorRequest extends MirrorRequest {
- protected IArtifactDescriptor sourceDescriptor, targetDescriptor;
-
- public RawMirrorRequest(IArtifactDescriptor sourceDescriptor, IArtifactDescriptor targetDescriptor, IArtifactRepository targetRepository) {
- super(sourceDescriptor.getArtifactKey(), targetRepository, null, null);
- this.sourceDescriptor = sourceDescriptor;
- this.targetDescriptor = targetDescriptor;
- }
-
- public void perform(IArtifactRepository sourceRepository, IProgressMonitor monitor) {
- monitor.subTask(NLS.bind(Messages.downloading, getArtifactKey().getId()));
- setSourceRepository(sourceRepository);
- // Do we already have the descriptor in the target?
- if (target.contains(targetDescriptor)) {
- setResult(new Status(IStatus.INFO, Activator.ID, NLS.bind(Messages.mirror_alreadyExists, targetDescriptor, target)));
- return;
- }
- // Does the source actually have the descriptor?
- if (!source.contains(getArtifactDescriptor())) {
- setResult(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.artifact_not_found, getArtifactKey())));
- return;
- }
- IStatus status = transfer(targetDescriptor, sourceDescriptor, monitor);
-
- // if ok, cancelled or transfer has already been done with the canonical form return with status set
- if (status.getSeverity() == IStatus.CANCEL) {
- setResult(status);
- return;
- }
- if (monitor.isCanceled()) {
- setResult(Status.CANCEL_STATUS);
- return;
- }
- if (status.isOK()) {
- setResult(status);
- return;
- }
-
- // failed, first remove possibly erroneously added descriptor
- if (target.contains(targetDescriptor))
- target.removeDescriptor(targetDescriptor);
-
- setResult(status);
- }
-
- public IArtifactDescriptor getArtifactDescriptor() {
- return sourceDescriptor;
- }
-
- // Perform the mirror operation without any processing steps
- protected IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- ProcessingStepHandler handler = new ProcessingStepHandler();
- if (SimpleArtifactRepository.MD5_CHECK_ENABLED && descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5) != null)
- destination = handler.link(new ProcessingStep[] {new MD5Verifier(descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5))}, destination, monitor);
- return getSourceRepository().getRawArtifact(descriptor, destination, monitor);
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java
deleted file mode 100644
index 2108b52f4..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/SignatureVerifier.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*******************************************************************************
-* Copyright (c) 2007, 2008 compeople AG and others.
-* All rights reserved. This program and the accompanying materials
-* are made available under the terms of the Eclipse Public License v1.0
-* which accompanies this distribution, and is available at
-* http://www.eclipse.org/legal/epl-v10.html
-*
-* Contributors:
-* compeople AG (Stefan Liebig) - initial API and implementation
-* IBM - continuing development
-*******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository;
-
-import java.io.*;
-import java.security.GeneralSecurityException;
-import java.util.ArrayList;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.core.helpers.FileUtils;
-import org.eclipse.equinox.internal.p2.core.helpers.ServiceHelper;
-import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.ProcessingStep;
-import org.eclipse.osgi.signedcontent.*;
-
-/**
- * Processing step validating the signature of the artifact being downloaded
- */
-public class SignatureVerifier extends ProcessingStep {
- private File inputFile;
- private OutputStream tempStream;
-
- public boolean areRequirementsSatisfied() {
- return true;
- }
-
- public void write(int b) throws IOException {
- getOutputStream().write(b);
- }
-
- public void write(byte[] bytes, int off, int len) throws IOException {
- getOutputStream().write(bytes, off, len);
- }
-
- private OutputStream getOutputStream() throws IOException {
- if (tempStream != null)
- return tempStream;
- // store input stream in temporary file
- inputFile = File.createTempFile("signatureFile", ".jar"); //$NON-NLS-1$ //$NON-NLS-2$
- tempStream = new BufferedOutputStream(new FileOutputStream(inputFile));
- return tempStream;
- }
-
- private void verify() throws IOException {
- BufferedInputStream resultStream = null;
- try {
- if (tempStream == null)
- // hmmm, no one wrote to this stream so there is nothing to pass on
- return;
- // Ok, so there is content, close the tempStream
- tempStream.close();
- setStatus(verifyContent());
-
- // now write the content to the final destination
- resultStream = new BufferedInputStream(new FileInputStream(inputFile));
- FileUtils.copyStream(resultStream, true, getDestination(), false);
- resultStream = null;
- } finally {
- if (inputFile != null)
- inputFile.delete();
- if (resultStream != null)
- resultStream.close();
- }
- }
-
- private IStatus verifyContent() throws IOException {
- SignedContentFactory verifierFactory = (SignedContentFactory) ServiceHelper.getService(Activator.getContext(), SignedContentFactory.class.getName());
- SignedContent signedContent;
- try {
- signedContent = verifierFactory.getSignedContent(inputFile);
- } catch (GeneralSecurityException e) {
- return new Status(IStatus.ERROR, Activator.ID, Messages.SignatureVerification_failedRead + inputFile, e);
- }
- ArrayList<IStatus> allStatus = new ArrayList<IStatus>(0);
- SignedContentEntry[] entries = signedContent.getSignedEntries();
- for (int i = 0; i < entries.length; i++)
- try {
- entries[i].verify();
- } catch (InvalidContentException e) {
- allStatus.add(new Status(IStatus.ERROR, Activator.ID, Messages.SignatureVerification_invalidContent + entries[i].getName(), e));
- } catch (OutOfMemoryError e) {
- allStatus.add(new Status(IStatus.ERROR, Activator.ID, Messages.SignatureVerifier_OutOfMemory, e));
- break;
- }
- if (allStatus.size() > 0)
- return new MultiStatus(Activator.ID, IStatus.ERROR, allStatus.toArray(new IStatus[allStatus.size()]), Messages.SignatureVerification_invalidFileContent + inputFile, null);
- return Status.OK_STATUS;
- }
-
- public void close() throws IOException {
- // When we go to close we must have seen all the content we are going to see
- // So before closing, verify and write the result to the destination
- verify();
- super.close();
- }
-
-} \ No newline at end of file
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties
deleted file mode 100644
index 64bf98934..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/messages.properties
+++ /dev/null
@@ -1,54 +0,0 @@
-###############################################################################
-# Copyright (c) 2007, 2009 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-artifact_not_found=Artifact not found: {0}.
-available_already_in=The artifact is already available in the repository {0}.
-no_location=No location for {0}.
-downloading=Downloading {0}
-error_closing_stream=Error closing the output stream for {0} on repository {1}.
-
-io_failedRead=Unable to read repository at {0}.
-io_parseError=Error parsing simple artifact repository.
-io_incompatibleVersion=Simple artifact repository has incompatible version {0}; expected {1}.
-io_invalidLocation=Invalid repository location: {0}.
-mirroring=Mirroring:
-io_failedWrite=Error occurred while writing repository at {0}.
-
-repoFailedWrite=Unable to write to repository: {0}.
-
-repoMan_internalError=Internal error.
-
-SignatureVerification_failedRead=Error reading signed content:
-SignatureVerification_invalidContent=Invalid content:
-SignatureVerification_invalidFileContent=File has invalid content:
-SignatureVerifier_OutOfMemory=Out of memory: Cannot verify signed content.
-
-sar_downloading=Download {0} artifacts
-sar_downloadJobName=Install download
-sar_failedMkdir=Failed to create directory {0}.
-sar_reportStatus=Problems downloading artifact: {0}.
-
-mirror_alreadyExists=Artifact: {0} already exists in repository: {1}.
-
-message_childrenRepos = Messages while trying children repositories.
-
-exception_comparatorNotFound = The Artifact Comparator {0} was not found.
-exception_noComparators = No Artifact Comparators are available.
-MirrorLog_Console_Log=Logging to the console instead.
-MirrorLog_Exception_Occurred=An exception occurred while writing to the log:
-MirrorRequest_multipleDownloadProblems=Multiple problems occurred while downloading.
-
-exception_unsupportedAddToComposite = Cannot add descriptors to a composite repository.
-exception_unsupportedGetOutputStream=Cannot write artifacts to a composite repository.
-exception_unsupportedRemoveFromComposite = Cannot remove descriptors from a composite repository.
-
-exception_unableToCreateParentDir = Unable to create parent directory.
-folder_artifact_not_file_repo=Artifact {0} is a folder but the repository is an archive or remote location.
-retryRequest=Download of {0} failed on repository {1}. Retrying. \ No newline at end of file
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java
deleted file mode 100644
index bf6fed250..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/BlobStore.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.io.*;
-import java.net.URI;
-import java.util.Set;
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.core.runtime.URIUtil;
-
-/**
- * Blob store which maps UUIDs to blobs on disk. The UUID is mapped
- * to a file in the file-system and the blob is the file contents. For scalability,
- * the blobs are split among 255 directories with the names 00 to FF.
- */
-public class BlobStore {
- protected URI store;
-
- protected boolean fileBased;
- /** Limits the range of directories' names. */
- protected byte mask;
-
- //private static short[] randomArray = {213, 231, 37, 85, 211, 29, 161, 175, 187, 3, 147, 246, 170, 30, 202, 183, 242, 47, 254, 189, 25, 248, 193, 2, 119, 133, 125, 12, 76, 213, 219, 79, 69, 133, 202, 80, 150, 190, 157, 190, 80, 190, 219, 150, 169, 117, 95, 10, 77, 214, 233, 70, 5, 188, 44, 91, 165, 149, 177, 93, 17, 112, 4, 41, 230, 148, 188, 107, 213, 31, 52, 60, 111, 246, 226, 121, 129, 197, 144, 248, 92, 133, 96, 116, 104, 67, 74, 144, 185, 141, 96, 34, 182, 90, 36, 217, 28, 205, 107, 52, 201, 14, 8, 1, 27, 216, 60, 35, 251, 194, 7, 156, 32, 5, 145, 29, 96, 61, 110, 145, 50, 56, 235, 239, 170, 138, 17, 211, 56, 98, 101, 126, 27, 57, 211, 144, 206, 207, 179, 111, 160, 50, 243, 69, 106, 118, 155, 159, 28, 57, 11, 175, 43, 173, 96, 181, 99, 169, 171, 156, 246, 243, 30, 198, 251, 81, 77, 92, 160, 235, 215, 187, 23, 71, 58, 247, 127, 56, 118, 132, 79, 188, 42, 188, 158, 121, 255, 65, 154, 118, 172, 217, 4, 47, 105, 204, 135, 27, 43, 90, 9, 31, 59, 115, 193, 28, 55, 101, 9, 117, 211, 112, 61, 55, 23, 235, 51, 104, 123, 138, 76, 148, 115, 119, 81, 54, 39, 46, 149, 191, 79, 16, 222, 69, 219, 136, 148, 181, 77, 250, 101, 223, 140, 194, 141, 44, 195, 217, 31, 223, 207, 149, 245, 115, 243, 183};
- private static byte[] randomArray = {-43, -25, 37, 85, -45, 29, -95, -81, -69, 3, -109, -10, -86, 30, -54, -73, -14, 47, -2, -67, 25, -8, -63, 2, 119, -123, 125, 12, 76, -43, -37, 79, 69, -123, -54, 80, -106, -66, -99, -66, 80, -66, -37, -106, -87, 117, 95, 10, 77, -42, -23, 70, 5, -68, 44, 91, -91, -107, -79, 93, 17, 112, 4, 41, -26, -108, -68, 107, -43, 31, 52, 60, 111, -10, -30, 121, -127, -59, -112, -8, 92, -123, 96, 116, 104, 67, 74, -112, -71, -115, 96, 34, -74, 90, 36, -39, 28, -51, 107, 52, -55, 14, 8, 1, 27, -40, 60, 35, -5, -62, 7, -100, 32, 5, -111, 29, 96, 61, 110, -111, 50, 56, -21, -17, -86, -118, 17, -45, 56, 98, 101, 126, 27, 57, -45, -112, -50, -49, -77, 111, -96, 50, -13, 69, 106, 118, -101, -97, 28, 57, 11, -81, 43, -83, 96, -75, 99, -87, -85, -100, -10, -13, 30,
- -58, -5, 81, 77, 92, -96, -21, -41, -69, 23, 71, 58, -9, 127, 56, 118, -124, 79, -68, 42, -68, -98, 121, -1, 65, -102, 118, -84, -39, 4, 47, 105, -52, -121, 27, 43, 90, 9, 31, 59, 115, -63, 28, 55, 101, 9, 117, -45, 112, 61, 55, 23, -21, 51, 104, 123, -118, 76, -108, 115, 119, 81, 54, 39, 46, -107, -65, 79, 16, -34, 69, -37, -120, -108, -75, 77, -6, 101, -33, -116, -62, -115, 44, -61, -39, 31, -33, -49, -107, -11, 115, -13, -73,};
-
- /**
- * The limit is the maximum number of directories managed by this store.
- * This number must be power of 2 and do not exceed 256. The location
- * should be an existing valid directory.
- */
- public BlobStore(URI store, int limit) {
- Assert.isNotNull(store);
- this.store = store;
- fileBased = "file".equalsIgnoreCase(store.getScheme()); //$NON-NLS-1$
- if (fileBased)
- Assert.isTrue(!URIUtil.toFile(store).isFile());
- Assert.isTrue(limit == 256 || limit == 128 || limit == 64 || limit == 32 || limit == 16 || limit == 8 || limit == 4 || limit == 2 || limit == 1);
- mask = (byte) (limit - 1);
- }
-
- public OutputStream getOutputStream(byte[] uuid) throws IOException {
- if (!fileBased)
- return null;
- new File(folderFor(uuid)).mkdir();
- return new FileOutputStream(URIUtil.toFile(fileFor(uuid)));
- }
-
- /* (non-Javadoc)
- * @see UniversalUniqueIdentifier#appendByteString(StringBuffer, byte)
- */
- private void appendByteString(StringBuffer buffer, byte value) {
- String hexString;
- if (value < 0)
- hexString = Integer.toHexString(256 + value);
- else
- hexString = Integer.toHexString(value);
- if (hexString.length() == 1)
- buffer.append("0"); //$NON-NLS-1$
- buffer.append(hexString);
- }
-
- /* (non-Javadoc)
- * Converts an array of bytes into a String.
- *
- * @see UniversalUniqueIdentifier#toString()
- */
- private String bytesToHexString(byte[] b) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < b.length; i++)
- appendByteString(buffer, b[i]);
- return buffer.toString();
- }
-
- /**
- * Deletes a blobFile.
- */
- public void deleteBlob(byte[] uuid) {
- Assert.isNotNull(uuid);
- if (fileBased)
- new File(fileFor(uuid)).delete();
- }
-
- /**
- * Delete all of the blobs in the given set.
- */
- public void deleteBlobs(Set<byte[]> set) {
- for (byte[] blob : set)
- deleteBlob(blob);
- }
-
- public URI fileFor(byte[] uuid) {
- return URIUtil.append(folderFor(uuid), bytesToHexString(uuid));
- }
-
- /**
- * Find out the name of the directory that fits better to this UUID.
- */
- public URI folderFor(byte[] uuid) {
- byte hash = hashUUIDbytes(uuid);
- hash &= mask; // limit the range of the directory
- return URIUtil.append(store, Integer.toHexString(hash + (128 & mask)) + '/'); // +(128 & mask) makes sure 00h is the lower value
- }
-
- public InputStream getBlob(byte[] uuid) throws IOException {
- return URIUtil.toURL(fileFor(uuid)).openStream();
- }
-
- /**
- * Converts a byte array into a byte hash representation. It is used to
- * get a directory name.
- */
- protected byte hashUUIDbytes(byte[] uuid) {
- byte hash = 0;
- for (int i = 0; i < uuid.length; i++)
- hash ^= randomArray[uuid[i] + 128]; // +128 makes sure the index is >0
- return hash;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java
deleted file mode 100644
index 20373a7b6..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/DownloadJob.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 Genuitec, LLC and others. All rights reserved. This
- * program and the accompanying materials are made available under the terms of
- * the Eclipse Public License v1.0 which accompanies this distribution, and is
- * available at http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: Genuitec, LLC - initial API and implementation
- * IBM Corporation - ongoing maintenance
- ******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.util.LinkedList;
-import org.eclipse.core.runtime.*;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRequest;
-
-public class DownloadJob extends Job {
- static final Object FAMILY = new Object();
-
- private LinkedList<IArtifactRequest> requestsPending;
- private SimpleArtifactRepository repository;
- private IProgressMonitor masterMonitor;
- private MultiStatus overallStatus;
-
- DownloadJob(String name) {
- super(name);
- setSystem(true);
- }
-
- void initialize(SimpleArtifactRepository repository, LinkedList<IArtifactRequest> requestsPending, IProgressMonitor masterMonitor, MultiStatus overallStatus) {
- this.repository = repository;
- this.requestsPending = requestsPending;
- this.masterMonitor = masterMonitor;
- this.overallStatus = overallStatus;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object)
- */
- public boolean belongsTo(Object family) {
- return family == FAMILY;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime.IProgressMonitor)
- */
- protected IStatus run(IProgressMonitor jobMonitor) {
- jobMonitor.beginTask("Downloading software", IProgressMonitor.UNKNOWN);
- do {
- // get the request we are going to process
- IArtifactRequest request;
- synchronized (requestsPending) {
- if (requestsPending.isEmpty())
- break;
- request = requestsPending.removeFirst();
- }
- if (masterMonitor.isCanceled())
- return Status.CANCEL_STATUS;
- // process the actual request
- SubProgressMonitor subMonitor = new SubProgressMonitor(masterMonitor, 1);
- subMonitor.beginTask("", 1); //$NON-NLS-1$
- try {
- IStatus status = repository.getArtifact(request, subMonitor);
- if (!status.isOK()) {
- synchronized (overallStatus) {
- overallStatus.add(status);
- }
- }
- } finally {
- subMonitor.done();
- }
- } while (true);
-
- jobMonitor.done();
- return Status.OK_STATUS;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/KeyIndex.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/KeyIndex.java
deleted file mode 100644
index 445543289..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/KeyIndex.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2010 Cloudsmith Inc. and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Cloudsmith Inc. - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.util.*;
-import org.eclipse.equinox.internal.p2.core.helpers.CollectionUtils;
-import org.eclipse.equinox.internal.p2.metadata.ArtifactKey;
-import org.eclipse.equinox.internal.p2.metadata.index.Index;
-import org.eclipse.equinox.p2.metadata.IArtifactKey;
-import org.eclipse.equinox.p2.metadata.expression.IEvaluationContext;
-import org.eclipse.equinox.p2.metadata.expression.IExpression;
-
-/**
- * An index that maps id to IArtifactKey
- */
-public class KeyIndex extends Index<IArtifactKey> {
- // Memory conserving map. Stores either String -> IArtifactKey
- // or String -> IArtifactKey[]
- // A stored array is always length >= 2.
- private final Map<String, Object> artifactMap;
-
- public KeyIndex(Collection<IArtifactKey> artifactKeys) {
- artifactMap = new HashMap<String, Object>(artifactKeys.size());
- for (IArtifactKey ak : artifactKeys) {
- Object prev = artifactMap.put(ak.getId(), ak);
- if (prev != null) {
- if (prev instanceof IArtifactKey)
- artifactMap.put(ak.getId(), new IArtifactKey[] {(IArtifactKey) prev, ak});
- else {
- IArtifactKey[] prevArr = (IArtifactKey[]) prev;
- IArtifactKey[] nxtArr = new IArtifactKey[prevArr.length + 1];
- System.arraycopy(prevArr, 0, nxtArr, 0, prevArr.length);
- nxtArr[prevArr.length] = ak;
- artifactMap.put(ak.getId(), nxtArr);
- }
- }
- }
- }
-
- public Iterator<IArtifactKey> getCandidates(IEvaluationContext ctx, IExpression variable, IExpression booleanExpr) {
- Object queriedKeys = getQueriedIDs(ctx, variable, ArtifactKey.MEMBER_ID, booleanExpr, null);
- if (queriedKeys == null)
- return null;
-
- Collection<IArtifactKey> collector = null;
- if (queriedKeys.getClass().isArray()) {
- Object[] keyArr = (Object[]) queriedKeys;
- int idx = keyArr.length;
- while (--idx >= 0) {
- Object v = artifactMap.get(keyArr[idx]);
- if (v == null)
- continue;
- if (collector == null)
- collector = new ArrayList<IArtifactKey>();
- if (v instanceof IArtifactKey)
- collector.add((IArtifactKey) v);
- else {
- IArtifactKey[] akArr = (IArtifactKey[]) v;
- for (IArtifactKey ak : akArr)
- collector.add(ak);
- }
- }
- if (collector == null)
- collector = CollectionUtils.emptySet();
- } else {
- Object v = artifactMap.get(queriedKeys);
- if (v == null)
- collector = CollectionUtils.emptySet();
- else if (v instanceof IArtifactKey)
- collector = Collections.singleton((IArtifactKey) v);
- else
- collector = CollectionUtils.unmodifiableList((IArtifactKey[]) v);
- }
- return collector.iterator();
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java
deleted file mode 100644
index 80b6b3e44..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/Mapper.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * compeople AG (Stefan Liebig) - various ongoing maintenance
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Dictionary;
-import java.util.Hashtable;
-import org.eclipse.core.runtime.URIUtil;
-import org.osgi.framework.*;
-
-public class Mapper {
- private Filter[] filters;
- private String[] outputStrings;
-
- private static final String REPOURL = "repoUrl"; //$NON-NLS-1$
- private static final String CLASSIFIER = "classifier"; //$NON-NLS-1$
- private static final String FORMAT = "format"; //$NON-NLS-1$
- private static final String ID = "id"; //$NON-NLS-1$
- private static final String VERSION = "version"; //$NON-NLS-1$
-
- public Mapper() {
- filters = new Filter[0];
- outputStrings = new String[0];
- }
-
- /**
- * mapping rule: LDAP filter --> output value
- * the more specific filters should be given first.
- */
- public void initialize(BundleContext ctx, String[][] mappingRules) {
- filters = new Filter[mappingRules.length];
- outputStrings = new String[mappingRules.length];
- for (int i = 0; i < mappingRules.length; i++) {
- try {
- filters[i] = ctx.createFilter(mappingRules[i][0]);
- outputStrings[i] = mappingRules[i][1];
- } catch (InvalidSyntaxException e) {
- //TODO Neeed to process this
- e.printStackTrace();
- }
- }
- }
-
- public URI map(URI repositoryLocation, String classifier, String id, String version, String format) {
- String locationString = URIUtil.toUnencodedString(repositoryLocation);
- Dictionary<String, Object> values = new Hashtable<String, Object>(5);
- if (repositoryLocation != null)
- values.put(REPOURL, locationString);
-
- if (classifier != null)
- values.put(CLASSIFIER, classifier);
-
- if (id != null)
- values.put(ID, id);
-
- if (version != null)
- values.put(VERSION, version);
-
- if (format != null)
- values.put(FORMAT, format);
-
- for (int i = 0; i < filters.length; i++) {
- if (filters[i].match(values))
- return doReplacement(outputStrings[i], locationString, classifier, id, version, format);
- }
- return null;
- }
-
- private URI doReplacement(String pattern, String repoLocation, String classifier, String id, String version, String format) {
- try {
- // currently our mapping rules assume the repo URL is not "/" terminated.
- // This may be the case for repoURLs in the root of a URL space e.g. root of a jar file or file:/c:/
- if (repoLocation.endsWith("/")) //$NON-NLS-1$
- repoLocation = repoLocation.substring(0, repoLocation.length() - 1);
-
- StringBuffer output = new StringBuffer(pattern);
- int index = 0;
- while (index < output.length()) {
- int beginning = output.indexOf("${", index); //$NON-NLS-1$
- if (beginning == -1)
- return URIUtil.fromString(output.toString());
-
- int end = output.indexOf("}", beginning); //$NON-NLS-1$
- if (end == -1)
- return URIUtil.fromString(pattern);
-
- String varName = output.substring(beginning + 2, end);
- String varValue = null;
- if (varName.equalsIgnoreCase(CLASSIFIER)) {
- varValue = classifier;
- } else if (varName.equalsIgnoreCase(ID)) {
- varValue = id;
- } else if (varName.equalsIgnoreCase(VERSION)) {
- varValue = version;
- } else if (varName.equalsIgnoreCase(REPOURL)) {
- varValue = repoLocation;
- } else if (varName.equalsIgnoreCase(FORMAT)) {
- varValue = format;
- }
- if (varValue == null)
- varValue = ""; //$NON-NLS-1$
-
- output.replace(beginning, end + 1, varValue);
- index = beginning + varValue.length();
- }
- return URIUtil.fromString(output.toString());
- } catch (URISyntaxException e) {
- return null;
- }
- }
-
- public String toString() {
- StringBuffer result = new StringBuffer();
- for (int i = 0; i < filters.length; i++) {
- result.append(filters[i]).append('-').append('>').append(outputStrings[i]).append('\n');
- }
- return result.toString();
- }
-
- public String[][] serialize() {
- String[][] result = new String[filters.length][2];
- for (int i = 0; i < filters.length; i++) {
- result[i][0] = filters[i].toString();
- result[i][1] = outputStrings[i];
- }
- return result;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java
deleted file mode 100644
index baa18869b..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactDescriptor.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.util.Map;
-import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties;
-import org.eclipse.equinox.p2.metadata.IArtifactKey;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor;
-
-public class SimpleArtifactDescriptor extends ArtifactDescriptor {
- public static final String ARTIFACT_REFERENCE = "artifact.reference"; //$NON-NLS-1$
-
- protected Map<String, String> repositoryProperties = new OrderedProperties();
-
- public SimpleArtifactDescriptor(IArtifactKey key) {
- super(key);
- }
-
- public SimpleArtifactDescriptor(IArtifactDescriptor base) {
- super(base);
- }
-
- public String getRepositoryProperty(String propertyKey) {
- return repositoryProperties.get(propertyKey);
- }
-
- public void setRepositoryProperty(String key, String value) {
- if (value == null)
- repositoryProperties.remove(key);
- else
- repositoryProperties.put(key, value);
- }
-
- public void addRepositoryProperties(Map<String, String> additionalProperties) {
- repositoryProperties.putAll(additionalProperties);
- }
-
- /**
- * Returns a read-only collection of the repository properties of the artifact descriptor.
- * @return the repository properties of this artifact descriptor.
- */
- public Map<String, String> getRepositoryProperties() {
- return OrderedProperties.unmodifiableProperties(repositoryProperties);
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null || !(obj instanceof SimpleArtifactDescriptor))
- return false;
-
- SimpleArtifactDescriptor other = (SimpleArtifactDescriptor) obj;
-
- //Properties affecting SimpleArtifactRepository#getLocation
- String locationProperty = getRepositoryProperty(ARTIFACT_REFERENCE);
- String otherProperty = other.getRepositoryProperty(ARTIFACT_REFERENCE);
- // want not null and the same, or both null
- if (locationProperty != null ? !locationProperty.equals(otherProperty) : otherProperty != null)
- return false;
-
- return super.equals(obj);
- }
-
- public int hashCode() {
- int superHash = super.hashCode();
- String ref = getRepositoryProperty(ARTIFACT_REFERENCE);
- if (ref != null)
- return 31 * superHash + ref.hashCode();
- return superHash;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java
deleted file mode 100644
index 343ec0a44..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepository.java
+++ /dev/null
@@ -1,1069 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Genuitec, LLC - support for multi-threaded downloads
- * Cloudsmith Inc. - query indexes
- * Sonatype Inc - ongoing development
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.io.*;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import org.eclipse.core.runtime.*;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.equinox.internal.p2.artifact.processors.md5.MD5Verifier;
-import org.eclipse.equinox.internal.p2.artifact.repository.*;
-import org.eclipse.equinox.internal.p2.artifact.repository.Messages;
-import org.eclipse.equinox.internal.p2.core.helpers.FileUtils;
-import org.eclipse.equinox.internal.p2.metadata.ArtifactKey;
-import org.eclipse.equinox.internal.p2.metadata.expression.CompoundIterator;
-import org.eclipse.equinox.internal.p2.metadata.index.IndexProvider;
-import org.eclipse.equinox.internal.p2.repository.RepositoryTransport;
-import org.eclipse.equinox.internal.p2.repository.Transport;
-import org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.*;
-import org.eclipse.equinox.internal.provisional.p2.repository.IStateful;
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.core.ProvisionException;
-import org.eclipse.equinox.p2.metadata.IArtifactKey;
-import org.eclipse.equinox.p2.metadata.index.IIndex;
-import org.eclipse.equinox.p2.metadata.index.IIndexProvider;
-import org.eclipse.equinox.p2.query.*;
-import org.eclipse.equinox.p2.repository.IRepository;
-import org.eclipse.equinox.p2.repository.IRunnableWithProgress;
-import org.eclipse.equinox.p2.repository.artifact.*;
-import org.eclipse.equinox.p2.repository.artifact.spi.AbstractArtifactRepository;
-import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactDescriptor;
-import org.eclipse.osgi.util.NLS;
-
-public class SimpleArtifactRepository extends AbstractArtifactRepository implements IFileArtifactRepository, IIndexProvider<IArtifactKey> {
- /**
- * A boolean property controlling whether mirroring is enabled.
- */
- public static final boolean MIRRORS_ENABLED = !"false".equals(Activator.getContext().getProperty("eclipse.p2.mirrors")); //$NON-NLS-1$//$NON-NLS-2$
-
- public static final boolean MD5_CHECK_ENABLED = !"false".equals(Activator.getContext().getProperty("eclipse.p2.MD5Check")); //$NON-NLS-1$//$NON-NLS-2$
-
- public static final String CONTENT_FILENAME = "artifacts"; //$NON-NLS-1$
-
- /**
- * The key for a integer property controls the maximum number
- * of threads that should be used when optimizing downloads from a remote
- * artifact repository.
- */
- public static final String PROP_MAX_THREADS = "eclipse.p2.max.threads"; //$NON-NLS-1$
-
- /**
- * Allows override of whether threading should be used.
- */
- public static final String PROP_FORCE_THREADING = "eclipse.p2.force.threading"; //$NON-NLS-1$
-
- public class ArtifactOutputStream extends OutputStream implements IStateful {
- private boolean closed;
- private long count = 0;
- private IArtifactDescriptor descriptor;
- private OutputStream destination;
- private File file;
- private IStatus status = Status.OK_STATUS;
- private OutputStream firstLink;
-
- public ArtifactOutputStream(OutputStream os, IArtifactDescriptor descriptor) {
- this(os, descriptor, null);
- }
-
- public ArtifactOutputStream(OutputStream os, IArtifactDescriptor descriptor, File file) {
- this.destination = os;
- this.descriptor = descriptor;
- this.file = file;
- }
-
- public void close() throws IOException {
- if (closed)
- return;
- closed = true;
-
- try {
- destination.close();
- } catch (IOException e) {
- // cleanup if possible
- if (file != null)
- delete(file);
- if (getStatus().isOK())
- throw e;
- // if the stream has already been e.g. canceled, we can return - the status is already set correctly
- return;
- }
- // if the steps ran ok and there was actual content, write the artifact descriptor
- // TODO the count check is a bit bogus but helps in some error cases (e.g., the optimizer)
- // where errors occurred in a processing step earlier in the chain. We likely need a better
- // or more explicit way of handling this case.
- OutputStream testStream = firstLink == null ? this : firstLink;
- if (ProcessingStepHandler.checkStatus(testStream).isOK() && count > 0) {
- ((ArtifactDescriptor) descriptor).setProperty(IArtifactDescriptor.DOWNLOAD_SIZE, Long.toString(count));
- addDescriptor(descriptor);
- } else if (file != null)
- // cleanup if possible
- delete(file);
- }
-
- public IStatus getStatus() {
- return status;
- }
-
- public OutputStream getDestination() {
- return destination;
- }
-
- public void setStatus(IStatus status) {
- this.status = status == null ? Status.OK_STATUS : status;
- }
-
- public void write(byte[] b) throws IOException {
- destination.write(b);
- count += b.length;
- }
-
- public void write(byte[] b, int off, int len) throws IOException {
- destination.write(b, off, len);
- count += len;
- }
-
- public void write(int b) throws IOException {
- destination.write(b);
- count++;
- }
-
- public void setFirstLink(OutputStream value) {
- firstLink = value;
- }
- }
-
- // TODO: optimize
- // we could stream right into the folder
- public static class ZippedFolderOutputStream extends OutputStream {
-
- private final File folder;
- private final FileOutputStream fos;
- private final File zipFile;
-
- public ZippedFolderOutputStream(File folder) throws IOException {
- this.folder = folder;
- zipFile = File.createTempFile(folder.getName(), JAR_EXTENSION, null);
- fos = new FileOutputStream(zipFile);
- }
-
- public void close() throws IOException {
- fos.close();
- try {
- FileUtils.unzipFile(zipFile, folder);
- } finally {
- zipFile.delete();
- }
- }
-
- public void flush() throws IOException {
- fos.flush();
- }
-
- public String toString() {
- return fos.toString();
- }
-
- public void write(byte[] b) throws IOException {
- fos.write(b);
- }
-
- public void write(byte[] b, int off, int len) throws IOException {
- fos.write(b, off, len);
- }
-
- public void write(int b) throws IOException {
- fos.write(b);
- }
- }
-
- private static final String ARTIFACT_FOLDER = "artifact.folder"; //$NON-NLS-1$
- private static final String ARTIFACT_UUID = "artifact.uuid"; //$NON-NLS-1$
- static final private String BLOBSTORE = ".blobstore/"; //$NON-NLS-1$
- static final private String[][] PACKED_MAPPING_RULES = { {"(& (classifier=osgi.bundle) (format=packed))", "${repoUrl}/plugins/${id}_${version}.jar.pack.gz"}, //$NON-NLS-1$//$NON-NLS-2$
- {"(& (classifier=osgi.bundle))", "${repoUrl}/plugins/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$
- {"(& (classifier=binary))", "${repoUrl}/binary/${id}_${version}"}, //$NON-NLS-1$ //$NON-NLS-2$
- {"(& (classifier=org.eclipse.update.feature) (format=packed))", "${repoUrl}/features/${id}_${version}.jar.pack.gz"}, //$NON-NLS-1$//$NON-NLS-2$
- {"(& (classifier=org.eclipse.update.feature))", "${repoUrl}/features/${id}_${version}.jar"}}; //$NON-NLS-1$//$NON-NLS-2$
-
- static final private String[][] DEFAULT_MAPPING_RULES = { {"(& (classifier=osgi.bundle))", "${repoUrl}/plugins/${id}_${version}.jar"}, //$NON-NLS-1$//$NON-NLS-2$
- {"(& (classifier=binary))", "${repoUrl}/binary/${id}_${version}"}, //$NON-NLS-1$ //$NON-NLS-2$
- {"(& (classifier=org.eclipse.update.feature))", "${repoUrl}/features/${id}_${version}.jar"}}; //$NON-NLS-1$//$NON-NLS-2$
- private static final String JAR_EXTENSION = ".jar"; //$NON-NLS-1$
- static final private String REPOSITORY_TYPE = IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY;
-
- static final private Integer REPOSITORY_VERSION = new Integer(1);
- private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$
- protected Set<SimpleArtifactDescriptor> artifactDescriptors = new HashSet<SimpleArtifactDescriptor>();
- /**
- * Map<IArtifactKey,List<IArtifactDescriptor>> containing the index of artifacts in the repository.
- */
- private Map<IArtifactKey, List<IArtifactDescriptor>> artifactMap = new HashMap<IArtifactKey, List<IArtifactDescriptor>>();
- private transient BlobStore blobStore;
- transient private Mapper mapper = new Mapper();
- private KeyIndex keyIndex;
- private boolean snapshotNeeded = false;
-
- static final private String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$
-
- private static final int DEFAULT_MAX_THREADS = 4;
-
- protected String[][] mappingRules = DEFAULT_MAPPING_RULES;
-
- private MirrorSelector mirrors;
-
- private boolean disableSave = false;
-
- static void delete(File toDelete) {
- if (toDelete.isDirectory()) {
- File[] children = toDelete.listFiles();
- if (children != null) {
- for (int i = 0; i < children.length; i++) {
- delete(children[i]);
- }
- }
- }
- toDelete.delete();
- }
-
- public static URI getActualLocation(URI base, boolean compress) {
- return getActualLocation(base, compress ? JAR_EXTENSION : XML_EXTENSION);
- }
-
- private static URI getActualLocation(URI base, String extension) {
- return URIUtil.append(base, CONTENT_FILENAME + extension);
- }
-
- public static URI getBlobStoreLocation(URI base) {
- return URIUtil.append(base, BLOBSTORE);
- }
-
- /*
- * This is only called by the parser when loading a repository.
- */
- SimpleArtifactRepository(IProvisioningAgent agent, String name, String type, String version, String description, String provider, Set<SimpleArtifactDescriptor> artifacts, String[][] mappingRules, Map<String, String> properties) {
- super(agent, name, type, version, null, description, provider, properties);
- this.artifactDescriptors.addAll(artifacts);
- this.mappingRules = mappingRules;
- for (SimpleArtifactDescriptor desc : artifactDescriptors)
- mapDescriptor(desc);
- }
-
- private synchronized void mapDescriptor(IArtifactDescriptor descriptor) {
- IArtifactKey key = descriptor.getArtifactKey();
- if (snapshotNeeded) {
- cloneAritfactMap();
- snapshotNeeded = false;
- }
- List<IArtifactDescriptor> descriptors = artifactMap.get(key);
- if (descriptors == null) {
- descriptors = new ArrayList<IArtifactDescriptor>();
- artifactMap.put(key, descriptors);
- }
- descriptors.add(descriptor);
- keyIndex = null;
- }
-
- private synchronized void unmapDescriptor(IArtifactDescriptor descriptor) {
- IArtifactKey key = descriptor.getArtifactKey();
- List<IArtifactDescriptor> descriptors = artifactMap.get(key);
- if (descriptors == null)
- return;
-
- if (snapshotNeeded) {
- cloneAritfactMap();
- snapshotNeeded = false;
- descriptors = artifactMap.get(key);
- }
- descriptors.remove(descriptor);
- if (descriptors.isEmpty())
- artifactMap.remove(key);
- keyIndex = null;
- }
-
- private void cloneAritfactMap() {
- HashMap<IArtifactKey, List<IArtifactDescriptor>> clone = new HashMap<IArtifactKey, List<IArtifactDescriptor>>(artifactMap.size());
- for (Entry<IArtifactKey, List<IArtifactDescriptor>> entry : artifactMap.entrySet())
- clone.put(entry.getKey(), new ArrayList<IArtifactDescriptor>(entry.getValue()));
- artifactMap = clone;
- }
-
- public SimpleArtifactRepository(IProvisioningAgent agent, String repositoryName, URI location, Map<String, String> properties) {
- super(agent, repositoryName, REPOSITORY_TYPE, REPOSITORY_VERSION.toString(), location, null, null, properties);
- initializeAfterLoad(location);
- if (properties != null) {
- if (properties.containsKey(PUBLISH_PACK_FILES_AS_SIBLINGS)) {
- synchronized (this) {
- String newValue = properties.get(PUBLISH_PACK_FILES_AS_SIBLINGS);
- if (Boolean.TRUE.toString().equals(newValue)) {
- mappingRules = PACKED_MAPPING_RULES;
- } else {
- mappingRules = DEFAULT_MAPPING_RULES;
- }
- initializeMapper();
- }
- }
- }
- save();
- }
-
- public synchronized void addDescriptor(IArtifactDescriptor toAdd) {
- if (artifactDescriptors.contains(toAdd))
- return;
-
- SimpleArtifactDescriptor internalDescriptor = createInternalDescriptor(toAdd);
- artifactDescriptors.add(internalDescriptor);
- mapDescriptor(internalDescriptor);
- save();
- }
-
- public IArtifactDescriptor createArtifactDescriptor(IArtifactKey key) {
- return new SimpleArtifactDescriptor(key);
- }
-
- private SimpleArtifactDescriptor createInternalDescriptor(IArtifactDescriptor descriptor) {
- SimpleArtifactDescriptor internal = new SimpleArtifactDescriptor(descriptor);
-
- internal.setRepository(this);
- if (isFolderBased(descriptor))
- internal.setRepositoryProperty(ARTIFACT_FOLDER, Boolean.TRUE.toString());
-
- //clear out the UUID if we aren't using the blobstore.
- if (flatButPackedEnabled(descriptor) && internal.getProperty(ARTIFACT_UUID) != null) {
- internal.setProperty(ARTIFACT_UUID, null);
- }
-
- if (descriptor instanceof SimpleArtifactDescriptor) {
- Map<String, String> repoProperties = ((SimpleArtifactDescriptor) descriptor).getRepositoryProperties();
- for (Map.Entry<String, String> entry : repoProperties.entrySet()) {
- internal.setRepositoryProperty(entry.getKey(), entry.getValue());
- }
- }
- return internal;
- }
-
- public synchronized void addDescriptors(IArtifactDescriptor[] descriptors) {
- for (int i = 0; i < descriptors.length; i++) {
- if (artifactDescriptors.contains(descriptors[i]))
- continue;
- SimpleArtifactDescriptor internalDescriptor = createInternalDescriptor(descriptors[i]);
- artifactDescriptors.add(internalDescriptor);
- mapDescriptor(internalDescriptor);
- }
- save();
- }
-
- private synchronized OutputStream addPostSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- ArrayList<ProcessingStep> steps = new ArrayList<ProcessingStep>();
- steps.add(new SignatureVerifier());
- if (steps.isEmpty())
- return destination;
- ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]);
- // TODO should probably be using createAndLink here
- return handler.link(stepArray, destination, monitor);
- }
-
- private OutputStream addPreSteps(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- ArrayList<ProcessingStep> steps = new ArrayList<ProcessingStep>();
- if (IArtifactDescriptor.TYPE_ZIP.equals(descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_CONTENTTYPE)))
- steps.add(new ZipVerifierStep());
- if (MD5_CHECK_ENABLED && descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5) != null)
- steps.add(new MD5Verifier(descriptor.getProperty(IArtifactDescriptor.DOWNLOAD_MD5)));
- // Add steps here if needed
- if (steps.isEmpty())
- return destination;
- ProcessingStep[] stepArray = steps.toArray(new ProcessingStep[steps.size()]);
- // TODO should probably be using createAndLink here
- return handler.link(stepArray, destination, monitor);
- }
-
- private byte[] bytesFromHexString(String string) {
- byte[] bytes = new byte[UniversalUniqueIdentifier.BYTES_SIZE];
- for (int i = 0; i < string.length(); i += 2) {
- String byteString = string.substring(i, i + 2);
- bytes[i / 2] = (byte) Integer.parseInt(byteString, 16);
- }
- return bytes;
- }
-
- private String bytesToHexString(byte[] bytes) {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < bytes.length; i++) {
- String hexString;
- if (bytes[i] < 0)
- hexString = Integer.toHexString(256 + bytes[i]);
- else
- hexString = Integer.toHexString(bytes[i]);
- if (hexString.length() == 1)
- buffer.append("0"); //$NON-NLS-1$
- buffer.append(hexString);
- }
- return buffer.toString();
- }
-
- public synchronized boolean contains(IArtifactDescriptor descriptor) {
- SimpleArtifactDescriptor simpleDescriptor = createInternalDescriptor(descriptor);
- return artifactDescriptors.contains(simpleDescriptor);
- }
-
- public synchronized boolean contains(IArtifactKey key) {
- return artifactMap.containsKey(key);
- }
-
- public synchronized URI createLocation(ArtifactDescriptor descriptor) {
- if (flatButPackedEnabled(descriptor)) {
- return getLocationForPackedButFlatArtifacts(descriptor);
- }
- // if the descriptor is canonical, clear out any UUID that might be set and use the Mapper
- if (descriptor.getProcessingSteps().length == 0) {
- descriptor.setProperty(ARTIFACT_UUID, null);
- IArtifactKey key = descriptor.getArtifactKey();
- URI result = mapper.map(getLocation(), key.getClassifier(), key.getId(), key.getVersion().toString(), descriptor.getProperty(IArtifactDescriptor.FORMAT));
- if (result != null) {
- if (isFolderBased(descriptor) && URIUtil.lastSegment(result).endsWith(JAR_EXTENSION)) {
- return URIUtil.removeFileExtension(result);
- }
- return result;
- }
- }
-
- // Otherwise generate a location by creating a UUID, remembering it in the properties
- // and computing the location
- byte[] bytes = new UniversalUniqueIdentifier().toBytes();
- descriptor.setProperty(ARTIFACT_UUID, bytesToHexString(bytes));
- return blobStore.fileFor(bytes);
- }
-
- /**
- * Removes the given descriptor, and the physical artifact corresponding
- * to that descriptor. Returns <code>true</code> if and only if the
- * descriptor existed in the repository, and was successfully removed.
- */
- private boolean doRemoveArtifact(IArtifactDescriptor descriptor) {
- SimpleArtifactDescriptor simple = null;
- if (descriptor instanceof SimpleArtifactDescriptor)
- simple = (SimpleArtifactDescriptor) descriptor;
- else
- simple = createInternalDescriptor(descriptor);
- if (simple.getRepositoryProperty(SimpleArtifactDescriptor.ARTIFACT_REFERENCE) == null) {
- File file = getArtifactFile(descriptor);
- if (file != null) {
- // If the file != null remove it, otherwise just remove
- // the descriptor
- delete(file);
- if (file.exists())
- return false;
- }
- }
- boolean result = artifactDescriptors.remove(descriptor);
- if (result)
- unmapDescriptor(descriptor);
-
- return result;
- }
-
- protected IStatus downloadArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- if (isFolderBased(descriptor)) {
- File artifactFolder = getArtifactFile(descriptor);
- if (artifactFolder == null) {
- if (getLocation(descriptor) != null && !URIUtil.isFileURI(getLocation(descriptor)))
- return reportStatus(descriptor, destination, new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.folder_artifact_not_file_repo, descriptor.getArtifactKey())));
- return reportStatus(descriptor, destination, new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.artifact_not_found, descriptor.getArtifactKey())));
- }
- // TODO: optimize and ensure manifest is written first
- File zipFile = null;
- try {
- zipFile = File.createTempFile(artifactFolder.getName(), JAR_EXTENSION, null);
- FileUtils.zip(artifactFolder.listFiles(), null, zipFile, FileUtils.createRootPathComputer(artifactFolder));
- FileInputStream fis = new FileInputStream(zipFile);
- FileUtils.copyStream(fis, true, destination, false);
- } catch (IOException e) {
- return reportStatus(descriptor, destination, new Status(IStatus.ERROR, Activator.ID, e.getMessage()));
- } finally {
- if (zipFile != null)
- zipFile.delete();
- }
- return reportStatus(descriptor, destination, Status.OK_STATUS);
- }
-
- //download from the best available mirror
- URI baseLocation = getLocation(descriptor);
- if (baseLocation == null)
- return new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.no_location, descriptor));
- URI mirrorLocation = getMirror(baseLocation, monitor);
- IStatus status = downloadArtifact(descriptor, mirrorLocation, destination, monitor);
- IStatus result = reportStatus(descriptor, destination, status);
- // if the original download went reasonably but the reportStatus found some issues
- // (e..g, in the processing steps/validators) then mark the mirror as bad and return
- // a retry code (assuming we have more mirrors)
- if ((status.isOK() || status.matches(IStatus.INFO | IStatus.WARNING)) && result.getSeverity() == IStatus.ERROR) {
- if (mirrors != null) {
- mirrors.reportResult(mirrorLocation.toString(), result);
- if (mirrors.hasValidMirror())
- return new MultiStatus(Activator.ID, CODE_RETRY, new IStatus[] {result}, "Retry another mirror", null); //$NON-NLS-1$
- }
- }
- // if the original status was a retry, don't lose that.
- return status.getCode() == CODE_RETRY ? status : result;
- }
-
- private IStatus downloadArtifact(IArtifactDescriptor descriptor, URI mirrorLocation, OutputStream destination, IProgressMonitor monitor) {
- IStatus result = getTransport().download(mirrorLocation, destination, monitor);
- if (mirrors != null)
- mirrors.reportResult(mirrorLocation.toString(), result);
- if (result.isOK() || result.getSeverity() == IStatus.CANCEL)
- return result;
- if (monitor.isCanceled())
- return Status.CANCEL_STATUS;
- // If there are more valid mirrors then return an error with a special code that tells the caller
- // to keep trying. Note that the message in the status is largely irrelevant but the child
- // status tells the story of why we failed on this try.
- // TODO find a better way of doing this.
- if (mirrors != null && mirrors.hasValidMirror())
- return new MultiStatus(Activator.ID, CODE_RETRY, new IStatus[] {result}, "Retry another mirror", null); //$NON-NLS-1$
- return result;
- }
-
- /**
- * Returns an equivalent mirror location for the given artifact location.
- * @param baseLocation The location of the artifact in this repository
- * @return the Location of the artifact in this repository, or an equivalent mirror
- */
- private synchronized URI getMirror(URI baseLocation, IProgressMonitor monitor) {
- if (!MIRRORS_ENABLED || (!isForceThreading() && isLocal()))
- return baseLocation;
- if (mirrors == null)
- mirrors = new MirrorSelector(this);
- return mirrors.getMirrorLocation(baseLocation, monitor);
- }
-
- @SuppressWarnings("rawtypes")
- public Object getAdapter(Class adapter) {
- // if we are adapting to file or writable repositories then make sure we have a file location
- if (adapter == IFileArtifactRepository.class)
- if (!isLocal())
- return null;
- return super.getAdapter(adapter);
- }
-
- IStatus getArtifact(IArtifactRequest request, IProgressMonitor monitor) {
- request.perform(this, monitor);
- return request.getResult();
- }
-
- public IStatus getArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- ProcessingStepHandler handler = new ProcessingStepHandler();
- destination = processDestination(handler, descriptor, destination, monitor);
- IStatus status = ProcessingStepHandler.checkStatus(destination);
- if (!status.isOK() && status.getSeverity() != IStatus.INFO)
- return status;
-
- return downloadArtifact(descriptor, destination, monitor);
- }
-
- public IStatus getRawArtifact(IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- return downloadArtifact(descriptor, destination, monitor);
- }
-
- public synchronized IArtifactDescriptor[] getArtifactDescriptors(IArtifactKey key) {
- List<IArtifactDescriptor> result = artifactMap.get(key);
- if (result == null)
- return new IArtifactDescriptor[0];
-
- return result.toArray(new IArtifactDescriptor[result.size()]);
- }
-
- public File getArtifactFile(IArtifactDescriptor descriptor) {
- URI result = getLocation(descriptor);
- if (result == null || !URIUtil.isFileURI(result))
- return null;
- return URIUtil.toFile(result);
- }
-
- public File getArtifactFile(IArtifactKey key) {
- IArtifactDescriptor descriptor = getCompleteArtifactDescriptor(key);
- if (descriptor == null)
- return null;
- return getArtifactFile(descriptor);
- }
-
- public IStatus getArtifacts(IArtifactRequest[] requests, IProgressMonitor monitor) {
- final MultiStatus overallStatus = new MultiStatus(Activator.ID, IStatus.OK, null, null);
- LinkedList<IArtifactRequest> requestsPending = new LinkedList<IArtifactRequest>(Arrays.asList(requests));
-
- int numberOfJobs = Math.min(requests.length, getMaximumThreads());
- if (numberOfJobs <= 1 || (!isForceThreading() && isLocal())) {
- SubMonitor subMonitor = SubMonitor.convert(monitor, requests.length);
- try {
- for (int i = 0; i < requests.length; i++) {
- if (monitor.isCanceled())
- return Status.CANCEL_STATUS;
- IStatus result = getArtifact(requests[i], subMonitor.newChild(1));
- if (!result.isOK())
- overallStatus.add(result);
- }
- } finally {
- subMonitor.done();
- }
- } else {
- // initialize the various jobs needed to process the get artifact requests
- monitor.beginTask(NLS.bind(Messages.sar_downloading, Integer.toString(requests.length)), requests.length);
- try {
- DownloadJob jobs[] = new DownloadJob[numberOfJobs];
- for (int i = 0; i < numberOfJobs; i++) {
- jobs[i] = new DownloadJob(Messages.sar_downloadJobName + i);
- jobs[i].initialize(this, requestsPending, monitor, overallStatus);
- jobs[i].schedule();
- }
- // wait for all the jobs to complete
- try {
- Job.getJobManager().join(DownloadJob.FAMILY, null);
- } catch (InterruptedException e) {
- //ignore
- }
- } finally {
- monitor.done();
- }
- }
- return (monitor.isCanceled() ? Status.CANCEL_STATUS : overallStatus);
- }
-
- public synchronized IArtifactDescriptor getCompleteArtifactDescriptor(IArtifactKey key) {
- List<IArtifactDescriptor> descriptors = artifactMap.get(key);
- if (descriptors == null)
- return null;
-
- for (IArtifactDescriptor desc : descriptors) {
- // look for a descriptor that matches the key and is "complete"
- if (desc.getArtifactKey().equals(key) && desc.getProcessingSteps().length == 0)
- return desc;
- }
- return null;
- }
-
- public synchronized Set<SimpleArtifactDescriptor> getDescriptors() {
- return artifactDescriptors;
- }
-
- /**
- * Typically non-canonical forms of the artifact are stored in the blob store.
- * However, we support having the pack200 files alongside the canonical artifact
- * for compatibility with the format used in optimized update sites. We call
- * this arrangement "flat but packed".
- */
- private boolean flatButPackedEnabled(IArtifactDescriptor descriptor) {
- return Boolean.TRUE.toString().equals(getProperties().get(PUBLISH_PACK_FILES_AS_SIBLINGS)) && IArtifactDescriptor.FORMAT_PACKED.equals(descriptor.getProperty(IArtifactDescriptor.FORMAT));
- }
-
- /**
- * @see #flatButPackedEnabled(IArtifactDescriptor)
- */
- private URI getLocationForPackedButFlatArtifacts(IArtifactDescriptor descriptor) {
- IArtifactKey key = descriptor.getArtifactKey();
- return mapper.map(getLocation(), key.getClassifier(), key.getId(), key.getVersion().toString(), descriptor.getProperty(IArtifactDescriptor.FORMAT));
- }
-
- public synchronized URI getLocation(IArtifactDescriptor descriptor) {
- if (flatButPackedEnabled(descriptor)) {
- return getLocationForPackedButFlatArtifacts(descriptor);
- }
-
- // if the artifact has a uuid then use it
- String uuid = descriptor.getProperty(ARTIFACT_UUID);
- if (uuid != null)
- return blobStore.fileFor(bytesFromHexString(uuid));
-
- try {
- // if the artifact is just a reference then return the reference location
- if (descriptor instanceof SimpleArtifactDescriptor) {
- String artifactReference = ((SimpleArtifactDescriptor) descriptor).getRepositoryProperty(SimpleArtifactDescriptor.ARTIFACT_REFERENCE);
- if (artifactReference != null) {
- try {
- return new URI(artifactReference);
- } catch (URISyntaxException e) {
- return URIUtil.fromString(artifactReference);
- }
- }
- }
-
- // if the descriptor is complete then use the mapping rules...
- if (descriptor.getProcessingSteps().length == 0) {
- IArtifactKey key = descriptor.getArtifactKey();
- URI result = mapper.map(getLocation(), key.getClassifier(), key.getId(), key.getVersion().toString(), descriptor.getProperty(IArtifactDescriptor.FORMAT));
- if (result != null) {
- if (isFolderBased(descriptor) && URIUtil.lastSegment(result).endsWith(JAR_EXTENSION))
- return URIUtil.removeFileExtension(result);
-
- return result;
- }
- }
- } catch (URISyntaxException e) {
- return null;
- }
- // in the end there is not enough information so return null
- return null;
- }
-
- /**
- * Returns the maximum number of concurrent download threads.
- */
- private int getMaximumThreads() {
- try {
- String maxThreadString = getProperties().get(PROP_MAX_THREADS);
- if (maxThreadString != null)
- return Math.max(1, Integer.parseInt(maxThreadString));
- } catch (NumberFormatException nfe) {
- // return default number of threads
- }
- return DEFAULT_MAX_THREADS;
- }
-
- public OutputStream getOutputStream(IArtifactDescriptor descriptor) throws ProvisionException {
- assertModifiable();
-
- // Create a copy of the original descriptor that we can manipulate and add to our repo.
- ArtifactDescriptor newDescriptor = createInternalDescriptor(descriptor);
-
- // Check if the artifact is already in this repository, check the newDescriptor instead of the original
- // since the implementation of hash/equals on the descriptor matters here.
- if (contains(newDescriptor)) {
- String msg = NLS.bind(Messages.available_already_in, getLocation().toString());
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.ARTIFACT_EXISTS, msg, null));
- }
-
- // Determine writing location
- URI newLocation = createLocation(newDescriptor);
- if (newLocation == null)
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.no_location, newDescriptor)));
- String file = URIUtil.toFile(newLocation).getAbsolutePath();
-
- // TODO at this point we have to assume that the repository is file-based. Eventually
- // we should end up with writeable URLs...
- // Make sure that the file does not exist and that the parents do
- File outputFile = new File(file);
- if (outputFile.exists()) {
- System.err.println("Artifact repository out of sync. Overwriting " + outputFile.getAbsoluteFile()); //$NON-NLS-1$
- delete(outputFile);
- }
-
- OutputStream target = null;
- try {
- if (isFolderBased(newDescriptor)) {
- mkdirs(outputFile);
- if (!outputFile.isDirectory())
- throw failedWrite(new IOException(NLS.bind(Messages.sar_failedMkdir, outputFile.toString())));
- target = new ZippedFolderOutputStream(outputFile);
- } else {
- // file based
- File parent = outputFile.getParentFile();
- parent.mkdirs();
- if (!parent.isDirectory())
- throw failedWrite(new IOException(NLS.bind(Messages.sar_failedMkdir, parent.toString())));
- target = new FileOutputStream(file);
- }
-
- // finally create and return an output stream suitably wrapped so that when it is
- // closed the repository is updated with the descriptor
- return new ArtifactOutputStream(new BufferedOutputStream(target), newDescriptor, outputFile);
- } catch (IOException e) {
- throw failedWrite(e);
- }
-
- }
-
- /**
- * We implement mkdirs ourselves because this code is known to run in
- * highly concurrent scenarios, and there is a race condition in the JRE implementation
- * of mkdirs (see bug 265654).
- */
- private void mkdirs(File dir) {
- if (dir == null || dir.exists())
- return;
- if (dir.mkdir())
- return;
- mkdirs(dir.getParentFile());
- dir.mkdir();
- }
-
- private ProvisionException failedWrite(Exception e) throws ProvisionException {
- String msg = NLS.bind(Messages.repoFailedWrite, getLocation());
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_WRITE, msg, e));
- }
-
- public synchronized String[][] getRules() {
- return mappingRules;
- }
-
- private Transport getTransport() {
- return RepositoryTransport.getInstance();
- }
-
- // use this method to setup any transient fields etc after the object has been restored from a stream
- public synchronized void initializeAfterLoad(URI repoLocation) {
- setLocation(repoLocation);
- blobStore = new BlobStore(getBlobStoreLocation(repoLocation), 128);
- initializeMapper();
- for (SimpleArtifactDescriptor desc : artifactDescriptors)
- desc.setRepository(this);
- }
-
- private synchronized void initializeMapper() {
- mapper = new Mapper();
- mapper.initialize(Activator.getContext(), mappingRules);
- }
-
- private boolean isFolderBased(IArtifactDescriptor descriptor) {
- // This is called from createInternalDescriptor, so if we aren't a
- // SimpleArtifactDescriptor then just check the descriptor properties instead
- // of creating the internal descriptor.
- SimpleArtifactDescriptor internalDescriptor = null;
- if (descriptor instanceof SimpleArtifactDescriptor)
- internalDescriptor = (SimpleArtifactDescriptor) descriptor;
- if (internalDescriptor != null) {
- String useArtifactFolder = internalDescriptor.getRepositoryProperty(ARTIFACT_FOLDER);
- if (useArtifactFolder != null)
- return Boolean.valueOf(useArtifactFolder).booleanValue();
- }
- return Boolean.valueOf(descriptor.getProperty(ARTIFACT_FOLDER)).booleanValue();
- }
-
- private boolean isForceThreading() {
- return "true".equals(getProperties().get(PROP_FORCE_THREADING)); //$NON-NLS-1$
- }
-
- private boolean isLocal() {
- return "file".equalsIgnoreCase(getLocation().getScheme()); //$NON-NLS-1$
- }
-
- public boolean isModifiable() {
- return isLocal();
- }
-
- public OutputStream processDestination(ProcessingStepHandler handler, IArtifactDescriptor descriptor, OutputStream destination, IProgressMonitor monitor) {
- destination = addPostSteps(handler, descriptor, destination, monitor);
- destination = handler.createAndLink(getProvisioningAgent(), descriptor.getProcessingSteps(), descriptor, destination, monitor);
- destination = addPreSteps(handler, descriptor, destination, monitor);
- return destination;
- }
-
- public synchronized void removeAll() {
- IArtifactDescriptor[] toRemove = artifactDescriptors.toArray(new IArtifactDescriptor[artifactDescriptors.size()]);
- boolean changed = false;
- for (int i = 0; i < toRemove.length; i++)
- changed |= doRemoveArtifact(toRemove[i]);
- if (changed)
- save();
- }
-
- public synchronized void removeDescriptor(IArtifactDescriptor descriptor) {
- if (doRemoveArtifact(descriptor))
- save();
- }
-
- public synchronized void removeDescriptor(IArtifactKey key) {
- IArtifactDescriptor[] toRemove = getArtifactDescriptors(key);
- boolean changed = false;
- for (int i = 0; i < toRemove.length; i++)
- changed |= doRemoveArtifact(toRemove[i]);
- if (changed)
- save();
- }
-
- private IStatus reportStatus(IArtifactDescriptor descriptor, OutputStream destination, IStatus status) {
- // If the destination is just a normal stream then the status is simple. Just return
- // it and do not close the destination
- if (!(destination instanceof ProcessingStep))
- return status;
-
- // If the destination is a processing step then close the stream to flush the data through all
- // the steps. then collect up the status from all the steps and return
- try {
- destination.close();
- } catch (IOException e) {
- return new Status(IStatus.ERROR, Activator.ID, NLS.bind(Messages.sar_reportStatus, descriptor.getArtifactKey().toExternalForm()), e);
- }
-
- // An error occurred obtaining the artifact, ProcessingStep errors aren't important
- if (status.matches(IStatus.ERROR))
- return status;
-
- IStatus stepStatus = ProcessingStepHandler.getErrorStatus(destination);
- // if the steps all ran ok and there is no interesting information, return the status from this method
- if (!stepStatus.isMultiStatus() && stepStatus.isOK())
- return status;
- // else gather up the status from the steps
- MultiStatus result = new MultiStatus(Activator.ID, IStatus.OK, new IStatus[0], NLS.bind(Messages.sar_reportStatus, descriptor.getArtifactKey().toExternalForm()), null);
-
- if (!status.isOK()) {
- // Transport pushes its status onto the output stream if the stream implements IStateful, to prevent
- // duplication determine if the Status is present in the ProcessingStep status.
- boolean found = false;
- IStatus[] stepStatusChildren = stepStatus.getChildren();
- for (int i = 0; i < stepStatusChildren.length && !found; i++)
- if (stepStatusChildren[i] == status)
- found = true;
- if (!found)
- result.merge(status);
- }
-
- result.merge(stepStatus);
- return result;
- }
-
- public void save() {
- if (disableSave)
- return;
- boolean compress = "true".equalsIgnoreCase(getProperty(PROP_COMPRESSED)); //$NON-NLS-1$
- save(compress);
- }
-
- private void save(boolean compress) {
- assertModifiable();
- OutputStream os = null;
- try {
- try {
- URI actualLocation = getActualLocation(getLocation(), false);
- File artifactsFile = URIUtil.toFile(actualLocation);
- File jarFile = URIUtil.toFile(getActualLocation(getLocation(), true));
- if (!compress) {
- if (jarFile.exists()) {
- jarFile.delete();
- }
- if (!artifactsFile.exists()) {
- // create parent folders
- mkdirs(artifactsFile.getParentFile());
- }
- os = new FileOutputStream(artifactsFile);
- } else {
- if (artifactsFile.exists()) {
- artifactsFile.delete();
- }
- if (!jarFile.exists()) {
- mkdirs(jarFile.getParentFile());
- jarFile.createNewFile();
- }
- JarOutputStream jOs = new JarOutputStream(new FileOutputStream(jarFile));
- jOs.putNextEntry(new JarEntry(new Path(artifactsFile.getAbsolutePath()).lastSegment()));
- os = jOs;
- }
- super.setProperty(IRepository.PROP_TIMESTAMP, Long.toString(System.currentTimeMillis()));
- new SimpleArtifactRepositoryIO(getProvisioningAgent()).write(this, os);
- } catch (IOException e) {
- // TODO proper exception handling
- e.printStackTrace();
- } finally {
- if (os != null)
- os.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public String setProperty(String key, String newValue) {
- String oldValue = super.setProperty(key, newValue);
- if (oldValue == newValue || (oldValue != null && oldValue.equals(newValue)))
- return oldValue;
- if (PUBLISH_PACK_FILES_AS_SIBLINGS.equals(key)) {
- synchronized (this) {
- if (Boolean.TRUE.toString().equals(newValue)) {
- mappingRules = PACKED_MAPPING_RULES;
- } else {
- mappingRules = DEFAULT_MAPPING_RULES;
- }
- initializeMapper();
- }
- }
- save();
- //force repository manager to reload this repository because it caches properties
- ArtifactRepositoryManager manager = (ArtifactRepositoryManager) getProvisioningAgent().getService(IArtifactRepositoryManager.SERVICE_NAME);
- if (manager.removeRepository(getLocation()))
- manager.addRepository(this);
- return oldValue;
- }
-
- public synchronized void setRules(String[][] rules) {
- mappingRules = rules;
- }
-
- public String toString() {
- return getLocation().toString();
- }
-
- public IQueryable<IArtifactDescriptor> descriptorQueryable() {
- return new IQueryable<IArtifactDescriptor>() {
- public IQueryResult<IArtifactDescriptor> query(IQuery<IArtifactDescriptor> query, IProgressMonitor monitor) {
- synchronized (SimpleArtifactRepository.this) {
- snapshotNeeded = true;
- Collection<List<IArtifactDescriptor>> descs = SimpleArtifactRepository.this.artifactMap.values();
- return query.perform(new CompoundIterator<IArtifactDescriptor>(descs.iterator()));
- }
- }
- };
- }
-
- public IQueryResult<IArtifactKey> query(IQuery<IArtifactKey> query, IProgressMonitor monitor) {
- return IndexProvider.query(this, query, monitor);
- }
-
- public synchronized Iterator<IArtifactKey> everything() {
- snapshotNeeded = true;
- return artifactMap.keySet().iterator();
- }
-
- public IStatus executeBatch(IRunnableWithProgress runnable, IProgressMonitor monitor) {
- IStatus result = null;
- synchronized (this) {
- try {
- disableSave = true;
- runnable.run(monitor);
- } catch (OperationCanceledException oce) {
- return new Status(IStatus.CANCEL, Activator.ID, oce.getMessage(), oce);
- } catch (Throwable e) {
- result = new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e);
- } finally {
- disableSave = false;
- try {
- save();
- } catch (Exception e) {
- if (result != null)
- result = new MultiStatus(Activator.ID, IStatus.ERROR, new IStatus[] {result}, e.getMessage(), e);
- else
- result = new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e);
- }
- }
- }
- if (result == null)
- result = Status.OK_STATUS;
- return result;
- }
-
- public synchronized IIndex<IArtifactKey> getIndex(String memberName) {
- if (ArtifactKey.MEMBER_ID.equals(memberName)) {
- snapshotNeeded = true;
- if (keyIndex == null)
- keyIndex = new KeyIndex(artifactMap.keySet());
- return keyIndex;
- }
- return null;
- }
-
- public Object getManagedProperty(Object client, String memberName, Object key) {
- return null;
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java
deleted file mode 100644
index 4ebeb06ad..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryFactory.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- * Sonatype Inc - ongoing development
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.io.*;
-import java.net.URI;
-import java.util.Map;
-import java.util.jar.JarEntry;
-import java.util.jar.JarInputStream;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.artifact.repository.Activator;
-import org.eclipse.equinox.internal.p2.artifact.repository.Messages;
-import org.eclipse.equinox.internal.p2.core.helpers.Tracing;
-import org.eclipse.equinox.internal.p2.repository.CacheManager;
-import org.eclipse.equinox.p2.core.ProvisionException;
-import org.eclipse.equinox.p2.repository.IRepositoryManager;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
-import org.eclipse.equinox.p2.repository.artifact.spi.ArtifactRepositoryFactory;
-import org.eclipse.osgi.util.NLS;
-
-public class SimpleArtifactRepositoryFactory extends ArtifactRepositoryFactory {
- private static final String PROTOCOL_FILE = "file"; //$NON-NLS-1$
- private static final String JAR_EXTENSION = ".jar"; //$NON-NLS-1$
- private static final String XML_EXTENSION = ".xml"; //$NON-NLS-1$
-
- public SimpleArtifactRepositoryFactory() {
- super();
- }
-
- /**
- * Returns a file in the local file system that contains the contents of the
- * metadata repository at the given location.
- */
- private File getLocalFile(URI location, IProgressMonitor monitor) throws IOException, ProvisionException {
- File localFile = null;
- URI jarLocation = SimpleArtifactRepository.getActualLocation(location, true);
- URI xmlLocation = SimpleArtifactRepository.getActualLocation(location, false);
- // If the repository is local, we can return the repository file directly
- if (PROTOCOL_FILE.equals(xmlLocation.getScheme())) {
- //look for a compressed local file
- localFile = URIUtil.toFile(jarLocation);
- if (localFile.exists())
- return localFile;
- //look for an uncompressed local file
- localFile = URIUtil.toFile(xmlLocation);
- if (localFile.exists())
- return localFile;
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, null));
- }
- // file is not local, create a cache of the repository metadata
- CacheManager cache = (CacheManager) getAgent().getService(CacheManager.SERVICE_NAME);
- if (cache == null)
- throw new IllegalArgumentException("Cache manager service not available"); //$NON-NLS-1$
- localFile = cache.createCache(location, SimpleArtifactRepository.CONTENT_FILENAME, monitor);
- if (localFile == null) {
- // there is no remote file in either form - this should not really happen as
- // createCache should bail out with exception if something is wrong. This is an internal
- // error.
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, Messages.repoMan_internalError, null));
- }
- return localFile;
- }
-
- public IArtifactRepository load(URI location, int flags, IProgressMonitor monitor) throws ProvisionException {
- long time = 0;
- final String debugMsg = "Restoring artifact repository "; //$NON-NLS-1$
- if (Tracing.DEBUG_METADATA_PARSING) {
- Tracing.debug(debugMsg + location);
- time = -System.currentTimeMillis();
- }
- SubMonitor sub = SubMonitor.convert(monitor, 400);
- try {
- File localFile = getLocalFile(location, sub.newChild(300));
- InputStream inStream = new BufferedInputStream(new FileInputStream(localFile));
- JarInputStream jarStream = null;
- try {
- //if reading from a jar, obtain a stream on the entry with the actual contents
- if (localFile.getAbsolutePath().endsWith(JAR_EXTENSION)) {
- jarStream = new JarInputStream(inStream);
- JarEntry jarEntry = jarStream.getNextJarEntry();
- String entryName = SimpleArtifactRepository.CONTENT_FILENAME + XML_EXTENSION;
- while (jarEntry != null && (!entryName.equals(jarEntry.getName()))) {
- jarEntry = jarStream.getNextJarEntry();
- }
- //if there is a jar but the entry is missing or invalid, treat this as an invalid repository
- if (jarEntry == null)
- throw new IOException(NLS.bind(Messages.io_invalidLocation, location));
- }
- //parse the repository descriptor file
- sub.setWorkRemaining(100);
- InputStream descriptorStream = jarStream != null ? jarStream : inStream;
- SimpleArtifactRepositoryIO io = new SimpleArtifactRepositoryIO(getAgent());
- SimpleArtifactRepository result = (SimpleArtifactRepository) io.read(localFile.toURL(), descriptorStream, sub.newChild(100));
- result.initializeAfterLoad(location);
- if (result != null && (flags & IRepositoryManager.REPOSITORY_HINT_MODIFIABLE) > 0 && !result.isModifiable())
- return null;
- if (Tracing.DEBUG_METADATA_PARSING) {
- time += System.currentTimeMillis();
- Tracing.debug(debugMsg + "time (ms): " + time); //$NON-NLS-1$
- }
- return result;
- } finally {
- safeClose(jarStream);
- safeClose(inStream);
- }
- } catch (FileNotFoundException e) {
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_NOT_FOUND, msg, e));
- } catch (IOException e) {
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, e));
- } finally {
- if (monitor != null)
- monitor.done();
- }
- }
-
- public IArtifactRepository create(URI location, String name, String type, Map<String, String> properties) {
- return new SimpleArtifactRepository(getAgent(), name, location, properties);
- }
-
- /**
- * Closes a stream, ignoring any secondary exceptions
- */
- private void safeClose(InputStream stream) {
- if (stream == null)
- return;
- try {
- stream.close();
- } catch (IOException e) {
- //ignore
- }
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java
deleted file mode 100644
index 06df4e3e6..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/SimpleArtifactRepositoryIO.java
+++ /dev/null
@@ -1,517 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2010 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.io.*;
-import java.net.URL;
-import java.util.*;
-import javax.xml.parsers.ParserConfigurationException;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.artifact.repository.Activator;
-import org.eclipse.equinox.internal.p2.artifact.repository.Messages;
-import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
-import org.eclipse.equinox.internal.p2.core.helpers.OrderedProperties;
-import org.eclipse.equinox.internal.p2.metadata.ArtifactKey;
-import org.eclipse.equinox.internal.p2.persistence.XMLParser;
-import org.eclipse.equinox.internal.p2.persistence.XMLWriter;
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.core.ProvisionException;
-import org.eclipse.equinox.p2.metadata.*;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository;
-import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.spi.ProcessingStepDescriptor;
-import org.eclipse.osgi.util.NLS;
-import org.osgi.framework.BundleContext;
-import org.xml.sax.*;
-
-/**
- * This class reads and writes artifact repository metadata
- * (e.g. table of contents files);
- *
- * This class is not used for reading or writing the actual artifacts.
- */
-
-// TODO: Should a registration/factory mechanism be supported
-// for getting a repository reader/writer given a repository type
-public class SimpleArtifactRepositoryIO {
-
- private final IProvisioningAgent agent;
-
- public SimpleArtifactRepositoryIO(IProvisioningAgent agent) {
- this.agent = agent;
- }
-
- /**
- * Writes the given artifact repository to the stream.
- * This method performs buffering, and closes the stream when finished.
- */
- public void write(SimpleArtifactRepository repository, OutputStream output) {
- OutputStream bufferedOutput = null;
- try {
- try {
- bufferedOutput = new BufferedOutputStream(output);
- Writer repositoryWriter = new Writer(bufferedOutput);
- repositoryWriter.write(repository);
- } finally {
- if (bufferedOutput != null) {
- bufferedOutput.close();
- }
- }
- } catch (IOException ioe) {
- // TODO shouldn't this throw a core exception?
- ioe.printStackTrace();
- }
- }
-
- /**
- * Reads the artifact repository from the given stream,
- * and returns the contained array of abstract artifact repositories.
- *
- * This method performs buffering, and closes the stream when finished.
- */
- public IArtifactRepository read(URL location, InputStream input, IProgressMonitor monitor) throws ProvisionException {
- BufferedInputStream bufferedInput = null;
- try {
- try {
- bufferedInput = new BufferedInputStream(input);
- Parser repositoryParser = new Parser(Activator.getContext(), Activator.ID);
- repositoryParser.parse(input);
- IStatus result = repositoryParser.getStatus();
- switch (result.getSeverity()) {
- case IStatus.CANCEL :
- throw new OperationCanceledException();
- case IStatus.ERROR :
- throw new ProvisionException(result);
- case IStatus.WARNING :
- case IStatus.INFO :
- LogHelper.log(result);
- }
- SimpleArtifactRepository repository = repositoryParser.getRepository();
- if (repository == null)
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, Messages.io_parseError, null));
- return repository;
- } finally {
- if (bufferedInput != null)
- bufferedInput.close();
- }
- } catch (IOException ioe) {
- String msg = NLS.bind(Messages.io_failedRead, location);
- throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.REPOSITORY_FAILED_READ, msg, ioe));
- }
- }
-
- private interface XMLConstants extends org.eclipse.equinox.internal.p2.persistence.XMLConstants {
-
- // Constants defining the structure of the XML for a SimpleArtifactRepository
-
- // A format version number for simple artifact repository XML.
- public static final Version COMPATIBLE_VERSION = Version.createOSGi(1, 0, 0);
- public static final Version CURRENT_VERSION = Version.createOSGi(1, 1, 0);
- public static final VersionRange XML_TOLERANCE = new VersionRange(COMPATIBLE_VERSION, true, Version.createOSGi(2, 0, 0), false);
-
- // Constants for processing instructions
- public static final String PI_REPOSITORY_TARGET = "artifactRepository"; //$NON-NLS-1$
- public static XMLWriter.ProcessingInstruction[] PI_DEFAULTS = new XMLWriter.ProcessingInstruction[] {XMLWriter.ProcessingInstruction.makeTargetVersionInstruction(PI_REPOSITORY_TARGET, CURRENT_VERSION)};
-
- // Constants for artifact repository elements
- public static final String REPOSITORY_ELEMENT = "repository"; //$NON-NLS-1$
- public static final String REPOSITORY_PROPERTIES_ELEMENT = "repositoryProperties"; //$NON-NLS-1$
- public static final String MAPPING_RULES_ELEMENT = "mappings"; //$NON-NLS-1$
- public static final String MAPPING_RULE_ELEMENT = "rule"; //$NON-NLS-1$
- public static final String ARTIFACTS_ELEMENT = "artifacts"; //$NON-NLS-1$
- public static final String ARTIFACT_ELEMENT = "artifact"; //$NON-NLS-1$
- public static final String PROCESSING_STEPS_ELEMENT = "processing"; //$NON-NLS-1$
- public static final String PROCESSING_STEP_ELEMENT = "step"; //$NON-NLS-1$
-
- public static final String MAPPING_RULE_FILTER_ATTRIBUTE = "filter"; //$NON-NLS-1$
- public static final String MAPPING_RULE_OUTPUT_ATTRIBUTE = "output"; //$NON-NLS-1$
-
- public static final String ARTIFACT_CLASSIFIER_ATTRIBUTE = CLASSIFIER_ATTRIBUTE;
-
- public static final String STEP_DATA_ATTRIBUTE = "data"; //$NON-NLS-1$
- public static final String STEP_REQUIRED_ATTRIBUTE = "required"; //$NON-NLS-1$
- }
-
- // XML writer for a SimpleArtifactRepository
- protected class Writer extends XMLWriter implements XMLConstants {
-
- public Writer(OutputStream output) throws IOException {
- super(output, PI_DEFAULTS);
- }
-
- /**
- * Write the given artifact repository to the output stream.
- */
- public void write(SimpleArtifactRepository repository) {
- start(REPOSITORY_ELEMENT);
- attribute(NAME_ATTRIBUTE, repository.getName());
- attribute(TYPE_ATTRIBUTE, repository.getType());
- attribute(VERSION_ATTRIBUTE, repository.getVersion());
- attributeOptional(PROVIDER_ATTRIBUTE, repository.getProvider());
- attributeOptional(DESCRIPTION_ATTRIBUTE, repository.getDescription()); // TODO: could be cdata?
-
- writeProperties(repository.getProperties());
- writeMappingRules(repository.getRules());
- writeArtifacts(repository.getDescriptors());
-
- end(REPOSITORY_ELEMENT);
- flush();
- }
-
- private void writeMappingRules(String[][] rules) {
- if (rules.length > 0) {
- start(MAPPING_RULES_ELEMENT);
- attribute(COLLECTION_SIZE_ATTRIBUTE, rules.length);
- for (int i = 0; i < rules.length; i++) {
- start(MAPPING_RULE_ELEMENT);
- attribute(MAPPING_RULE_FILTER_ATTRIBUTE, rules[i][0]);
- attribute(MAPPING_RULE_OUTPUT_ATTRIBUTE, rules[i][1]);
- end(MAPPING_RULE_ELEMENT);
- }
- end(MAPPING_RULES_ELEMENT);
- }
- }
-
- private void writeArtifacts(Set<SimpleArtifactDescriptor> artifactDescriptors) {
- start(ARTIFACTS_ELEMENT);
- attribute(COLLECTION_SIZE_ATTRIBUTE, artifactDescriptors.size());
- for (SimpleArtifactDescriptor descriptor : artifactDescriptors) {
- IArtifactKey key = descriptor.getArtifactKey();
- start(ARTIFACT_ELEMENT);
- attribute(ARTIFACT_CLASSIFIER_ATTRIBUTE, key.getClassifier());
- attribute(ID_ATTRIBUTE, key.getId());
- attribute(VERSION_ATTRIBUTE, key.getVersion());
- writeProcessingSteps(descriptor.getProcessingSteps());
- writeProperties(descriptor.getProperties());
- writeProperties(REPOSITORY_PROPERTIES_ELEMENT, descriptor.getRepositoryProperties());
- end(ARTIFACT_ELEMENT);
- }
- end(ARTIFACTS_ELEMENT);
- }
-
- private void writeProcessingSteps(IProcessingStepDescriptor[] processingSteps) {
- if (processingSteps.length > 0) {
- start(PROCESSING_STEPS_ELEMENT);
- attribute(COLLECTION_SIZE_ATTRIBUTE, processingSteps.length);
- for (int i = 0; i < processingSteps.length; i++) {
- start(PROCESSING_STEP_ELEMENT);
- attribute(ID_ATTRIBUTE, processingSteps[i].getProcessorId());
- attribute(STEP_DATA_ATTRIBUTE, processingSteps[i].getData());
- attribute(STEP_REQUIRED_ATTRIBUTE, processingSteps[i].isRequired());
- end(PROCESSING_STEP_ELEMENT);
- }
- end(PROCESSING_STEPS_ELEMENT);
- }
- }
- }
-
- /*
- * Parser for the contents of a SimpleArtifactRepository,
- * as written by the Writer class.
- */
- private class Parser extends XMLParser implements XMLConstants {
-
- private SimpleArtifactRepository theRepository = null;
-
- public Parser(BundleContext context, String bundleId) {
- super(context, bundleId);
- }
-
- public synchronized void parse(InputStream stream) throws IOException {
- this.status = null;
- try {
- // TODO: currently not caching the parser since we make no assumptions
- // or restrictions on concurrent parsing
- getParser();
- RepositoryHandler repositoryHandler = new RepositoryHandler();
- xmlReader.setContentHandler(new RepositoryDocHandler(REPOSITORY_ELEMENT, repositoryHandler));
- xmlReader.parse(new InputSource(stream));
- if (isValidXML()) {
- theRepository = repositoryHandler.getRepository();
- }
- } catch (SAXException e) {
- throw new IOException(e.getMessage());
- } catch (ParserConfigurationException e) {
- throw new IOException(e.getMessage());
- } finally {
- stream.close();
- }
- }
-
- public SimpleArtifactRepository getRepository() {
- return theRepository;
- }
-
- protected Object getRootObject() {
- return theRepository;
- }
-
- private final class RepositoryDocHandler extends DocHandler {
-
- public RepositoryDocHandler(String rootName, RootHandler rootHandler) {
- super(rootName, rootHandler);
- }
-
- public void processingInstruction(String target, String data) throws SAXException {
- if (PI_REPOSITORY_TARGET.equals(target)) {
- // TODO: should the root handler be constructed based on class
- // via an extension registry mechanism?
- // String clazz = extractPIClass(data);
- // TODO: version tolerance by extension
- Version repositoryVersion = extractPIVersion(target, data);
- if (!XML_TOLERANCE.isIncluded(repositoryVersion)) {
- throw new SAXException(NLS.bind(Messages.io_incompatibleVersion, repositoryVersion, XML_TOLERANCE));
- }
- }
- }
-
- }
-
- private final class RepositoryHandler extends RootHandler {
-
- private final String[] required = new String[] {NAME_ATTRIBUTE, TYPE_ATTRIBUTE, VERSION_ATTRIBUTE};
- private final String[] optional = new String[] {DESCRIPTION_ATTRIBUTE, PROVIDER_ATTRIBUTE};
-
- private String[] attrValues = new String[required.length + optional.length];
-
- private MappingRulesHandler mappingRulesHandler = null;
- private PropertiesHandler propertiesHandler = null;
- private ArtifactsHandler artifactsHandler = null;
-
- private SimpleArtifactRepository repository = null;
-
- public RepositoryHandler() {
- super();
- }
-
- public SimpleArtifactRepository getRepository() {
- return repository;
- }
-
- protected void handleRootAttributes(Attributes attributes) {
- attrValues = parseAttributes(attributes, required, optional);
- attrValues[2] = checkVersion(REPOSITORY_ELEMENT, VERSION_ATTRIBUTE, attrValues[2]).toString();
- }
-
- public void startElement(String name, Attributes attributes) {
- if (MAPPING_RULES_ELEMENT.equals(name)) {
- if (mappingRulesHandler == null) {
- mappingRulesHandler = new MappingRulesHandler(this, attributes);
- } else {
- duplicateElement(this, name, attributes);
- }
- } else if (ARTIFACTS_ELEMENT.equals(name)) {
- if (artifactsHandler == null) {
- artifactsHandler = new ArtifactsHandler(this, attributes);
- } else {
- duplicateElement(this, name, attributes);
- }
- } else if (PROPERTIES_ELEMENT.equals(name)) {
- if (propertiesHandler == null) {
- propertiesHandler = new PropertiesHandler(this, attributes);
- } else {
- duplicateElement(this, name, attributes);
- }
- } else {
- invalidElement(name, attributes);
- }
- }
-
- protected void finished() {
- if (isValidXML()) {
- String[][] mappingRules = (mappingRulesHandler == null ? new String[0][0] //
- : mappingRulesHandler.getMappingRules());
- Map<String, String> properties = (propertiesHandler == null ? new OrderedProperties(0) //
- : propertiesHandler.getProperties());
- Set<SimpleArtifactDescriptor> artifacts = (artifactsHandler == null ? new HashSet<SimpleArtifactDescriptor>(0) //
- : artifactsHandler.getArtifacts());
- repository = new SimpleArtifactRepository(agent, attrValues[0], attrValues[1], attrValues[2], attrValues[3], //
- attrValues[4], artifacts, mappingRules, properties);
- }
- }
- }
-
- protected class MappingRulesHandler extends AbstractHandler {
-
- private List<String[]> mappingRules;
-
- public MappingRulesHandler(AbstractHandler parentHandler, Attributes attributes) {
- super(parentHandler, MAPPING_RULES_ELEMENT);
- String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE);
- mappingRules = (size != null ? new ArrayList<String[]>(new Integer(size).intValue()) : new ArrayList<String[]>(4));
- }
-
- public String[][] getMappingRules() {
- String[][] rules = new String[mappingRules.size()][2];
- for (int index = 0; index < mappingRules.size(); index++) {
- String[] ruleAttributes = mappingRules.get(index);
- rules[index] = ruleAttributes;
- }
- return rules;
- }
-
- public void startElement(String name, Attributes attributes) {
- if (name.equals(MAPPING_RULE_ELEMENT)) {
- new MappingRuleHandler(this, attributes, mappingRules);
- } else {
- invalidElement(name, attributes);
- }
- }
- }
-
- protected class MappingRuleHandler extends AbstractHandler {
-
- private final String[] required = new String[] {MAPPING_RULE_FILTER_ATTRIBUTE, MAPPING_RULE_OUTPUT_ATTRIBUTE};
-
- public MappingRuleHandler(AbstractHandler parentHandler, Attributes attributes, List<String[]> mappingRules) {
- super(parentHandler, MAPPING_RULE_ELEMENT);
- mappingRules.add(parseRequiredAttributes(attributes, required));
- }
-
- public void startElement(String name, Attributes attributes) {
- invalidElement(name, attributes);
- }
- }
-
- protected class ArtifactsHandler extends AbstractHandler {
-
- private Set<SimpleArtifactDescriptor> artifacts;
-
- public ArtifactsHandler(AbstractHandler parentHandler, Attributes attributes) {
- super(parentHandler, ARTIFACTS_ELEMENT);
- String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE);
- artifacts = (size != null ? new LinkedHashSet<SimpleArtifactDescriptor>(new Integer(size).intValue()) : new LinkedHashSet<SimpleArtifactDescriptor>(4));
- }
-
- public Set<SimpleArtifactDescriptor> getArtifacts() {
- return artifacts;
- }
-
- public void startElement(String name, Attributes attributes) {
- if (name.equals(ARTIFACT_ELEMENT)) {
- new ArtifactHandler(this, attributes, artifacts);
- } else {
- invalidElement(name, attributes);
- }
- }
- }
-
- protected class ArtifactHandler extends AbstractHandler {
-
- private final String[] required = new String[] {ARTIFACT_CLASSIFIER_ATTRIBUTE, ID_ATTRIBUTE, VERSION_ATTRIBUTE};
-
- private Set<SimpleArtifactDescriptor> artifacts;
- SimpleArtifactDescriptor currentArtifact = null;
-
- private PropertiesHandler propertiesHandler = null;
- private PropertiesHandler repositoryPropertiesHandler = null;
- private ProcessingStepsHandler processingStepsHandler = null;
-
- public ArtifactHandler(AbstractHandler parentHandler, Attributes attributes, Set<SimpleArtifactDescriptor> artifacts) {
- super(parentHandler, ARTIFACT_ELEMENT);
- this.artifacts = artifacts;
- String[] values = parseRequiredAttributes(attributes, required);
- Version version = checkVersion(ARTIFACT_ELEMENT, VERSION_ATTRIBUTE, values[2]);
- // TODO: resolve access restriction on ArtifactKey construction
- currentArtifact = new SimpleArtifactDescriptor(new ArtifactKey(values[0], values[1], version));
- }
-
- public void startElement(String name, Attributes attributes) {
- if (PROCESSING_STEPS_ELEMENT.equals(name)) {
- if (processingStepsHandler == null) {
- processingStepsHandler = new ProcessingStepsHandler(this, attributes);
- } else {
- duplicateElement(this, name, attributes);
- }
- } else if (PROPERTIES_ELEMENT.equals(name)) {
- if (propertiesHandler == null) {
- propertiesHandler = new PropertiesHandler(this, attributes);
- } else {
- duplicateElement(this, name, attributes);
- }
- } else if (REPOSITORY_PROPERTIES_ELEMENT.equals(name)) {
- if (repositoryPropertiesHandler == null) {
- repositoryPropertiesHandler = new PropertiesHandler(this, attributes);
- } else {
- duplicateElement(this, name, attributes);
- }
- } else {
- invalidElement(name, attributes);
- }
- }
-
- protected void finished() {
- if (isValidXML() && currentArtifact != null) {
- Map<String, String> properties = (propertiesHandler == null ? new OrderedProperties(0) : propertiesHandler.getProperties());
- currentArtifact.addProperties(properties);
-
- properties = (repositoryPropertiesHandler == null ? new OrderedProperties(0) : repositoryPropertiesHandler.getProperties());
- currentArtifact.addRepositoryProperties(properties);
-
- IProcessingStepDescriptor[] processingSteps = (processingStepsHandler == null ? new ProcessingStepDescriptor[0] //
- : processingStepsHandler.getProcessingSteps());
- currentArtifact.setProcessingSteps(processingSteps);
- artifacts.add(currentArtifact);
- }
- }
- }
-
- protected class ProcessingStepsHandler extends AbstractHandler {
-
- private List<IProcessingStepDescriptor> processingSteps;
-
- public ProcessingStepsHandler(AbstractHandler parentHandler, Attributes attributes) {
- super(parentHandler, PROCESSING_STEPS_ELEMENT);
- String size = parseOptionalAttribute(attributes, COLLECTION_SIZE_ATTRIBUTE);
- processingSteps = (size != null ? new ArrayList<IProcessingStepDescriptor>(new Integer(size).intValue()) : new ArrayList<IProcessingStepDescriptor>(4));
- }
-
- public IProcessingStepDescriptor[] getProcessingSteps() {
- return processingSteps.toArray(new ProcessingStepDescriptor[processingSteps.size()]);
- }
-
- public void startElement(String name, Attributes attributes) {
- if (name.equals(PROCESSING_STEP_ELEMENT)) {
- new ProcessingStepHandler(this, attributes, processingSteps);
- } else {
- invalidElement(name, attributes);
- }
- }
- }
-
- protected class ProcessingStepHandler extends AbstractHandler {
-
- private final String[] required = new String[] {ID_ATTRIBUTE, STEP_REQUIRED_ATTRIBUTE};
- private final String[] optional = new String[] {STEP_DATA_ATTRIBUTE};
-
- public ProcessingStepHandler(AbstractHandler parentHandler, Attributes attributes, List<IProcessingStepDescriptor> processingSteps) {
- super(parentHandler, PROCESSING_STEP_ELEMENT);
- String[] attributeValues = parseAttributes(attributes, required, optional);
- processingSteps.add(new ProcessingStepDescriptor(attributeValues[0], attributeValues[2], checkBoolean(PROCESSING_STEP_ELEMENT, STEP_REQUIRED_ATTRIBUTE, attributeValues[1]).booleanValue()));
- }
-
- public void startElement(String name, Attributes attributes) {
- invalidElement(name, attributes);
- }
- }
-
- protected String getErrorMessage() {
- return Messages.io_parseError;
- }
-
- public String toString() {
- // TODO:
- return null;
- }
-
- }
-
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/UniversalUniqueIdentifier.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/UniversalUniqueIdentifier.java
deleted file mode 100644
index 636893afa..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/p2/artifact/repository/simple/UniversalUniqueIdentifier.java
+++ /dev/null
@@ -1,349 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2007 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-package org.eclipse.equinox.internal.p2.artifact.repository.simple;
-
-import java.io.*;
-import java.math.BigInteger;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.security.SecureRandom;
-import java.util.GregorianCalendar;
-import java.util.Random;
-import org.eclipse.core.runtime.Assert;
-
-public class UniversalUniqueIdentifier implements java.io.Serializable {
-
- /**
- * All serializable objects should have a stable serialVersionUID
- */
- private static final long serialVersionUID = 1L;
-
- /* INSTANCE FIELDS =============================================== */
-
- private byte[] fBits = new byte[BYTES_SIZE];
-
- /* NON-FINAL PRIVATE STATIC FIELDS =============================== */
-
- private static BigInteger fgPreviousClockValue;
- private static int fgClockAdjustment = 0;
- private static int fgClockSequence = -1;
- private static byte[] nodeAddress;
-
- static {
- nodeAddress = computeNodeAddress();
- }
-
- /* PRIVATE STATIC FINAL FIELDS =================================== */
-
- private static Random fgRandomNumberGenerator = new Random();
-
- /* PUBLIC STATIC FINAL FIELDS ==================================== */
-
- public static final int BYTES_SIZE = 16;
- public static final byte[] UNDEFINED_UUID_BYTES = new byte[16];
- public static final int MAX_CLOCK_SEQUENCE = 0x4000;
- public static final int MAX_CLOCK_ADJUSTMENT = 0x7FFF;
- public static final int TIME_FIELD_START = 0;
- public static final int TIME_FIELD_STOP = 6;
- public static final int TIME_HIGH_AND_VERSION = 7;
- public static final int CLOCK_SEQUENCE_HIGH_AND_RESERVED = 8;
- public static final int CLOCK_SEQUENCE_LOW = 9;
- public static final int NODE_ADDRESS_START = 10;
- public static final int NODE_ADDRESS_BYTE_SIZE = 6;
-
- public static final int BYTE_MASK = 0xFF;
-
- public static final int HIGH_NIBBLE_MASK = 0xF0;
-
- public static final int LOW_NIBBLE_MASK = 0x0F;
-
- public static final int SHIFT_NIBBLE = 4;
-
- public static final int ShiftByte = 8;
-
- /**
- UniversalUniqueIdentifier default constructor returns a
- new instance that has been initialized to a unique value.
- */
- public UniversalUniqueIdentifier() {
- this.setVersion(1);
- this.setVariant(1);
- this.setTimeValues();
- this.setNode(getNodeAddress());
- }
-
- /**
- Constructor that accepts the bytes to use for the instance.&nbsp;&nbsp; The format
- of the byte array is compatible with the <code>toBytes()</code> method.
-
- <p>The constructor returns the undefined uuid if the byte array is invalid.
-
- @see #toBytes()
- @see #BYTES_SIZE
- */
- public UniversalUniqueIdentifier(byte[] byteValue) {
- fBits = new byte[BYTES_SIZE];
- if (byteValue.length >= BYTES_SIZE)
- System.arraycopy(byteValue, 0, fBits, 0, BYTES_SIZE);
- }
-
- private void appendByteString(StringBuffer buffer, byte value) {
- String hexString;
-
- if (value < 0)
- hexString = Integer.toHexString(256 + value);
- else
- hexString = Integer.toHexString(value);
- if (hexString.length() == 1)
- buffer.append("0"); //$NON-NLS-1$
- buffer.append(hexString);
- }
-
- private static BigInteger clockValueNow() {
- GregorianCalendar now = new GregorianCalendar();
- BigInteger nowMillis = BigInteger.valueOf(now.getTime().getTime());
- BigInteger baseMillis = BigInteger.valueOf(now.getGregorianChange().getTime());
-
- return (nowMillis.subtract(baseMillis).multiply(BigInteger.valueOf(10000L)));
- }
-
- /**
- Simply increases the visibility of <code>Object</code>'s clone.
- Otherwise, no new behaviour.
- */
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- Assert.isTrue(false, "Clone not supported");
- return null;
- }
- }
-
- public static int compareTime(byte[] fBits1, byte[] fBits2) {
- for (int i = TIME_FIELD_STOP; i >= 0; i--)
- if (fBits1[i] != fBits2[i])
- return (0xFF & fBits1[i]) - (0xFF & fBits2[i]);
- return 0;
- }
-
- /**
- * Answers the node address attempting to mask the IP
- * address of this machine.
- *
- * @return byte[] the node address
- */
- private static byte[] computeNodeAddress() {
-
- byte[] address = new byte[NODE_ADDRESS_BYTE_SIZE];
-
- // Seed the secure randomizer with some oft-varying inputs
- int thread = Thread.currentThread().hashCode();
- long time = System.currentTimeMillis();
- int objectId = System.identityHashCode(new String());
- ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
- DataOutputStream out = new DataOutputStream(byteOut);
- byte[] ipAddress = getIPAddress();
-
- try {
- if (ipAddress != null)
- out.write(ipAddress);
- out.write(thread);
- out.writeLong(time);
- out.write(objectId);
- out.close();
- } catch (IOException exc) {
- //ignore the failure, we're just trying to come up with a random seed
- }
- byte[] rand = byteOut.toByteArray();
-
- SecureRandom randomizer = new SecureRandom(rand);
- randomizer.nextBytes(address);
-
- // set the MSB of the first octet to 1 to distinguish from IEEE node addresses
- address[0] = (byte) (address[0] | (byte) 0x80);
-
- return address;
- }
-
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (!(obj instanceof UniversalUniqueIdentifier))
- return false;
-
- byte[] other = ((UniversalUniqueIdentifier) obj).fBits;
- if (fBits == other)
- return true;
- if (fBits.length != other.length)
- return false;
- for (int i = 0; i < fBits.length; i++) {
- if (fBits[i] != other[i])
- return false;
- }
- return true;
- }
-
- /**
- Answers the IP address of the local machine using the
- Java API class <code>InetAddress</code>.
-
- @return byte[] the network address in network order
- @see java.net.InetAddress#getLocalHost()
- @see java.net.InetAddress#getAddress()
- */
- protected static byte[] getIPAddress() {
- try {
- return InetAddress.getLocalHost().getAddress();
- } catch (UnknownHostException e) {
- //valid for this to be thrown be a machine with no IP connection
- //It is VERY important NOT to throw this exception
- return null;
- }
- }
-
- private static byte[] getNodeAddress() {
- return nodeAddress;
- }
-
- public int hashCode() {
- return fBits[0] + fBits[3] + fBits[7] + fBits[11] + fBits[15];
- }
-
- private static int nextClockSequence() {
-
- if (fgClockSequence == -1)
- fgClockSequence = (int) (fgRandomNumberGenerator.nextDouble() * MAX_CLOCK_SEQUENCE);
-
- fgClockSequence = (fgClockSequence + 1) % MAX_CLOCK_SEQUENCE;
-
- return fgClockSequence;
- }
-
- private static BigInteger nextTimestamp() {
-
- BigInteger timestamp = clockValueNow();
- int timestampComparison;
-
- timestampComparison = timestamp.compareTo(fgPreviousClockValue);
-
- if (timestampComparison == 0) {
- if (fgClockAdjustment == MAX_CLOCK_ADJUSTMENT) {
- while (timestamp.compareTo(fgPreviousClockValue) == 0)
- timestamp = clockValueNow();
- timestamp = nextTimestamp();
- } else
- fgClockAdjustment++;
- } else {
- fgClockAdjustment = 0;
-
- if (timestampComparison < 0)
- nextClockSequence();
- }
-
- return timestamp;
- }
-
- private void setClockSequence(int clockSeq) {
- int clockSeqHigh = (clockSeq >>> ShiftByte) & LOW_NIBBLE_MASK;
- int reserved = fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] & HIGH_NIBBLE_MASK;
-
- fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] = (byte) (reserved | clockSeqHigh);
- fBits[CLOCK_SEQUENCE_LOW] = (byte) (clockSeq & BYTE_MASK);
- }
-
- protected void setNode(byte[] bytes) {
-
- for (int index = 0; index < NODE_ADDRESS_BYTE_SIZE; index++)
- fBits[index + NODE_ADDRESS_START] = bytes[index];
- }
-
- private void setTimestamp(BigInteger timestamp) {
- BigInteger value = timestamp;
- BigInteger bigByte = BigInteger.valueOf(256L);
- BigInteger[] results;
- int version;
- int timeHigh;
-
- for (int index = TIME_FIELD_START; index < TIME_FIELD_STOP; index++) {
- results = value.divideAndRemainder(bigByte);
- value = results[0];
- fBits[index] = (byte) results[1].intValue();
- }
- version = fBits[TIME_HIGH_AND_VERSION] & HIGH_NIBBLE_MASK;
- timeHigh = value.intValue() & LOW_NIBBLE_MASK;
- fBits[TIME_HIGH_AND_VERSION] = (byte) (timeHigh | version);
- }
-
- protected synchronized void setTimeValues() {
- this.setTimestamp(timestamp());
- this.setClockSequence(fgClockSequence);
- }
-
- protected int setVariant(int variantIdentifier) {
- int clockSeqHigh = fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] & LOW_NIBBLE_MASK;
- int variant = variantIdentifier & LOW_NIBBLE_MASK;
-
- fBits[CLOCK_SEQUENCE_HIGH_AND_RESERVED] = (byte) ((variant << SHIFT_NIBBLE) | clockSeqHigh);
- return (variant);
- }
-
- protected void setVersion(int versionIdentifier) {
- int timeHigh = fBits[TIME_HIGH_AND_VERSION] & LOW_NIBBLE_MASK;
- int version = versionIdentifier & LOW_NIBBLE_MASK;
-
- fBits[TIME_HIGH_AND_VERSION] = (byte) (timeHigh | (version << SHIFT_NIBBLE));
- }
-
- private static BigInteger timestamp() {
- BigInteger timestamp;
-
- if (fgPreviousClockValue == null) {
- fgClockAdjustment = 0;
- nextClockSequence();
- timestamp = clockValueNow();
- } else
- timestamp = nextTimestamp();
-
- fgPreviousClockValue = timestamp;
- return fgClockAdjustment == 0 ? timestamp : timestamp.add(BigInteger.valueOf(fgClockAdjustment));
- }
-
- /**
- This representation is compatible with the (byte[]) constructor.
-
- @see #UniversalUniqueIdentifier(byte[])
- */
- public byte[] toBytes() {
- byte[] result = new byte[fBits.length];
-
- System.arraycopy(fBits, 0, result, 0, fBits.length);
- return result;
- }
-
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < fBits.length; i++)
- appendByteString(buffer, fBits[i]);
- return buffer.toString();
- }
-
- public String toStringAsBytes() {
- String result = "{"; //$NON-NLS-1$
-
- for (int i = 0; i < fBits.length; i++) {
- result += fBits[i];
- if (i < fBits.length + 1)
- result += ","; //$NON-NLS-1$
- }
- return result + "}"; //$NON-NLS-1$
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/Messages.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/Messages.java
deleted file mode 100644
index 6d35da258..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/Messages.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008, 2009 IBM Corporation and others. All rights reserved. This
- * program and the accompanying materials are made available under the terms of
- * the Eclipse Public License v1.0 which accompanies this distribution, and is
- * available at http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: IBM Corporation - initial API and implementation
- ******************************************************************************/
-package org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing.messages"; //$NON-NLS-1$
- public static String cannot_get_extension;
- public static String cannot_instantiate_step;
- public static String ZipVerifierStep_invalid_archive;
- public static String processing_step_results;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- //
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java
deleted file mode 100644
index c0e4858ec..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStep.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*******************************************************************************
-* Copyright (c) 2007, 2009 compeople AG and others.
-* All rights reserved. This program and the accompanying materials
-* are made available under the terms of the Eclipse Public License v1.0
-* which accompanies this distribution, and is available at
-* http://www.eclipse.org/legal/epl-v10.html
-*
-* Contributors:
-* compeople AG (Stefan Liebig) - initial API and implementation
-* IBM Corporation - continuing development
-*******************************************************************************/
-package org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.provisional.p2.repository.IStateful;
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor;
-
-/**
- * ProcessingSteps process the data written to them and pass the resultant data on
- * to a configured destination stream. Steps may monitor (e.g., count) the data, compute information
- * about the data (e.g., checksum or hash) or transform the data (e.g., unpack200).
- */
-public abstract class ProcessingStep extends OutputStream implements IStateful {
-
- private OutputStream destination;
- private IProgressMonitor monitor;
- private IStatus status = Status.OK_STATUS;
-
- protected ProcessingStep() {
- super();
- }
-
- /**
- * Initialize this processing step according to the information in the given
- * descriptor and context. After initialization, this step is ready for linking
- * with other steps or output streams
- * @param descriptor description of the step
- * @param context the context in which the step is being used
- */
- public void initialize(IProvisioningAgent agent, IProcessingStepDescriptor descriptor, IArtifactDescriptor context) {
- // nothing to do here!
- }
-
- /**
- * Link this step with the given output stream and configure the step to use the given
- * progress monitor. After linking the step is ready to have data written to it.
- * @param destination the stream into which to write the processed data
- * @param monitor the progress monitor to use for reporting activity
- */
- public void link(OutputStream destination, IProgressMonitor monitor) {
- this.destination = destination;
- this.monitor = monitor;
- }
-
- /**
- * Process the given byte and pass the result on to the configured destination stream
- * @param b the byte being written
- */
- public void write(int b) throws IOException {
- // nothing to do here!
- }
-
- /**
- * Flush any unwritten data from this stream.
- */
- public void flush() throws IOException {
- super.flush();
- if (destination != null)
- destination.flush();
- }
-
- /**
- * Close this stream and, if the configured destination is a ProcessingStep,
- * close it as well. Typically a chain of steps terminates in a conventional
- * output stream. Implementors of this method should ensure they set the
- * status of the step.
- */
- public void close() throws IOException {
- super.close();
- if (destination instanceof ProcessingStep)
- destination.close();
- monitor = null;
- }
-
- public IStatus getStatus() {
- return status;
- }
-
- public void setStatus(IStatus value) {
- if (value == null)
- value = Status.OK_STATUS;
- if (status != null && status.getSeverity() >= value.getSeverity())
- return;
- status = value;
- }
-
- /**
- * Get the progress monitor.
- * @return the progress monitor; may be null
- */
- protected IProgressMonitor getProgressMonitor() {
- return monitor;
- }
-
- /**
- * Get the stream to write the processed data into.
- *
- * @return output stream for processed data
- */
- protected OutputStream getDestination() {
- return destination;
- }
-
- /**
- * Return the status of this step. The status will be <code>null</code> if the
- * step has not yet executed. If the step has executed the returned status
- * indicates the success or failure of the step.
- * @param deep whether or not to aggregate the status of any linked steps
- * @return the requested status
- */
- public IStatus getStatus(boolean deep) {
- return ProcessingStepHandler.getStatus(this, deep);
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java
deleted file mode 100644
index e5530e937..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ProcessingStepHandler.java
+++ /dev/null
@@ -1,205 +0,0 @@
-/*******************************************************************************
-* Copyright (c) 2007, 2009 compeople AG and others.
-* All rights reserved. This program and the accompanying materials
-* are made available under the terms of the Eclipse Public License v1.0
-* which accompanies this distribution, and is available at
-* http://www.eclipse.org/legal/epl-v10.html
-*
-* Contributors:
-* compeople AG (Stefan Liebig) - initial API and implementation
-* IBM - continuing development
-*******************************************************************************/
-package org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing;
-
-import java.io.OutputStream;
-import java.util.ArrayList;
-import org.eclipse.core.runtime.*;
-import org.eclipse.equinox.internal.p2.artifact.repository.Activator;
-import org.eclipse.equinox.internal.p2.artifact.repository.simple.SimpleArtifactRepository.ArtifactOutputStream;
-import org.eclipse.equinox.internal.provisional.p2.repository.IStateful;
-import org.eclipse.equinox.p2.core.IProvisioningAgent;
-import org.eclipse.equinox.p2.repository.artifact.IArtifactDescriptor;
-import org.eclipse.equinox.p2.repository.artifact.IProcessingStepDescriptor;
-import org.eclipse.osgi.util.NLS;
-
-/**
- * Creates processing step instances from extensions and executes them.
- */
-public class ProcessingStepHandler {
-
- private static final String PROCESSING_STEPS_EXTENSION_ID = "org.eclipse.equinox.p2.artifact.repository.processingSteps"; //$NON-NLS-1$
-
- //TODO This method can go
- public static IStatus checkStatus(OutputStream output) {
- return getStatus(output, true);
- }
-
- /**
- * Check to see that we have processors for all the steps in the given descriptor
- * @param descriptor the descriptor to check
- * @return whether or not processors for all the descriptor's steps are installed
- */
- public static boolean canProcess(IArtifactDescriptor descriptor) {
- IExtensionRegistry registry = RegistryFactory.getRegistry();
- IExtensionPoint point = registry.getExtensionPoint(PROCESSING_STEPS_EXTENSION_ID);
- if (point == null)
- return false;
- IProcessingStepDescriptor[] steps = descriptor.getProcessingSteps();
- for (int i = 0; i < steps.length; i++) {
- if (point.getExtension(steps[i].getProcessorId()) == null)
- return false;
- }
- return true;
- }
-
- /**
- * Return the status of this step. The status will be <code>null</code> if the
- * step has not yet executed. If the step has executed the returned status
- * indicates the success or failure of the step.
- * @param deep whether or not to aggregate the status of any linked steps
- * @return the requested status
- */
- public static IStatus getStatus(OutputStream stream, boolean deep) {
- if (!deep)
- return getStatus(stream);
- ArrayList<IStatus> list = new ArrayList<IStatus>();
- int severity = collectStatus(stream, list);
- if (severity == IStatus.OK)
- return Status.OK_STATUS;
- IStatus[] result = list.toArray(new IStatus[list.size()]);
- return new MultiStatus(Activator.ID, severity, result, Messages.processing_step_results, null);
- }
-
- /**
- * Return statuses from this step and any linked step, discarding OK statuses until an error status is received.
- * @param stream the stream representing the first step
- * @return the requested status
- */
- public static IStatus getErrorStatus(OutputStream stream) {
- ArrayList<IStatus> list = new ArrayList<IStatus>();
- int severity = collectErrorStatus(stream, list);
- if (severity == IStatus.OK)
- return Status.OK_STATUS;
- IStatus[] result = list.toArray(new IStatus[list.size()]);
- return new MultiStatus(Activator.ID, 0, result, Messages.processing_step_results, null);
- }
-
- private static int collectErrorStatus(OutputStream stream, ArrayList<IStatus> list) {
- IStatus status = getStatus(stream);
- if (!status.isOK())
- list.add(status);
- if (status.matches(IStatus.ERROR))
- // Errors past this should be bogus as they rely on output from this step
- return status.getSeverity();
-
- OutputStream destination = getDestination(stream);
- if (destination == null || !(destination instanceof IStateful))
- return status.getSeverity();
- int result = collectErrorStatus(destination, list);
- // TODO greater than test here is a little brittle but it is very unlikely that we will add
- // a new status severity.
- return status.getSeverity() > result ? status.getSeverity() : result;
- }
-
- public static IStatus getStatus(OutputStream stream) {
- if (stream instanceof IStateful)
- return ((IStateful) stream).getStatus();
- return Status.OK_STATUS;
- }
-
- private static int collectStatus(OutputStream stream, ArrayList<IStatus> list) {
- IStatus status = getStatus(stream);
- list.add(status);
- OutputStream destination = getDestination(stream);
- if (destination == null || !(destination instanceof IStateful))
- return status.getSeverity();
- int result = collectStatus(destination, list);
- // TODO greater than test here is a little brittle but it is very unlikely that we will add
- // a new status severity.
- return status.getSeverity() > result ? status.getSeverity() : result;
- }
-
- private static OutputStream getDestination(OutputStream stream) {
- if (stream instanceof ProcessingStep)
- return ((ProcessingStep) stream).getDestination();
- if (stream instanceof ArtifactOutputStream)
- return ((ArtifactOutputStream) stream).getDestination();
- return null;
- }
-
- public ProcessingStep[] create(IProvisioningAgent agent, IProcessingStepDescriptor[] descriptors, IArtifactDescriptor context) {
- ProcessingStep[] result = new ProcessingStep[descriptors.length];
- for (int i = 0; i < descriptors.length; i++)
- result[i] = create(agent, descriptors[i], context);
- return result;
- }
-
- public ProcessingStep create(IProvisioningAgent agent, IProcessingStepDescriptor descriptor, IArtifactDescriptor context) {
- IExtensionRegistry registry = RegistryFactory.getRegistry();
- IExtension extension = registry.getExtension(PROCESSING_STEPS_EXTENSION_ID, descriptor.getProcessorId());
- Exception error;
- if (extension != null) {
- IConfigurationElement[] config = extension.getConfigurationElements();
- try {
- Object object = config[0].createExecutableExtension("class"); //$NON-NLS-1$
- ProcessingStep step = (ProcessingStep) object;
- step.initialize(agent, descriptor, context);
- return step;
- } catch (Exception e) {
- error = e;
- }
- } else
- error = new ProcessingStepHandlerException(NLS.bind(Messages.cannot_get_extension, PROCESSING_STEPS_EXTENSION_ID, descriptor.getProcessorId()));
-
- int severity = descriptor.isRequired() ? IStatus.ERROR : IStatus.INFO;
- ProcessingStep result = new EmptyProcessingStep();
- result.setStatus(new Status(severity, Activator.ID, Messages.cannot_instantiate_step + descriptor.getProcessorId(), error));
- return result;
- }
-
- public OutputStream createAndLink(IProvisioningAgent agent, IProcessingStepDescriptor[] descriptors, IArtifactDescriptor context, OutputStream output, IProgressMonitor monitor) {
- if (descriptors == null)
- return output;
- ProcessingStep[] steps = create(agent, descriptors, context);
- return link(steps, output, monitor);
- }
-
- public OutputStream link(ProcessingStep[] steps, OutputStream output, IProgressMonitor monitor) {
- OutputStream previous = output;
- for (int i = steps.length - 1; i >= 0; i--) {
- ProcessingStep step = steps[i];
- step.link(previous, monitor);
- previous = step;
- }
- if (steps.length == 0)
- return previous;
- // now link the artifact stream to the first stream in the new chain
- ArtifactOutputStream lastLink = getArtifactStream(previous);
- if (lastLink != null)
- lastLink.setFirstLink(previous);
- return previous;
- }
-
- // Traverse the chain of processing steps and return the stream served up by
- // the artifact repository or null if one cannot be found.
- private ArtifactOutputStream getArtifactStream(OutputStream stream) {
- OutputStream current = stream;
- while (current instanceof ProcessingStep)
- current = ((ProcessingStep) current).getDestination();
- if (current instanceof ArtifactOutputStream)
- return (ArtifactOutputStream) current;
- return null;
- }
-
- protected static final class EmptyProcessingStep extends ProcessingStep {
- // Just to hold the status
- }
-
- protected static final class ProcessingStepHandlerException extends Exception {
- private static final long serialVersionUID = 1L;
-
- public ProcessingStepHandlerException(String message) {
- super(message);
- }
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ZipVerifierStep.java b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ZipVerifierStep.java
deleted file mode 100644
index a649b0c23..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/ZipVerifierStep.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2008 IBM Corporation and others. All rights reserved. This
- * program and the accompanying materials are made available under the terms of
- * the Eclipse Public License v1.0 which accompanies this distribution, and is
- * available at http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors: IBM Corporation - initial API and implementation
- ******************************************************************************/
-package org.eclipse.equinox.internal.provisional.p2.artifact.repository.processing;
-
-import java.io.IOException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.equinox.internal.p2.artifact.repository.Activator;
-
-public class ZipVerifierStep extends ProcessingStep {
- static final int[] ZIP_HEADER = new int[] {0x50, 0x4b, 0x03, 0x04};
-
- private int valid = 0; //-1 indicates that it is not a zip, >3 indicates that we are done the verification
-
- public void write(int b) throws IOException {
- getDestination().write(b);
- if (valid > 3)
- return;
- if (valid == -1) {
- return;
- }
- if (b != ZIP_HEADER[valid++]) {
- valid = -1;
- setStatus(new Status(IStatus.ERROR, Activator.ID, Messages.ZipVerifierStep_invalid_archive));
- return;
- }
- }
-
- public void close() throws IOException {
- if (valid > 3) {
- setStatus(Status.OK_STATUS);
- } else {
- setStatus(new Status(IStatus.ERROR, Activator.ID, Messages.ZipVerifierStep_invalid_archive));
- }
- super.close();
- }
-}
diff --git a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/messages.properties b/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/messages.properties
deleted file mode 100644
index 9459df431..000000000
--- a/bundles/org.eclipse.equinox.p2.artifact.repository/src/org/eclipse/equinox/internal/provisional/p2/artifact/repository/processing/messages.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-cannot_instantiate_step=Could not instantiate step:
-###############################################################################
-# Copyright (c) 2007, 2009 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-cannot_get_extension=Could not get extension {0} for descriptor id {1}.
-ZipVerifierStep_invalid_archive=Downloaded stream not a valid archive. Check the server.
-processing_step_results=Result of processing steps. \ No newline at end of file

Back to the top