/** {@inheritDoc} */
 public ClassSpec getClassSpec(final String name) throws IOException {
   final VirtualFile file = root.getChild(name);
   if (!file.exists()) {
     return null;
   }
   final long size = file.getSize();
   final ClassSpec spec = new ClassSpec();
   final InputStream is = file.openStream();
   try {
     if (size <= (long) Integer.MAX_VALUE) {
       final int castSize = (int) size;
       byte[] bytes = new byte[castSize];
       int a = 0, res;
       while ((res = is.read(bytes, a, castSize - a)) > 0) {
         a += res;
       }
       // done
       is.close();
       spec.setBytes(bytes);
       spec.setCodeSource(new CodeSource(rootUrl, file.getCodeSigners()));
       return spec;
     } else {
       throw ServerMessages.MESSAGES.resourceTooLarge();
     }
   } finally {
     VFSUtils.safeClose(is);
   }
 }
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
      return;
    }
    final ResourceRoot deploymentRoot =
        deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT);
    final VirtualFile deploymentFile = deploymentRoot.getRoot();
    final VirtualFile applicationXmlFile = deploymentFile.getChild(JBOSS_APP_XML);
    if (!applicationXmlFile.exists()) {
      return;
    }

    InputStream inputStream = null;
    try {
      inputStream = applicationXmlFile.openStream();
      final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
      inputFactory.setXMLResolver(NoopXmlResolver.create());
      XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(inputStream);
      final JBossAppMetaData appMetaData = JBossAppMetaDataParser.parse(xmlReader);
      if (appMetaData != null) {
        final EarMetaData earMetaData = deploymentUnit.getAttachment(Attachments.EAR_METADATA);
        if (earMetaData != null) {
          JBossAppMetaDataMerger.merge(appMetaData, null, earMetaData);
        }
        deploymentUnit.putAttachment(Attachments.JBOSS_APP_METADATA, appMetaData);
      }
    } catch (Exception e) {
      throw new DeploymentUnitProcessingException("Failed to parse " + applicationXmlFile, e);
    } finally {
      VFSUtils.safeClose(inputStream);
    }
  }
 /** {@inheritDoc} */
 public Resource getResource(final String name) {
   try {
     final VirtualFile file = root.getChild(PathUtils.canonicalize(name));
     if (!file.exists()) {
       return null;
     }
     return new VFSEntryResource(file, file.toURL());
   } catch (MalformedURLException e) {
     // must be invalid...?  (todo: check this out)
     return null;
   }
 }
 /**
  * Batch deployments must have a {@code META-INF/batch.xml} and/or XML configuration files in
  * {@code META-INF/batch-jobs}. They must be in an EJB JAR or a WAR.
  *
  * @param deploymentUnit the deployment unit to check
  * @return {@code true} if a {@code META-INF/batch.xml} or a non-empty {@code META-INF/batch-jobs}
  *     directory was found otherwise {@code false}
  */
 private boolean isBatchDeployment(final DeploymentUnit deploymentUnit) {
   // Section 10.7 of JSR 352 discusses valid packaging types, of which it appears EAR should be
   // one. It seems
   // though that it's of no real use as 10.5 and 10.6 seem to indicate it must be in
   // META-INF/batch-jobs of a JAR
   // and WEB-INF/classes/META-INF/batch-jobs of a WAR.
   if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)
       || !deploymentUnit.hasAttachment(Attachments.DEPLOYMENT_ROOT)) {
     return false;
   }
   final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
   final VirtualFile metaInf;
   if (DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
     metaInf = root.getRoot().getChild("WEB-INF/classes/META-INF");
   } else {
     metaInf = root.getRoot().getChild("META-INF");
   }
   final VirtualFile jobXmlFile = metaInf.getChild("batch.xml");
   final VirtualFile batchJobsDir = metaInf.getChild("batch-jobs");
   return (jobXmlFile.exists()
       || (batchJobsDir.exists() && !batchJobsDir.getChildren().isEmpty()));
 }
  @Test
  public void testLoadCorrectJbossWeb() throws Exception {
    final VirtualFile jbossWebxml = mock(VirtualFile.class);
    when(jbossWebxml.exists()).thenReturn(Boolean.TRUE);
    when(jbossWebxml.openStream())
        .thenReturn(
            JBossWebParsingDeploymentProcessorTest.class.getResourceAsStream("jboss-web.xml"));

    final VirtualFile deploymentRoot = mock(VirtualFile.class);
    when(deploymentRoot.getChild("WEB-INF/jboss-web.xml")).thenReturn(jbossWebxml);

    final ResourceRoot resourceRoot = mock(ResourceRoot.class);
    when(resourceRoot.getRoot()).thenReturn(deploymentRoot);
    when(deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT))
        .thenReturn(resourceRoot);
    processor.deploy(phaseContext);
  }
  /**
   * Process a deployment for jboss-service.xml files. Will parse the xml file and attach a
   * configuration discovered during processing.
   *
   * @param phaseContext the deployment unit context
   * @throws DeploymentUnitProcessingException
   */
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

    final VirtualFile deploymentRoot =
        phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();

    if (deploymentRoot == null || !deploymentRoot.exists()) return;

    VirtualFile serviceXmlFile = null;
    if (deploymentRoot.isDirectory()) {
      serviceXmlFile = deploymentRoot.getChild(SERVICE_DESCRIPTOR_PATH);
    } else if (deploymentRoot
        .getName()
        .toLowerCase(Locale.ENGLISH)
        .endsWith(SERVICE_DESCRIPTOR_SUFFIX)) {
      serviceXmlFile = deploymentRoot;
    }
    if (serviceXmlFile == null || !serviceXmlFile.exists()) return;

    final XMLMapper xmlMapper = XMLMapper.Factory.create();
    final JBossServiceXmlDescriptorParser jBossServiceXmlDescriptorParser =
        new JBossServiceXmlDescriptorParser(
            JBossDescriptorPropertyReplacement.propertyReplacer(phaseContext.getDeploymentUnit()));
    xmlMapper.registerRootElement(
        new QName("urn:jboss:service:7.0", "server"), jBossServiceXmlDescriptorParser);
    xmlMapper.registerRootElement(new QName(null, "server"), jBossServiceXmlDescriptorParser);

    InputStream xmlStream = null;
    try {
      xmlStream = serviceXmlFile.openStream();
      final XMLStreamReader reader = inputFactory.createXMLStreamReader(xmlStream);
      final ParseResult<JBossServiceXmlDescriptor> result =
          new ParseResult<JBossServiceXmlDescriptor>();
      xmlMapper.parseDocument(result, reader);
      final JBossServiceXmlDescriptor xmlDescriptor = result.getResult();
      if (xmlDescriptor != null)
        phaseContext
            .getDeploymentUnit()
            .putAttachment(JBossServiceXmlDescriptor.ATTACHMENT_KEY, xmlDescriptor);
      else throw SarMessages.MESSAGES.failedXmlParsing(serviceXmlFile);
    } catch (Exception e) {
      throw SarMessages.MESSAGES.failedXmlParsing(e, serviceXmlFile);
    } finally {
      VFSUtils.safeClose(xmlStream);
    }
  }
  private static PersistenceUnitMetadata getPersistenceUnit(
      DeploymentUnit current, final String absolutePath, String puName) {
    final String path;
    if (absolutePath.startsWith("../")) {
      path = absolutePath.substring(3);
    } else {
      path = absolutePath;
    }
    final VirtualFile parent =
        current.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot().getParent();
    final VirtualFile resolvedPath = parent.getChild(path);

    List<ResourceRoot> resourceRoots =
        DeploymentUtils.allResourceRoots(DeploymentUtils.getTopDeploymentUnit(current));

    for (ResourceRoot resourceRoot : resourceRoots) {
      if (resourceRoot.getRoot().equals(resolvedPath)) {
        PersistenceUnitMetadataHolder holder =
            resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
        if (holder != null) {
          for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
            if (traceEnabled) {
              ROOT_LOGGER.tracef(
                  "getPersistenceUnit check '%s' against pu '%s'",
                  puName, pu.getPersistenceUnitName());
            }
            if (pu.getPersistenceUnitName().equals(puName)) {
              if (traceEnabled) {
                ROOT_LOGGER.tracef(
                    "getPersistenceUnit matched '%s' against pu '%s'",
                    puName, pu.getPersistenceUnitName());
              }
              return pu;
            }
          }
        }
      }
    }

    throw MESSAGES.persistenceUnitNotFound(absolutePath, puName, current);
  }
  @Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

    // Check if we already have an OSGi deployment
    DeploymentUnit depUnit = phaseContext.getDeploymentUnit();
    if (depUnit.hasAttachment(OSGiConstants.OSGI_METADATA_KEY)) return;

    // Get the OSGi XService properties
    VirtualFile virtualFile = depUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    VirtualFile xserviceFile = virtualFile.getChild(XSERVICE_PROPERTIES_NAME);
    if (xserviceFile.exists() == false) return;

    try {
      Properties props = new Properties();
      props.load(xserviceFile.openStream());
      OSGiMetaData metadata = OSGiMetaDataBuilder.load(props);
      depUnit.putAttachment(OSGiConstants.OSGI_METADATA_KEY, metadata);
    } catch (IOException ex) {
      throw MESSAGES.cannotParseOSGiMetadata(ex, xserviceFile);
    }
  }
  /**
   * Process a deployment for standard ra deployment files. Will parse the xml file and attach an
   * configuration discovered during processing.
   *
   * @param phaseContext the deployment unit context
   * @throws DeploymentUnitProcessingException
   */
  @Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot =
        phaseContext.getDeploymentUnit().getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();

    if (deploymentRoot == null || !deploymentRoot.exists()) return;

    final String deploymentRootName = deploymentRoot.getLowerCaseName();
    if (!deploymentRootName.endsWith(".rar")) {
      return;
    }

    VirtualFile serviceXmlFile = deploymentRoot.getChild("/META-INF/ra.xml");

    InputStream xmlStream = null;
    Connector result = null;
    try {
      if (serviceXmlFile != null && serviceXmlFile.exists()) {

        xmlStream = serviceXmlFile.openStream();
        result = (new RaParser()).parse(xmlStream);
        if (result == null) throw MESSAGES.failedToParseServiceXml(serviceXmlFile);
      }
      File root = deploymentRoot.getPhysicalFile();
      URL url = root.toURI().toURL();
      String deploymentName = deploymentRootName.substring(0, deploymentRootName.indexOf(".rar"));
      ConnectorXmlDescriptor xmlDescriptor =
          new ConnectorXmlDescriptor(result, root, url, deploymentName);
      phaseContext
          .getDeploymentUnit()
          .putAttachment(ConnectorXmlDescriptor.ATTACHMENT_KEY, xmlDescriptor);

    } catch (Exception e) {
      throw MESSAGES.failedToParseServiceXml(e, serviceXmlFile);
    } finally {
      VFSUtils.safeClose(xmlStream);
    }
  }
  @Test
  public void testLoadIncorrectJbossWeb() throws Exception {
    expectedException.expect(DeploymentUnitProcessingException.class);
    expectedException.expectMessage(
        "JBAS018014: Failed to parse XML descriptor \"/content/basic.war/WEB-INF/jboss-web.xml\" at [4,5]");

    final VirtualFile jbossWebxml = mock(VirtualFile.class);
    when(jbossWebxml.exists()).thenReturn(Boolean.TRUE);
    when(jbossWebxml.openStream())
        .thenReturn(
            JBossWebParsingDeploymentProcessorTest.class.getResourceAsStream(
                "jboss-error-web.xml"));
    when(jbossWebxml.toString()).thenReturn("\"/content/basic.war/WEB-INF/jboss-web.xml\"");

    final VirtualFile deploymentRoot = mock(VirtualFile.class);
    when(deploymentRoot.getChild("WEB-INF/jboss-web.xml")).thenReturn(jbossWebxml);

    final ResourceRoot resourceRoot = mock(ResourceRoot.class);
    when(resourceRoot.getRoot()).thenReturn(deploymentRoot);
    when(deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT))
        .thenReturn(resourceRoot);
    processor.deploy(phaseContext);
  }
  /**
   * Finds a ejb-jar.xml (at WEB-INF of a .war or META-INF of a .jar) parses the file and creates
   * metadata out of it. The metadata is then attached to the deployment unit.
   *
   * @param deploymentPhase
   * @throws DeploymentUnitProcessingException
   */
  @Override
  public void deploy(DeploymentPhaseContext deploymentPhase)
      throws DeploymentUnitProcessingException {

    // get hold of the deployment unit.
    DeploymentUnit deploymentUnit = deploymentPhase.getDeploymentUnit();

    // get the root of the deployment unit
    VirtualFile deploymentRoot =
        deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();

    // Locate a ejb-jar.xml
    VirtualFile ejbJarXml = null;
    // EJB 3.1 FR 20.4 Enterprise Beans Packaged in a .war
    // TODO: Is there a better way to do this?
    if (deploymentRoot.getName().toLowerCase().endsWith(WAR_FILE_EXTENSION)) {
      // it's a .war file, so look for the ejb-jar.xml in WEB-INF
      ejbJarXml = deploymentRoot.getChild(EJB_JAR_XML_LOCATION_IN_WAR);
    } else if (deploymentRoot.getName().toLowerCase().endsWith(JAR_FILE_EXTENSION)) {
      ejbJarXml = deploymentRoot.getChild(EJB_JAR_XML_LOCATION_IN_JAR);
    } else {
      // neither a .jar nor a .war. Return
      return;
    }

    if (ejbJarXml == null || !ejbJarXml.exists()) {
      // no ejb-jar.xml found, nothing to do!
      return;
    }
    // Mark it as a EJB deployment
    EjbDeploymentMarker.mark(deploymentUnit);
    if (!deploymentUnit.hasAttachment(EjbDeploymentAttachmentKeys.EJB_JAR_DESCRIPTION)) {
      final EEModuleDescription moduleDescription =
          deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
      final EjbJarDescription ejbModuleDescription = new EjbJarDescription(moduleDescription);
      deploymentUnit.putAttachment(
          EjbDeploymentAttachmentKeys.EJB_JAR_DESCRIPTION, ejbModuleDescription);
    }

    // get the XMLStreamReader and parse the ejb-jar.xml
    MetaDataElementParser.DTDInfo dtdInfo = new MetaDataElementParser.DTDInfo();
    InputStream stream = null;
    try {
      stream = ejbJarXml.openStream();

      XMLStreamReader reader = this.getXMLStreamReader(stream, ejbJarXml, dtdInfo);

      EjbJarMetaData ejbJarMetaData = EjbJarMetaDataParser.parse(reader, dtdInfo);
      // attach the EjbJarMetaData to the deployment unit
      deploymentUnit.putAttachment(EjbDeploymentAttachmentKeys.EJB_JAR_METADATA, ejbJarMetaData);

    } catch (XMLStreamException xmlse) {
      throw new DeploymentUnitProcessingException(
          "Exception while parsing ejb-jar.xml: " + ejbJarXml.getPathName(), xmlse);
    } catch (IOException ioe) {
      throw new DeploymentUnitProcessingException(
          "Failed to create reader for ejb-jar.xml: " + ejbJarXml.getPathName(), ioe);
    } finally {
      try {
        if (stream != null) {
          stream.close();
        }
      } catch (IOException ioe) {
        logger.debug("Ignoring exception while closing the InputStream ", ioe);
      }
    }
  }