Example usage for org.springframework.core.io ClassPathResource getInputStream

List of usage examples for org.springframework.core.io ClassPathResource getInputStream

Introduction

In this page you can find the example usage for org.springframework.core.io ClassPathResource getInputStream.

Prototype

@Override
public InputStream getInputStream() throws IOException 

Source Link

Document

This implementation opens an InputStream for the given class path resource.

Usage

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.bootstrap.MultiTAdminServiceImpl.java

public void bootstrapWorkflows() {
    // use this to deploy standard workflow process defs to the JBPM engine
    WorkflowDeployer workflowBootstrap = (WorkflowDeployer) getApplicationContext()
            .getBean("workflowBootstrap");

    String resourceClasspath = null;

    // Workflow process definitions
    try {/*from  w  ww  . ja v a 2s .  com*/
        List<Properties> workflowDefs = workflowBootstrap.getWorkflowDefinitions();
        if (workflowDefs != null) {
            for (Properties workflowDefProps : workflowDefs) {
                resourceClasspath = workflowDefProps.getProperty(WorkflowDeployer.LOCATION);
                ClassPathResource resource = new ClassPathResource(resourceClasspath);
                workflowService.deployDefinition(workflowDefProps.getProperty(WorkflowDeployer.ENGINE_ID),
                        resource.getInputStream(), workflowDefProps.getProperty(WorkflowDeployer.MIMETYPE));
            }
        }
    } catch (IOException ioe) {
        throw new AlfrescoRuntimeException("Failed to find workflow process def: " + resourceClasspath);
    }

    logger.info("Tenant workflows bootstrapped: " + tenantService.getCurrentUserDomain());
}

From source file:net.solarnetwork.node.backup.test.FileSystemBackupServiceTest.java

