<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.aries.application.management.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;

import org.apache.aries.application.ApplicationMetadata;
import org.apache.aries.application.ApplicationMetadataFactory;
import org.apache.aries.application.DeploymentMetadata;
import org.apache.aries.application.DeploymentMetadataFactory;
import org.apache.aries.application.filesystem.IDirectory;
import org.apache.aries.application.filesystem.IFile;
import org.apache.aries.application.management.AriesApplication;
import org.apache.aries.application.management.AriesApplicationContext;
import org.apache.aries.application.management.AriesApplicationListener;
import org.apache.aries.application.management.AriesApplicationManager;
import org.apache.aries.application.management.BundleInfo;
import org.apache.aries.application.management.ManagementException;
import org.apache.aries.application.management.ResolveConstraint;
import org.apache.aries.application.management.ResolverException;
import org.apache.aries.application.management.UpdateException;
import org.apache.aries.application.management.internal.MessageUtil;
import org.apache.aries.application.management.repository.ApplicationRepository;
import org.apache.aries.application.management.spi.convert.BundleConversion;
import org.apache.aries.application.management.spi.convert.BundleConverter;
import org.apache.aries.application.management.spi.convert.ConversionException;
import org.apache.aries.application.management.spi.repository.BundleRepository;
import org.apache.aries.application.management.spi.resolve.DeploymentManifestManager;
import org.apache.aries.application.management.spi.runtime.AriesApplicationContextManager;
import org.apache.aries.application.management.spi.runtime.LocalPlatform;
import org.apache.aries.application.utils.AppConstants;
import org.apache.aries.application.utils.filesystem.FileSystem;
import org.apache.aries.application.utils.filesystem.IOUtils;
import org.apache.aries.application.utils.management.SimpleBundleInfo;
import org.apache.aries.application.utils.manifest.BundleManifest;
import org.apache.aries.application.utils.manifest.ManifestDefaultsInjector;
import org.apache.aries.application.utils.manifest.ManifestProcessor;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AriesApplicationManagerImpl implements AriesApplicationManager {

  private ApplicationMetadataFactory _applicationMetadataFactory;
  private DeploymentMetadataFactory _deploymentMetadataFactory;
  private List<BundleConverter> _bundleConverters;

  private LocalPlatform _localPlatform;
  private AriesApplicationContextManager _applicationContextManager;
  private BundleContext _bundleContext;

  private DeploymentManifestManager deploymentManifestManager;
  
  private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.application.management.impl");

  public void setApplicationMetadataFactory (ApplicationMetadataFactory amf) { 
    _applicationMetadataFactory = amf;
  }
  
  public void setDeploymentMetadataFactory (DeploymentMetadataFactory dmf) { 
    _deploymentMetadataFactory = dmf;
  }
  
  public void setBundleConverters (List<BundleConverter> bcs) { 
    _bundleConverters = bcs;
  }
  
  public void setDeploymentManifestManager(DeploymentManifestManager dm) {
    this.deploymentManifestManager = dm;
  }

  public void setLocalPlatform (LocalPlatform lp) { 
    _localPlatform = lp;
  }
  
  public void setApplicationContextManager (AriesApplicationContextManager acm) { 
    _applicationContextManager = acm;
  }
  
  public void setBundleContext(BundleContext b)
  {
    _bundleContext = b;
  }
  
  
  /**
   * Create an AriesApplication from a .eba file: a zip file with a '.eba' extension
   */
  public AriesApplication createApplication(IDirectory ebaFile) throws ManagementException {
    ApplicationMetadata applicationMetadata = null;
    DeploymentMetadata deploymentMetadata = null;
    Map<String, BundleConversion> modifiedBundles = new HashMap<String, BundleConversion>();
    AriesApplicationImpl application = null;
    String appPath = ebaFile.toString();
    try {   
      // try to read the app name out of the application.mf
      Manifest applicationManifest = parseApplicationManifest (ebaFile);
      String appName = applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_NAME);

      //If the application name is null, we will try to get the file name.
      if (appName == null || appName.isEmpty()) {
          String fullPath = appPath;
          if (fullPath.endsWith("/")) {
            fullPath = fullPath.substring(0, fullPath.length() -1);  
          }
              
          int last_slash = fullPath.lastIndexOf("/");
          appName = fullPath.substring(last_slash + 1, fullPath.length()); 
      }
                  
      IFile deploymentManifest = ebaFile.getFile(AppConstants.DEPLOYMENT_MF);
      /* We require that all other .jar and .war files included by-value be valid bundles
       * because a DEPLOYMENT.MF has been provided. If no DEPLOYMENT.MF, migrate 
       * wars to wabs, plain jars to bundles
       */
      Set<BundleInfo> extraBundlesInfo = new HashSet<BundleInfo>();
      for (IFile f : ebaFile) { 
        if (f.isDirectory()) { 
          continue;
        }
        BundleManifest bm = getBundleManifest (f);
        if (bm != null) {
          if (bm.isValid()) {
            extraBundlesInfo.add(new SimpleBundleInfo(bm, f.toURL().toExternalForm()));
          } else if (deploymentManifest == null) { 
            // We have a jar that needs converting to a bundle, or a war to migrate to a WAB 
            // We only do this if a DEPLOYMENT.MF does not exist.
            BundleConversion convertedBinary = null;
            Iterator<BundleConverter> converters = _bundleConverters.iterator();
            List<ConversionException> conversionExceptions = Collections.emptyList();
            while (converters.hasNext() && convertedBinary == null) { 
              try {
                convertedBinary = converters.next().convert(ebaFile, f);
              } catch (ServiceException sx) {
                // We'll get this if our optional BundleConverter has not been injected. 
              } catch (ConversionException cx) { 
                conversionExceptions.add(cx);
              }
            }
            if (conversionExceptions.size() > 0) {
              for (ConversionException cx : conversionExceptions) { 
                _logger.error("APPMANAGEMENT0004E", new Object[]{f.getName(), appName, cx});
              }
              throw new ManagementException (MessageUtil.getMessage("APPMANAGEMENT0005E", appName));
            }
            if (convertedBinary != null) { 
              modifiedBundles.put (f.getName(), convertedBinary);             
              extraBundlesInfo.add(convertedBinary.getBundleInfo());
            } 
          }
        } 
      }
 
      // if Application-Content header was not specified build it based on the bundles included by value
      if (applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_CONTENT) == null) {<commit_msg>ARIES-638: Logging improvements for AriesApplicationManagerImpl<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIESOR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.aries.application.management.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;

import org.apache.aries.application.ApplicationMetadata;
import org.apache.aries.application.ApplicationMetadataFactory;
import org.apache.aries.application.DeploymentMetadata;
import org.apache.aries.application.DeploymentMetadataFactory;
import org.apache.aries.application.filesystem.IDirectory;
import org.apache.aries.application.filesystem.IFile;
import org.apache.aries.application.management.AriesApplication;
import org.apache.aries.application.management.AriesApplicationContext;
import org.apache.aries.application.management.AriesApplicationListener;
import org.apache.aries.application.management.AriesApplicationManager;
import org.apache.aries.application.management.BundleInfo;
import org.apache.aries.application.management.ManagementException;
import org.apache.aries.application.management.ResolveConstraint;
import org.apache.aries.application.management.ResolverException;
import org.apache.aries.application.management.UpdateException;
import org.apache.aries.application.management.internal.MessageUtil;
import org.apache.aries.application.management.repository.ApplicationRepository;
import org.apache.aries.application.management.spi.convert.BundleConversion;
import org.apache.aries.application.management.spi.convert.BundleConverter;
import org.apache.aries.application.management.spi.convert.ConversionException;
import org.apache.aries.application.management.spi.repository.BundleRepository;
import org.apache.aries.application.management.spi.resolve.DeploymentManifestManager;
import org.apache.aries.application.management.spi.runtime.AriesApplicationContextManager;
import org.apache.aries.application.management.spi.runtime.LocalPlatform;
import org.apache.aries.application.utils.AppConstants;
import org.apache.aries.application.utils.filesystem.FileSystem;
import org.apache.aries.application.utils.filesystem.IOUtils;
import org.apache.aries.application.utils.management.SimpleBundleInfo;
import org.apache.aries.application.utils.manifest.BundleManifest;
import org.apache.aries.application.utils.manifest.ManifestDefaultsInjector;
import org.apache.aries.application.utils.manifest.ManifestProcessor;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceException;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AriesApplicationManagerImpl implements AriesApplicationManager {

  private ApplicationMetadataFactory _applicationMetadataFactory;
  private DeploymentMetadataFactory _deploymentMetadataFactory;
  private List<BundleConverter> _bundleConverters;

  private LocalPlatform _localPlatform;
  private AriesApplicationContextManager _applicationContextManager;
  private BundleContext _bundleContext;

  private DeploymentManifestManager deploymentManifestManager;
  
  private static final Logger _logger = LoggerFactory.getLogger("org.apache.aries.application.management.impl");

  public void setApplicationMetadataFactory (ApplicationMetadataFactory amf) { 
    _applicationMetadataFactory = amf;
  }
  
  public void setDeploymentMetadataFactory (DeploymentMetadataFactory dmf) { 
    _deploymentMetadataFactory = dmf;
  }
  
  public void setBundleConverters (List<BundleConverter> bcs) { 
    _bundleConverters = bcs;
  }
  
  public void setDeploymentManifestManager(DeploymentManifestManager dm) {
    this.deploymentManifestManager = dm;
  }

  public void setLocalPlatform (LocalPlatform lp) { 
    _localPlatform = lp;
  }
  
  public void setApplicationContextManager (AriesApplicationContextManager acm) { 
    _applicationContextManager = acm;
  }
  
  public void setBundleContext(BundleContext b)
  {
    _bundleContext = b;
  }
  
  
  /**
   * Create an AriesApplication from a .eba file: a zip file with a '.eba' extension
   */
  public AriesApplication createApplication(IDirectory ebaFile) throws ManagementException {
    ApplicationMetadata applicationMetadata = null;
    DeploymentMetadata deploymentMetadata = null;
    Map<String, BundleConversion> modifiedBundles = new HashMap<String, BundleConversion>();
    AriesApplicationImpl application = null;
    String appPath = ebaFile.toString();
    try {   
      // try to read the app name out of the application.mf
      Manifest applicationManifest = parseApplicationManifest (ebaFile);
      String appName = applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_NAME);

      //If the application name is null, we will try to get the file name.
      if (appName == null || appName.isEmpty()) {
          String fullPath = appPath;
          if (fullPath.endsWith("/")) {
            fullPath = fullPath.substring(0, fullPath.length() -1);  
          }
              
          int last_slash = fullPath.lastIndexOf("/");
          appName = fullPath.substring(last_slash + 1, fullPath.length()); 
      }
                  
      IFile deploymentManifest = ebaFile.getFile(AppConstants.DEPLOYMENT_MF);
      /* We require that all other .jar and .war files included by-value be valid bundles
       * because a DEPLOYMENT.MF has been provided. If no DEPLOYMENT.MF, migrate 
       * wars to wabs, plain jars to bundles
       */
      Set<BundleInfo> extraBundlesInfo = new HashSet<BundleInfo>();
      for (IFile f : ebaFile) { 
        if (f.isDirectory()) { 
          continue;
        }
        BundleManifest bm = getBundleManifest (f);
        if (bm != null) {
          if (bm.isValid()) {
            _logger.debug("File {} is a valid bundle. Adding it to bundle list.", f.getName());
            extraBundlesInfo.add(new SimpleBundleInfo(bm, f.toURL().toExternalForm()));
          } else if (deploymentManifest == null) { 
            _logger.debug("File {} is not a valid bundle. Attempting to convert it.", f.getName());
            // We have a jar that needs converting to a bundle, or a war to migrate to a WAB 
            // We only do this if a DEPLOYMENT.MF does not exist.
            BundleConversion convertedBinary = null;
            Iterator<BundleConverter> converters = _bundleConverters.iterator();
            List<ConversionException> conversionExceptions = Collections.emptyList();
            while (converters.hasNext() && convertedBinary == null) { 
              try {
            	BundleConverter converter = converters.next();
            	_logger.debug("Converting file using {} converter", converter);
                convertedBinary = converter.convert(ebaFile, f);
              } catch (ServiceException sx) {
                // We'll get this if our optional BundleConverter has not been injected. 
              } catch (ConversionException cx) { 
                conversionExceptions.add(cx);
              }
            }
            if (conversionExceptions.size() > 0) {
              for (ConversionException cx : conversionExceptions) { 
                _logger.error("APPMANAGEMENT0004E", new Object[]{f.getName(), appName, cx});
              }
              throw new ManagementException (MessageUtil.getMessage("APPMANAGEMENT0005E", appName));
            }
            if (convertedBinary != null) { 
              _logger.debug("File {} was successfully converted. Adding it to bundle list.", f.getName());
              modifiedBundles.put (f.getName(), convertedBinary);             
              extraBundlesInfo.add(convertedBinary.getBundleInfo());
            } else {
              _logger.debug("File {} was not converted.", f.getName());
            }
          } else {
            _logger.debug("File {} was ignored. It is not a valid bundle and DEPLOYMENT.MF is present", f.getName());
          }
        } else {
          _logger.debug("File {} was ignored. It has no manifest file.", f.getName());
        }
      }
 
      // if Application-Content header was not specified build it based on the bundles included by value
      if (applicationManifest.getMainAttributes().getValue(AppConstants.APPLICATION_CONTENT) == null) {
{'fraction_non_alphanumeric': 0.0859461863464532, 'fraction_numerical': 0.0021681120747164776, 'mean_word_length': 3.676111255523785, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6895406', 'n_tokens_mistral': 4687, 'n_tokens_neox': 4579, 'n_words': 1189}