@Test
public void backupOne() throws IOException, InterruptedException {
    final ClassPathResource testResource = new ClassPathResource("test-context.xml",
            AbstractNodeTransactionalTest.class);
    final BackupService bs = service;
    final List<BackupResource> resources = new ArrayList<BackupResource>(1);
    final Calendar now = new GregorianCalendar();
    now.set(Calendar.MILLISECOND, 0);
    resources.add(new ResourceBackupResource(testResource, "test.xml"));
    Backup result = bs.performBackup(resources);
    assertNotNull(result);/*from  w  ww  .  j ava2s .  com*/
    assertNotNull(result.getDate());
    assertTrue(!now.after(result.getDate()));
    assertNotNull(result.getKey());
    assertTrue(result.isComplete());

    // now let's verify we can get that file back out of the backup
    Collection<Backup> backups = bs.getAvailableBackups();
    assertNotNull(backups);
    assertEquals(1, backups.size());
    Backup b = backups.iterator().next();
    assertEquals(result.getKey(), b.getKey());
    assertEquals(result.getDate().getTime(), b.getDate().getTime());

    int count = 0;
    final BackupResourceIterable backupResources = bs.getBackupResources(b);
    try {
        for (BackupResource r : backupResources) {
            count++;
            assertEquals("test.xml", r.getBackupPath());
            Assert.assertArrayEquals(FileCopyUtils.copyToByteArray(testResource.getInputStream()),
                    FileCopyUtils.copyToByteArray(r.getInputStream()));
        }
    } finally {
        backupResources.close();
    }
    assertEquals("Should only have one backup resource", 1, count);
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleEventUtilsImplTest.java

/**
 * The test is is focused on the results of an event containing data in Oracle's Personal Notes feature.
 * Oracle Base64's the value of the attendee's Personal Notes and stores the result in the
 * X-ORACLE-PERSONAL-COMMENT x parameter (and an RTF version in X-ORACLE-PERSONAL-COMMENT-RTF).
 * /*  w  w w  . j  a  v a2  s .com*/
 * The Base64 algorithm sometimes outputs a equals sign ('=') at the end as a pad, 
 * see http://en.wikipedia.org/wiki/Base64
 * 
 * The RFC for iCalendar includes the equals sign in the range of valid characters for a parameter.
 * 
 * @throws IOException
 * @throws ParserException
 */
@Test
public void testOraclePersonalNotes() throws IOException, ParserException {
    ClassPathResource resource = new ClassPathResource(
            "org/jasig/schedassist/impl/oraclecalendar/personal-notes-test.ics");

    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CalendarBuilder builder = new CalendarBuilder();
    Calendar cal = builder.build(resource.getInputStream());
    Assert.assertNotNull(cal);
    ComponentList list = cal.getComponents();
    Assert.assertEquals(1, list.size());
    VEvent event = (VEvent) list.get(0);
    Assert.assertEquals("personal notes test", event.getSummary().getValue());
    Attendee attendee = (Attendee) event.getProperty(Attendee.ATTENDEE);

    ParameterList paramList = attendee.getParameters();
    Assert.assertEquals(10, paramList.size());
    Assert.assertEquals("e1xydGYxXHVjMCBteSBwZXJzb25hbCBub3Rlc30A",
            paramList.getParameter("X-ORACLE-PERSONAL-COMMENT-RTF").getValue());
    Assert.assertEquals("bXkgcGVyc29uYWwgbm90ZXM=",
            paramList.getParameter("X-ORACLE-PERSONAL-COMMENT").getValue());
    Assert.assertEquals("TRUE", paramList.getParameter("X-ORACLE-ISTIMEOK").getValue());
    Assert.assertEquals("FALSE", paramList.getParameter("X-ORACLE-PERSONAL-COMMENT-ISDIRTY").getValue());
    Assert.assertEquals("BUSY", paramList.getParameter("X-ORACLE-SHOWASFREE").getValue());
    Assert.assertEquals("200000118219869582153896", paramList.getParameter("X-ORACLE-GUID").getValue());
    Assert.assertEquals("INDIVIDUAL", paramList.getParameter("CUTYPE").getValue());
    Assert.assertEquals("FALSE", paramList.getParameter("RSVP").getValue());
    Assert.assertEquals("NICHOLAS BLAIR", paramList.getParameter("CN").getValue());
    Assert.assertEquals("ACCEPTED", paramList.getParameter("PARTSTAT").getValue());

    Assert.assertEquals("mailto:nblair@doit.wisc.edu", attendee.getValue());
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleEventUtilsImplTest.java

/**
 * Related to {@link #testOraclePersonalNotes()}, this test validates an
 * event with empty X-ORACLE-PERSONAL-COMMENT parameter.
 * /*from ww  w.  j  a va  2s.co m*/
 * @throws IOException
 * @throws ParserException
 */
@Test
public void testEmptyOraclePersonalNotes() throws IOException, ParserException {
    ClassPathResource resource = new ClassPathResource(
            "org/jasig/schedassist/impl/oraclecalendar/personal-notes-test-empty.ics");

    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CalendarBuilder builder = new CalendarBuilder();
    Calendar cal = builder.build(resource.getInputStream());
    Assert.assertNotNull(cal);
    ComponentList list = cal.getComponents();
    Assert.assertEquals(1, list.size());
    VEvent event = (VEvent) list.get(0);
    Assert.assertEquals("personal notes test", event.getSummary().getValue());
    Attendee attendee = (Attendee) event.getProperty(Attendee.ATTENDEE);

    ParameterList paramList = attendee.getParameters();
    Assert.assertEquals(10, paramList.size());
    Assert.assertEquals("AA==", paramList.getParameter("X-ORACLE-PERSONAL-COMMENT-RTF").getValue());
    Assert.assertEquals("", paramList.getParameter("X-ORACLE-PERSONAL-COMMENT").getValue());
    Assert.assertEquals("TRUE", paramList.getParameter("X-ORACLE-ISTIMEOK").getValue());
    Assert.assertEquals("FALSE", paramList.getParameter("X-ORACLE-PERSONAL-COMMENT-ISDIRTY").getValue());
    Assert.assertEquals("BUSY", paramList.getParameter("X-ORACLE-SHOWASFREE").getValue());
    Assert.assertEquals("200000118219869582153896", paramList.getParameter("X-ORACLE-GUID").getValue());
    Assert.assertEquals("INDIVIDUAL", paramList.getParameter("CUTYPE").getValue());
    Assert.assertEquals("FALSE", paramList.getParameter("RSVP").getValue());
    Assert.assertEquals("NICHOLAS BLAIR", paramList.getParameter("CN").getValue());
    Assert.assertEquals("ACCEPTED", paramList.getParameter("PARTSTAT").getValue());

    Assert.assertEquals("mailto:nblair@doit.wisc.edu", attendee.getValue());
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleEventUtilsImplTest.java

@Test
public void testResourceOwnerGroupAppointment() throws IOException, ParserException {
    ClassPathResource resource = new ClassPathResource(
            "org/jasig/schedassist/impl/oraclecalendar/resource-owner-group-appt.ics");
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CalendarBuilder builder = new CalendarBuilder();
    Calendar cal = builder.build(resource.getInputStream());
    Assert.assertNotNull(cal);//  w w  w. j  av  a 2  s.c om
    ComponentList list = cal.getComponents();
    Assert.assertEquals(1, list.size());
    VEvent event = (VEvent) list.get(0);
    Assert.assertEquals("Resource Owner, Group Appointment", event.getSummary().getValue());
    PropertyList attendees = this.eventUtils.getAttendeeListFromEvent(event);
    Assert.assertEquals(2, attendees.size());
    for (Object o : attendees) {
        Property p = (Property) o;
        if (Attendee.ATTENDEE.equals(p.getName())) {
            // visitor
            Assert.assertEquals("mailto:mesdjian@wisctest.wisc.edu", p.getValue());

        } else if (OracleResourceAttendee.ORACLE_RESOURCE_ATTENDEE.equals(p.getName())) {
            // owner

        } else {
            Assert.fail("unexpected property in attendee list: " + p);
        }
    }

    MockCalendarAccount visitorAccount = new MockCalendarAccount();
    visitorAccount.setDisplayName("ARA MESDJIAN");
    visitorAccount.setEmailAddress("mesdjian@wisctest.wisc.edu");
    Assert.assertTrue(this.eventUtils.isAttendingAsVisitor(event, visitorAccount));

    OracleCalendarResourceAccount resourceAccount = new OracleCalendarResourceAccount();
    resourceAccount.setResourceName("DOIT Ara Testing 333");
    resourceAccount.setOracleGuid("803858C134BC57A9E04400144FAD412A");
    Assert.assertTrue(this.eventUtils.isAttendingAsOwner(event, resourceAccount));
}

From source file:org.jasig.schedassist.impl.oraclecalendar.OracleEventUtilsImplTest.java

/**
 * //from  w ww.j  a va 2 s  .c om
 * @throws ParserException 
 * @throws IOException 
 * @throws InputFormatException 
 * @throws ParseException 
 */
@Test
public void testResourceSchedule() throws IOException, ParserException, InputFormatException, ParseException {
    ClassPathResource resource = new ClassPathResource(
            "org/jasig/schedassist/impl/oraclecalendar/resource-owner-schedule.ics");

    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CalendarBuilder builder = new CalendarBuilder();
    Calendar cal = builder.build(resource.getInputStream());
    Assert.assertNotNull(cal);

    Set<AvailableBlock> blocks = new TreeSet<AvailableBlock>();
    blocks.add(AvailableBlockBuilder.createBlock("20101108-1330", "20101108-1500"));
    blocks.add(AvailableBlockBuilder.createBlock("20101109-0930", "20101109-1300"));
    blocks.add(AvailableBlockBuilder.createBlock("20101111-0930", "20101111-1300"));
    blocks.add(AvailableBlockBuilder.createBlock("20101112-1330", "20101112-1600"));

    AvailableSchedule schedule = new AvailableSchedule(AvailableBlockBuilder.expand(blocks, 30));

    VisibleScheduleBuilder scheduleBuilder = new VisibleScheduleBuilder(this.eventUtils);

    OracleCalendarResourceAccount calendarAccount = new OracleCalendarResourceAccount();
    calendarAccount.setResourceName("MUS WARF Interviews");
    calendarAccount.setOracleGuid("94144ACB42663A86E04400144F2BD678");
    calendarAccount.setLocation("{5542 Humanities}");

    Assert.assertEquals("94144ACB42663A86E04400144F2BD678@email.invalid", calendarAccount.getEmailAddress());
    MockScheduleOwner owner = new MockScheduleOwner(calendarAccount, 1L);
    owner.setPreference(Preferences.MEETING_LIMIT, "1");
    owner.setPreference(Preferences.DURATIONS, "30");
    owner.setPreference(Preferences.MEETING_PREFIX, "WARF Interview");
    owner.setPreference(Preferences.LOCATION, "5542 Humanities");

    VisibleSchedule visibleSchedule = scheduleBuilder.calculateVisibleSchedule(makeDate("20101105"),
            makeDate("20101119"), cal, schedule, owner);

    List<AvailableBlock> busy = visibleSchedule.getBusyList();
    Assert.assertEquals(9, busy.size());
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101108-1330", "20101108-1400")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101109-0930", "20101109-1000")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101109-1000", "20101109-1030")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101109-1030", "20101109-1100")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101109-1100", "20101109-1130")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101109-1130", "20101109-1200")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101111-1230", "20101111-1300")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101112-1500", "20101112-1530")));
    Assert.assertTrue(busy.contains(AvailableBlockBuilder.createBlock("20101112-1530", "20101112-1600")));
    List<AvailableBlock> free = visibleSchedule.getFreeList();
    Assert.assertEquals(13, free.size());

}

From source file:net.solarnetwork.node.backup.test.FileSystemBackupServiceTest.java

@Test
public void backupMultiple() throws IOException {
    final ClassPathResource testResource1 = new ClassPathResource("test-context.xml",
            AbstractNodeTransactionalTest.class);
    final ClassPathResource testResource2 = new ClassPathResource("test-file.txt",
            FileSystemBackupServiceTest.class);
    final BackupService bs = service;
    final List<BackupResource> resources = new ArrayList<BackupResource>(1);
    final Calendar now = new GregorianCalendar();
    now.set(Calendar.MILLISECOND, 0);
    resources.add(new ResourceBackupResource(testResource1, "test.xml"));
    resources.add(new ResourceBackupResource(testResource2, "test.txt"));

    Backup result = bs.performBackup(resources);
    assertNotNull(result);/*from  w w w .  j  a  v a2  s . c  o m*/
    assertNotNull(result.getDate());
    assertTrue(!now.after(result.getDate()));
    assertNotNull(result.getKey());
    assertTrue(result.isComplete());

    // now let's verify we can get that file back out of the backup
    Collection<Backup> backups = bs.getAvailableBackups();
    assertNotNull(backups);
    assertEquals(1, backups.size());
    Backup b = backups.iterator().next();
    assertEquals(result.getKey(), b.getKey());
    assertEquals(result.getDate().getTime(), b.getDate().getTime());

    int count = 0;
    final BackupResourceIterable backupResources = bs.getBackupResources(b);
    try {
        for (BackupResource r : bs.getBackupResources(b)) {
            if (count == 0) {
                assertEquals("test.xml", r.getBackupPath());
                Assert.assertArrayEquals(FileCopyUtils.copyToByteArray(testResource1.getInputStream()),
                        FileCopyUtils.copyToByteArray(r.getInputStream()));
            } else if (count == 1) {
                assertEquals("test.txt", r.getBackupPath());
                Assert.assertArrayEquals(FileCopyUtils.copyToByteArray(testResource2.getInputStream()),
                        FileCopyUtils.copyToByteArray(r.getInputStream()));
            }
            count++;
        }
    } finally {
        backupResources.close();
    }
    assertEquals("Should have 2 backup resources", 2, count);
}

From source file:org.sakaiproject.sitestats.impl.report.ReportManagerImpl.java

public byte[] getReportAsPDF(Report report) {
    ByteArrayOutputStream out = null;
    try {/*  w  ww  .j a v a2  s . co  m*/
        // Setup a buffer to obtain the content length
        out = new ByteArrayOutputStream();
        fopFactory.setURIResolver(new LibraryURIResolver());
        FOUserAgent foUserAgent = fopFactory.newFOUserAgent();

        // Construct fop with desired output format
        Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);

        // Setup XSLT
        if (cachedXmlFoXSLT == null) {
            ClassPathResource xsltCPR = new ClassPathResource(
                    "org/sakaiproject/sitestats/config/fop/" + XML_FO_XSL_FILE);
            InputStream xslt = xsltCPR.getInputStream();
            TransformerFactory factory = TransformerFactory.newInstance();
            cachedXmlFoXSLT = factory.newTemplates(new StreamSource(xslt));
        }
        Transformer transformer = cachedXmlFoXSLT.newTransformer();

        // Setup input for XSLT transformation
        Source src = new SAXSource(new ReportXMLReader(), new ReportInputSource(report));

        // Resulting SAX events (the generated FO) must be piped through to FOP
        Result res = new SAXResult(fop.getDefaultHandler());

        // Start XSLT transformation and FOP processing
        transformer.transform(src, res);

    } catch (TransformerConfigurationException e) {
        LOG.error("TransformerConfigurationException while writing SiteStats PDF report", e);
    } catch (FOPException e) {
        LOG.error("FOPException while writing SiteStats PDF report", e);
    } catch (TransformerException e) {
        LOG.error("TransformerException while writing SiteStats PDF report", e);
    } catch (Exception e) {
        LOG.error("Exception while generating SiteStats PDF report", e);
    } finally {
        try {
            if (out != null) {
                out.close();
                return out.toByteArray();
            }
        } catch (IOException e) {
            LOG.error("IOException while writing SiteStats PDF report", e);
        }
    }
    return null;
}

From source file:com.genscript.gsscm.product.service.ProductService.java

/**
 * ?Product// w  w w.j  a  v  a 2  s.  c o m
 * 
 * @param productDTO
 * @return
 */
public Product saveProduct(ProductDTO productDTO, Integer userId, String ruleId, String path) {
    boolean isAdd = false;
    if (productDTO.getProductId() == null || productDTO.getProductId() == 0) {
        isAdd = true;
    }
    Product product = this.dozer.map(productDTO, Product.class);
    Product dbProduct = this.productDao.findUniqueBy("catalogNo", product.getCatalogNo());
    if (dbProduct != null
            && (product.getProductId() == null || !(product.getProductId().equals(dbProduct.getProductId())))) {
        System.out.println("ruleId:" + ruleId);
        if (ruleId != null && !ruleId.equals("") && !ruleId.equals("null")) {
            System.out.println("ruleId:" + ruleId);
            this.saveCatalogNoRules(Integer.valueOf(ruleId));
        }
        // this.productDao.getSession().evict(dbProduct);
        throw new BussinessException(BussinessException.ERR_PRODUCT_CATALOGNO_UNIQUE);
    }
    this.productDao.getSession().evict(dbProduct);
    Integer objectId = product.getProductId();// for approved.
    Date now = new Date();

    product.setModifiedBy(userId);
    if (product.getProductId() == null) {
        product.setCreatedBy(userId);
        product.setCreationDate(now);
    }
    product.setModifyDate(now);
    if (product.getDimUom() == null) {
        product.setDimUom("inches");
    }
    this.productDao.save(product);
    if (ruleId != null && !ruleId.equals("") && !ruleId.equals("null")) {
        System.out.println("ruleId:" + ruleId);
        this.saveCatalogNoRules(Integer.valueOf(ruleId));
    }
    this.attachShipCondition(product, productDTO.getShipCondition(), userId);
    this.attachStorageCondition(product, productDTO.getStorageCondition(), userId);
    this.attachPdtRestrictShip(product, productDTO.getRestrictShipList(), productDTO.getDelRestrictShipIdList(),
            userId);
    this.attachPdtIntmd(product, productDTO.getIntmdList(), productDTO.getDelIntmdIdList(), userId);
    this.attachPdtComponent(product, productDTO.getComponentList(), productDTO.getDelComIdList(), userId);

    this.attachPdtSpecialPrice(product, productDTO.getSpecialPriceList(), productDTO.getDelSpecialPriceIdList(),
            userId);
    this.attachPdtSupplier(product, productDTO.getVendorProductList(), productDTO.getDelVendorProductIdList(),
            userId);
    this.attachPdtRelation(product, productDTO.getPdtRelationList(), userId);
    this.attachPdtRoyalty(product, productDTO.getRoyaltyProduct(), userId);
    this.attachProductMoreInfo(productDTO.getProductExtendedInfo(), userId, product.getProductId());

    this.attachPdtPrice(dbProduct, productDTO.getPriceList(), product.getProductId(),
            productDTO.getDelPriceIdList(), userId);
    this.attachProductReference(productDTO.getProductReferenceList(), product.getProductId(), userId,
            productDTO.getDelReferenceList());
    String productType = productDTO.getType();
    if (productType != null) {
        productType = productType.toLowerCase();
        Integer productId = product.getProductId();
        if ("peptide".equals(productType)) {
            this.attachPdtOfPeptide(productId, productDTO.getPeptide(), userId);
        } else if ("antibody".equals(productType)) {
            this.attachPdtOfAntibody(productId, productDTO.getAntibody(), userId);
        } else if ("enzyme".equals(productType)) {
            this.attachPdtOfEnzyme(productId, productDTO.getEnzyme(), userId);
        } else if ("gene".equals(productType)) {
            this.attachPdtOfGene(productId, productDTO.getGene(), userId);
        } else if ("kit".equals(productType)) {
            this.attachPdtOfKit(productId, productDTO.getKit(), userId);
        } else if ("oligo".equals(productType)) {
            this.attachPdtOfOligo(productId, productDTO.getOligo(), userId);
        } else if ("protein".equals(productType)) {
            this.attachPdtOfProtein(productId, productDTO.getProtein(), userId);
        } else if ("molecule".equals(productType)) {
            this.attachPdtOfMolecule(productId, productDTO.getMolecule(), userId);
        } else if ("chemicals".equals(productType)) {
            this.attachPdtOfChemical(productId, productDTO.getChemical(), userId);
        }
    }

    // with lifeng's approved module.
    Integer requestId = null;
    productApproved(productDTO, userId, product, objectId, requestId);

    Integer priceRequestId = null;
    if (productDTO.getPriceList() != null && productDTO.getPriceList().size() > 0) {
        for (ProductPriceDTO priceDTO : productDTO.getPriceList()) {
            Integer objectPriceId = priceDTO.getPriceId();
            productPriceApproved(productDTO, userId, priceDTO, objectPriceId, priceRequestId);
        }
    }
    String wordString = "";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String s = sdf.format(new Date());
    if (path != null && !path.equals("")) {
        try {
            if (product.getProductClsId().equals(2)) {// Peptide Rp?
                String readPath = path + "wordModel//Emodel.doc";
                wordString = WordPOIUtil.readWordFileToString(readPath);
                Peptide peptide = this.peptideDao.getById(product.getProductId());
                if (peptide != null) {
                    if (peptide.getPhoenixpeptideCatNo() == null) {
                        wordString = wordString.replaceAll("catalogNo", " ");
                    } else {
                        wordString = wordString.replaceAll("catalogNo", " " + product.getCatalogNo());
                    }
                    if (peptide.getMolecularFormula() == null) {
                        wordString = wordString.replaceAll("productformula", " ");
                    } else {
                        wordString = wordString.replaceAll("productformula",
                                " " + peptide.getMolecularFormula());

                    }

                    if (peptide.getSequenceShortening() == null) {
                        wordString = wordString.replaceAll("tttttt", "");
                    } else {
                        wordString = wordString.replaceAll("tttttt", " " + peptide.getSequenceShortening());
                    }
                    if (peptide.getCasNo() == null) {
                        wordString = wordString.replaceAll("ssaaa", " ");
                    } else {
                        wordString = wordString.replaceAll("ssaaa", " " + peptide.getCasNo());
                    }

                    if (peptide.getMolecularWeight() == null) {
                        wordString = wordString.replaceAll("productmw", " ");
                    } else {
                        wordString = wordString.replaceAll("productmw", " " + peptide.getMolecularWeight());
                    }
                    if (peptide.getSpecificity() == null) {
                        wordString = wordString.replaceAll("ag", "");
                    } else {
                        wordString = wordString.replaceAll("ag", "" + peptide.getSpecificity());
                    }

                    if (peptide.getPurity() == null) {
                        wordString = wordString.replaceAll("productPurity", " ");
                    } else {
                        wordString = wordString.replaceAll("productPurity", " " + peptide.getPurity());
                    }

                    if (peptide.getSequence() == null) {
                        wordString = wordString.replaceAll("productsequence", " ");
                    } else {
                        wordString = wordString.replaceAll("productsequence", " " + peptide.getSequence());

                    }
                    if (peptide.getCterminal() == null) {
                        wordString = wordString.replaceAll("productcterminal", " ");
                    } else {
                        wordString = wordString.replaceAll("productcterminal", " " + peptide.getCterminal());

                    }
                    if (peptide.getNterminal() == null) {
                        wordString = wordString.replaceAll("productnterminal", " ");
                    } else {
                        wordString = wordString.replaceAll("productnterminal", " " + peptide.getNterminal());

                    }
                    if (peptide.getConcentration() == null) {
                        wordString = wordString.replaceAll("productchemicalbridge", "");
                    } else {
                        wordString = wordString.replaceAll("productchemicalbridge",
                                "" + peptide.getConcentration());
                    }

                    if (peptide.getSpecificActivity() == null) {
                        wordString = wordString.replaceAll("bbbb", " ");
                    } else {
                        wordString = wordString.replaceAll("bbbb", " " + peptide.getSpecificActivity());
                    }

                    if (peptide.getEndotoxinLevel() == null) {
                        wordString = wordString.replaceAll("productendotoxinlevel", " ");
                    } else {
                        wordString = wordString.replaceAll("productendotoxinlevel",
                                " " + peptide.getEndotoxinLevel());
                    }

                    if (peptide.getConcentration() == null) {
                        wordString = wordString.replaceAll("productconcentration", " ");
                    } else {
                        wordString = wordString.replaceAll("productconcentration",
                                " " + peptide.getConcentration());
                    }

                    if (peptide.getQualityControl() == null) {
                        wordString = wordString.replaceAll("productqualitycontrol", " ");
                    } else {
                        wordString = wordString.replaceAll("productqualitycontrol",
                                " " + peptide.getQualityControl());
                    }
                    if (productDTO.getStorageCondition().getComment() == null) {
                        wordString = wordString.replaceAll("productstorage", " ");
                    } else {
                        wordString = wordString.replaceAll("productstorage",
                                " " + productDTO.getStorageCondition().getComment());
                    }

                    if (product.getShortDesc() == null) {
                        wordString = wordString.replaceAll("productnotes", " ");
                    } else {
                        wordString = wordString.replaceAll("productnotes", " " + product.getShortDesc());
                    }

                } else {

                    wordString = wordString.replaceAll("productformula", " ");

                    wordString = wordString.replaceAll("ssaaa", " ");

                    wordString = wordString.replaceAll("tttttt", " ");

                    wordString = wordString.replaceAll("productmw", " ");

                    wordString = wordString.replaceAll("productPurity", " ");
                    wordString = wordString.replaceAll("bbbb", "");

                    wordString = wordString.replaceAll("productsequence", " ");

                    wordString = wordString.replaceAll("productcterminal", " ");

                    wordString = wordString.replaceAll("ag", " ");

                    wordString = wordString.replaceAll("productendotoxinlevel", " ");

                    wordString = wordString.replaceAll("productconcentration", " ");

                    wordString = wordString.replaceAll("productqualitycontrol", " ");

                    wordString = wordString.replaceAll("productstorage", " ");

                    wordString = wordString.replaceAll("productnotes", " ");

                }

                if (product.getSize() == null) {
                    wordString = wordString.replaceAll("sizes", " ");
                } else {
                    String size = " " + product.getSize().toString() + " " + product.getUom();
                    if (product.getAltSize() != null) {
                        size += " or " + product.getAltSize().toString() + " " + product.getAltUom();
                    }
                    wordString = wordString.replaceAll("sizes", size);
                }

                if (product.getName() == null) {
                    wordString = wordString.replaceAll("name", " ");
                } else {
                    wordString = wordString.replaceAll("name", " " + product.getName());
                }

                if (product.getCatalogNo() == null) {
                    wordString = wordString.replaceAll("catalogNo", " ");
                } else {
                    wordString = wordString.replaceAll("catalogNo", " " + product.getCatalogNo());
                }

                if (productDTO.getStorageCondition().getComment() == null) {
                    wordString = wordString.replaceAll("productstorage", " ");
                } else {
                    wordString = wordString.replaceAll("productstorage",
                            " " + productDTO.getStorageCondition().getComment());
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                String dateStr = df.format(new Date());
                wordString = wordString.replaceAll("datetime", " Version: " + dateStr);
                String writeP = this.fileService.getUploadPath();
                String writePath = writeP + "productFile_notes/" + product.getCatalogNo() + "_" + s + ".doc";
                System.out.println(writePath);
                WordPOIUtil.writeWordFile(writePath, wordString);
            }
            if (product.getProductClsId().equals(6)) {// Antibody
                String readPath = path + "wordModel//Amodel.doc";
                wordString = WordPOIUtil.readWordFileToString(readPath);
                Antibody antibody = this.antibodyDao.getById(product.getProductId());
                ProductExtendedInfo productExtendedInfo = this.pdtExtInfoDao.getById(product.getProductId());
                if (product.getName() == null) {
                    wordString = wordString.replaceAll("name", " ");
                } else {
                    wordString = wordString.replaceAll("name", " " + product.getName());
                }
                if (product.getCatalogNo() == null) {
                    wordString = wordString.replaceAll("catalogNo", " ");
                } else {
                    wordString = wordString.replaceAll("catalogNo", " " + product.getCatalogNo());
                }
                if (product.getSize() == null) {
                    wordString = wordString.replaceAll("productSize", " ");
                } else {
                    String size = " " + product.getSize().toString() + " " + product.getUom();
                    if (product.getAltSize() != null) {
                        size += " or " + product.getAltSize().toString() + " " + product.getAltUom();
                    }
                    wordString = wordString.replaceAll("productSize", size);
                }
                if (product.getSellingNote() == null) {
                    wordString = wordString.replaceAll("sellingNote", " ");
                } else {
                    wordString = wordString.replaceAll("sellingNote", " " + product.getSellingNote());
                }
                if (antibody != null) {
                    if (antibody.getHostSpecies() == null) {
                        wordString = wordString.replaceAll("hostSpecies", " ");
                    } else {
                        wordString = wordString.replaceAll("hostSpecies", " " + antibody.getHostSpecies());
                    }
                    if (antibody.getConjugation() == null) {
                        wordString = wordString.replaceAll("productConjugation", " ");
                    } else {
                        wordString = wordString.replaceAll("productConjugation",
                                " " + antibody.getConjugation());
                    }
                    if (antibody.getImmunogen() == null) {
                        wordString = wordString.replaceAll("productImmunogen", " ");
                    } else {
                        wordString = wordString.replaceAll("productImmunogen", " " + antibody.getImmunogen());
                    }
                    if (antibody.getAntigenSpecies() == null) {
                        wordString = wordString.replaceAll("antigenSpecies", " ");
                    } else {
                        wordString = wordString.replaceAll("antigenSpecies",
                                " " + antibody.getAntigenSpecies());
                    }
                    if (antibody.getSpeciesReactivity() == null) {
                        wordString = wordString.replaceAll("speciesReactivity", " ");
                    } else {
                        wordString = wordString.replaceAll("speciesReactivity",
                                " " + antibody.getSpeciesReactivity());
                    }
                    if (antibody.getSubclass() == null) {
                        wordString = wordString.replaceAll("productSubclass", " ");
                    } else {
                        wordString = wordString.replaceAll("productSubclass", " " + antibody.getSubclass());
                    }
                    if (antibody.getPurification() == null) {
                        wordString = wordString.replaceAll("productPurification", " ");
                    } else {
                        wordString = wordString.replaceAll("productPurification",
                                " " + antibody.getPurification());
                    }
                    if (antibody.getConcentration() == null) {
                        wordString = wordString.replaceAll("productConcentration", " ");
                    } else {
                        wordString = wordString.replaceAll("productConcentration",
                                " " + antibody.getConcentration());
                    }
                    if (antibody.getConcentration() == null) {
                        wordString = wordString.replaceAll("productSpecificity", " ");
                    } else {
                        wordString = wordString.replaceAll("productSpecificity",
                                " " + antibody.getSpecificity());
                    }
                } else {

                    wordString = wordString.replaceAll("hostSpecies", " ");
                    wordString = wordString.replaceAll("productImmunogen", " ");
                    wordString = wordString.replaceAll("antigenSpecies", " ");
                    wordString = wordString.replaceAll("speciesReactivity", " ");
                    wordString = wordString.replaceAll("productSubclass", " ");
                    wordString = wordString.replaceAll("productPurification", " ");
                    wordString = wordString.replaceAll("productConcentration", " ");
                }

                if (productDTO.getStorageCondition().getTemperature() == null) {
                    wordString = wordString.replaceAll("temperature", " ");
                } else {
                    String str = "Store at " + productDTO.getStorageCondition().getTemperature().toString()
                            + " C";
                    if (productDTO.getStorageCondition().getComment() != null) {
                        str += "/ " + productDTO.getStorageCondition().getComment();
                    }
                    wordString = wordString.replaceAll("temperature", str);
                }

                if (productExtendedInfo != null) {
                    if (productExtendedInfo.getApplications() == null) {
                        wordString = wordString.replaceAll("productApplication", " ");
                    } else {
                        wordString = wordString.replaceAll("productApplication",
                                " " + productExtendedInfo.getApplications());
                    }

                } else {
                    wordString = wordString.replaceAll("productApplication", " ");
                }

            }

            if (product.getProductClsId().equals(3)) {
                String readPath = path + "wordModel//Zmodel.doc";

                wordString = WordPOIUtil.readWordFileToString(readPath);
                Protein protein = this.proteinDao.getById(product.getProductId());
                if (protein != null) {
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("measuredMolecularWeight", " ");
                    } else {
                        wordString = wordString.replaceAll("measuredMolecularWeight",
                                " " + protein.getMolecularWeight());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productPurty", " ");
                    } else {
                        wordString = wordString.replaceAll("productPurty", " " + protein.getPurity());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("proudctEndotoxinLevel", " ");
                    } else {
                        wordString = wordString.replaceAll("proudctEndotoxinLevel",
                                " " + protein.getEndotoxinLevel());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productQuantitation", " ");
                    } else {
                        wordString = wordString.replaceAll("productQuantitation",
                                " " + protein.getQuantitation());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productSpecificActivity", " ");
                    } else {
                        wordString = wordString.replaceAll("productSpecificActivity",
                                " " + protein.getSpecificActivity());
                    }

                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productFormulation", " ");
                    } else {
                        wordString = wordString.replaceAll("productFormulation",
                                " " + protein.getFormulation());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productReconstitution", " ");
                    } else {
                        wordString = wordString.replaceAll("productReconstitution",
                                " " + protein.getReconstitution());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productSequence", " ");
                    } else {
                        wordString = wordString.replaceAll("productSequence", " " + protein.getSequence());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productDimers", " ");
                    } else {
                        wordString = wordString.replaceAll("productDimers", " " + protein.getDimers());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productSequencAnalysis", " ");
                    } else {
                        wordString = wordString.replaceAll("productSequencAnalysis",
                                " " + protein.getSequenceAnalysis());
                    }
                    if (product.getName() == null) {
                        wordString = wordString.replaceAll("productSource", " ");
                    } else {
                        wordString = wordString.replaceAll("productSource", " " + protein.getSource());
                    }

                } else {
                    wordString = wordString.replaceAll("measuredMolecularWeight", " ");

                    wordString = wordString.replaceAll("productPurty", " ");

                    wordString = wordString.replaceAll("proudctEndotoxinLevel", " ");

                    wordString = wordString.replaceAll("productQuantitation", " ");

                    wordString = wordString.replaceAll("productSpecificActivity", " ");

                    wordString = wordString.replaceAll("productFormulation", " ");

                    wordString = wordString.replaceAll("productReconstitution", " ");

                    wordString = wordString.replaceAll("productSequence", " ");

                    wordString = wordString.replaceAll("productDimers", " ");

                    wordString = wordString.replaceAll("productSequencAnalysis", " ");

                    wordString = wordString.replaceAll("productSource", " ");

                }
                if (product.getName() == null) {
                    wordString = wordString.replaceAll("name", " ");
                } else {
                    wordString = wordString.replaceAll("name", " " + product.getName());
                }
                if (product.getCatalogNo() == null) {
                    wordString = wordString.replaceAll("catalogNo", " ");
                } else {
                    wordString = wordString.replaceAll("catalogNo", " " + product.getCatalogNo());
                }
                if (product.getName() == null) {
                    wordString = wordString.replaceAll("productDescription", " ");
                } else {
                    wordString = wordString.replaceAll("productDescription", " " + product.getShortDesc());
                }
                if (product.getName() == null) {
                    wordString = wordString.replaceAll("productStorage", " ");
                } else {
                    wordString = wordString.replaceAll("productStorage",
                            " " + productDTO.getStorageCondition().getComment());
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = df.format(new Date());
        wordString = wordString.replaceAll("datetime", " Version: " + dateStr);
        String writeP = this.fileService.getUploadPath();
        String writePath = writeP + "productFile_notes/" + product.getCatalogNo() + "_" + s + ".doc";
        WordPOIUtil.writeWordFile(writePath, wordString);
        Integer loginUserId = SessionUtil.getUserId();
        df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Documents document = null;
        if (product.getProductId() != null && !"".equals(product.getProductId())) {
            // Documents??
            document = this.documentdao.getByProductId(product.getProductId());
            String dates = "";
            dates = df.format(now);

            String filePath = "productFile_notes/" + product.getCatalogNo() + "_" + s + ".doc";
            String docname = product.getCatalogNo() + "_" + s + ".doc";
            if (document.getDocId() != null) {
                DocumentVersion ver = this.dozer.map(document, DocumentVersion.class);
                ver.setVersion(document.getVersion());
                ver.setDocFilePath(filePath);
                ver.setDocId(document.getDocId());
                ver.setCreatedBy(userId);
                ver.setCreationDate(now);
                ver.setModifiedBy(userId);
                ver.setModifyDate(now);
                this.documentVersionDao.save(ver);
                String sql = "";
                sql = "update   `product`.`documents` set  doc_name='" + docname + "',version='"
                        + format.format(now) + "',doc_type='Document-DATASHEET',"
                        + "doc_file_type='DOC',doc_file_name='" + docname + "'," + "doc_file_path='" + filePath
                        + "',description='new document for datesheet !',old_flag='4',"
                        + "internal_flag='1',validate_flag='1',creation_date='" + dates + "',created_by='"
                        + loginUserId + "',modify_date='" + dates + "',modified_by='" + loginUserId
                        + "' where doc_id=" + document.getDocId();
                System.out.println(sql);
                ClassPathResource cr = new ClassPathResource("application.properties");
                Properties pros = new Properties();
                try {
                    pros.load(cr.getInputStream());
                } catch (IOException e3) {
                    e3.printStackTrace();
                }
                String user = pros.getProperty("jdbc.username");
                String password = pros.getProperty("jdbc.password");
                String url = pros.getProperty("jdbc.url");
                String driver = pros.getProperty("jdbc.driver");
                Connection con = null;
                Statement stmt = null;
                int s1 = 0;
                try {
                    Class.forName(driver);
                    con = DriverManager.getConnection(url, user, password);
                    stmt = con.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
                            java.sql.ResultSet.CONCUR_READ_ONLY);
                    s1 = stmt.executeUpdate(sql);
                    if (s1 != -1) {
                        System.out.println(" create it ok ~");
                    }
                } catch (ClassNotFoundException e1) {
                    e1.printStackTrace();
                } catch (SQLException e2) {
                    e2.printStackTrace();
                } finally {
                    try {
                        if (stmt != null)
                            stmt.close();
                        if (con != null)
                            con.close();
                    } catch (SQLException e) {
                        System.out.println(e.toString());
                    }
                }
            } else {
                Documents entity = new Documents();
                entity.setCreatedBy(loginUserId);
                entity.setCreationDate(now);
                entity.setModifiedBy(userId);
                entity.setModifyDate(now);
                entity.setDocFileName(docname);
                entity.setDocFilePath(filePath);
                entity.setDocFileType("DOC");
                entity.setDocName(docname);
                entity.setInternalFlag("1");
                entity.setValidateFlag("1");
                entity.setOldFlag("4");
                entity.setDocType("Document-DATASHEET");
                entity.setDescription("new document for datesheet !");
                this.documentDao.save(entity);
                ProductDocuments pd = new ProductDocuments();
                pd.setCreatedBy(userId);
                pd.setCreationDate(now);
                pd.setModifiedBy(userId);
                pd.setModifyDate(now);
                pd.setDocId(entity.getDocId());
                pd.setProductId(product.getProductId());
                this.productDocumentDao.save(pd);
            }

        }

    }
    if (isAdd) {
        ApplicationEvent evt = new NewPartEvent(this, productDTO);
        context.publishEvent(evt);
    } else {
        ApplicationEvent evt = new NewPartEvent(this, productDTO);
        context.publishEvent(evt);
    }
    return product;

}