javax.mail.AuthenticationFailedException#javax.activation.FileDataSource源码实例Demo

下面列出了javax.mail.AuthenticationFailedException#javax.activation.FileDataSource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

public void sendUsingMTOM(String fileName, String targetEPR) throws IOException {
    final String EXPECTED = "<m0:uploadFileUsingMTOMResponse xmlns:m0=\"http://services.samples\"><m0:response>"
            + "<m0:image>PHByb3h5PkFCQzwvcHJveHk+</m0:image></m0:response></m0:uploadFileUsingMTOMResponse>";
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
    OMElement payload = factory.createOMElement("uploadFileUsingMTOM", ns);
    OMElement request = factory.createOMElement("request", ns);
    OMElement image = factory.createOMElement("image", ns);

    FileDataSource fileDataSource = new FileDataSource(new File(fileName));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    OMText textData = factory.createOMText(dataHandler, true);
    image.addChild(textData);
    request.addChild(image);
    payload.addChild(request);

    ServiceClient serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference(targetEPR));
    options.setAction("urn:uploadFileUsingMTOM");
    options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
    options.setCallTransportCleanup(true);
    serviceClient.setOptions(options);
    OMElement response = serviceClient.sendReceive(payload);
    Assert.assertTrue(response.toString().contains(EXPECTED), "Attachment is missing in the response");
}
 
源代码2 项目: DKIM-for-JavaMail   文件: TestUtil.java
public static void addFileAttachment(Multipart mp, Object filename) throws MessagingException {

		if (filename==null) return;
		
		File f = new File((String) filename);
		if (!f.exists() || !f.canRead()) {
			msgAndExit("Cannot read attachment file "+filename+", sending stops");
		}

		MimeBodyPart mbp_file = new MimeBodyPart();
        FileDataSource fds = new FileDataSource(f);
        mbp_file.setDataHandler(new DataHandler(fds));
        mbp_file.setFileName(f.getName());

        mp.addBodyPart(mbp_file);        
    }
 
@Test
public void marshalAttachments() throws Exception {
	marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(BinaryObject.class);
	marshaller.setMtomEnabled(true);
	marshaller.afterPropertiesSet();
	MimeContainer mimeContainer = mock(MimeContainer.class);

	Resource logo = new ClassPathResource("spring-ws.png", getClass());
	DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile()));

	given(mimeContainer.convertToXopPackage()).willReturn(true);
	byte[] bytes = FileCopyUtils.copyToByteArray(logo.getInputStream());
	BinaryObject object = new BinaryObject(bytes, dataHandler);
	StringWriter writer = new StringWriter();
	marshaller.marshal(object, new StreamResult(writer), mimeContainer);
	assertTrue("No XML written", writer.toString().length() > 0);
	verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class));
}
 
源代码4 项目: DrivingAgency   文件: MailSenderUtil.java
public void sendAttachmentMail(String to, String subject, String content, File file){
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    try {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);
        FileDataSource fileDataSource=new FileDataSource(file);
        helper.addAttachment("Student.xls",fileDataSource);
        //helper.addAttachment("test"+fileName, file);

        mailSender.send(mimeMessage);
        log.info("带附件的邮件已经发送。");
    } catch (MessagingException e) {
        log.error("发送带附件的邮件时发⽣异常!", e);
    }
}
 
@Test
public void marshalAttachments() throws Exception {
	marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(BinaryObject.class);
	marshaller.setMtomEnabled(true);
	marshaller.afterPropertiesSet();
	MimeContainer mimeContainer = mock(MimeContainer.class);

	Resource logo = new ClassPathResource("spring-ws.png", getClass());
	DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile()));

	given(mimeContainer.convertToXopPackage()).willReturn(true);
	byte[] bytes = FileCopyUtils.copyToByteArray(logo.getInputStream());
	BinaryObject object = new BinaryObject(bytes, dataHandler);
	StringWriter writer = new StringWriter();
	marshaller.marshal(object, new StreamResult(writer), mimeContainer);
	assertTrue("No XML written", writer.toString().length() > 0);
	verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class));
}
 
源代码6 项目: olat   文件: OnyxReporterWebserviceManager.java
/**
 * Delivers a map with all possible outcome-variables of this onyx test.
 * 
 * @param node The course node with the Onyx test.
 * @return A map with all outcome-variables with name as key and type as value.
 */
public Map<String, String> getOutcomes(final AssessableCourseNode node) throws RemoteException {
	final Map<String, String> outcomes = new HashMap<String, String>();
	final OnyxReporterStub stub = client.getOnyxReporterStub();

	final File onyxTestZip = getCP(node.getReferencedRepositoryEntry());

	// Get outcomes
	final ContentPackage cp = new ContentPackage();
	cp.setContentPackage(new DataHandler(new FileDataSource(onyxTestZip)));
	final ResultVariableCandidatesInput resultVariableCandidatesInput = new ResultVariableCandidatesInput();
	resultVariableCandidatesInput.setResultVariableCandidatesInput(cp);
	final ResultVariableCandidatesResponse response = stub.resultVariableCandidates(resultVariableCandidatesInput);
	final PostGetParams[] params = response.getResultVariableCandidatesResponse().getReturnValues();

	for (final PostGetParams param : params) {
		outcomes.put(param.getParamName(), param.getParamValue());
	}

	return outcomes;
}
 
源代码7 项目: fastdfs-zyc   文件: BuildMail.java
/**
 * @param name
 *            String
 * @param pass
 *            String
 */
public boolean addFileAffix(String filename) {

	System.out.println("增加邮件附件:" + filename);

	try {
		BodyPart bp = new MimeBodyPart();
		FileDataSource fileds = new FileDataSource(filename);
		bp.setDataHandler(new DataHandler(fileds));
		bp.setFileName(fileds.getName());

		mp.addBodyPart(bp);

		return true;
	} catch (Exception e) {
		System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
		return false;
	}
}
 
源代码8 项目: carbon-identity   文件: BPELDeployer.java
private void deployArtifacts() throws RemoteException {

        String bpelArchiveName = processName + BPELDeployer.Constants.ZIP_EXT;
        String archiveHome = System.getProperty(BPELDeployer.Constants.TEMP_DIR_PROPERTY) + File.separator;
        DataSource bpelDataSource = new FileDataSource(archiveHome + bpelArchiveName);

        WorkflowDeployerClient workflowDeployerClient;
        if (bpsProfile.getProfileName().equals(WFImplConstant.DEFAULT_BPS_PROFILE_NAME)) {
            workflowDeployerClient = new WorkflowDeployerClient(bpsProfile.getManagerHostURL(),
                    bpsProfile.getUsername());
        } else {
            workflowDeployerClient = new WorkflowDeployerClient(bpsProfile.getManagerHostURL(),
                    bpsProfile.getUsername(), bpsProfile.getPassword());
        }
        workflowDeployerClient.uploadBPEL(getBPELUploadedFileItem(new DataHandler(bpelDataSource),
                                                                  bpelArchiveName, BPELDeployer.Constants.ZIP_TYPE));
        String htArchiveName = htName + BPELDeployer.Constants.ZIP_EXT;
        DataSource htDataSource = new FileDataSource(archiveHome + htArchiveName);
        workflowDeployerClient.uploadHumanTask(getHTUploadedFileItem(new DataHandler(htDataSource), htArchiveName,
                                                                     BPELDeployer.Constants.ZIP_TYPE));
    }
 
@Test
public void testCheckin() throws Exception {
	docService.checkout("", 1);

	Document doc = docDao.findById(1);
	Assert.assertNotNull(doc);
	docDao.initialize(doc);
	Assert.assertEquals(Document.DOC_CHECKED_OUT, doc.getStatus());

	File file = new File("pom.xml");
	docService.checkin("", 1, "comment", "pom.xml", true, new DataHandler(new FileDataSource(file)));

	doc = docDao.findById(1);
	Assert.assertNotNull(doc);
	docDao.initialize(doc);

	// Assert.assertEquals(AbstractDocument.INDEX_TO_INDEX,
	// doc.getIndexed());
	Assert.assertEquals(0, doc.getSigned());
	Assert.assertEquals(Document.DOC_UNLOCKED, doc.getStatus());
}
 
源代码10 项目: ats-framework   文件: MimePackage.java
/**
 * Add the specified file as an attachment
 *
 * @param fileName
 *            name of the file
 * @throws PackageException
 *             on error
 */
@PublicAtsApi
public void addAttachment(
                           String fileName ) throws PackageException {

    try {
        // add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        FileDataSource ds = new FileDataSource(fileName);
        attPart.setDataHandler(new DataHandler(ds));
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(ds.getName());

        addPart(attPart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
源代码11 项目: jplag   文件: AccessStructure.java
/**
 * @return A MimeMultipart object containing the zipped result files
 */
public MimeMultipart getResult() {

    File file = new File(JPLAG_RESULTS_DIRECTORY + File.separator
            + submissionID + getUsername() + ".zip");

    MimeMultipart mmp = new MimeMultipart();

    FileDataSource fds1 = new FileDataSource(file);
    MimetypesFileTypeMap mftp = new MimetypesFileTypeMap();
    mftp.addMimeTypes("multipart/zip zip ZIP");
    fds1.setFileTypeMap(mftp);

    MimeBodyPart mbp = new MimeBodyPart();

    try {
        mbp.setDataHandler(new DataHandler(fds1));
        mbp.setFileName(file.getName());

        mmp.addBodyPart(mbp);
    } catch (MessagingException me) {
        me.printStackTrace();
    }
    return mmp;
}
 
源代码12 项目: olat   文件: OnyxReporterWebserviceManager.java
/**
 * For every result xml file found in the survey folder a dummy student is created.
 * 
 * @param nodeId
 * @return
 */
private List<Student> getAnonymizedStudentsWithResultsForSurvey(final String nodeId) {
	final List<Student> serviceStudents = new ArrayList<Student>();

	final File directory = new File(this.surveyFolderPath);
	if (directory.exists()) {
		final String[] allXmls = directory.list(new myFilenameFilter(nodeId));
		if (allXmls != null && allXmls.length > 0) {
			int id = 0;
			for (final String xmlFileName : allXmls) {
				final File xmlFile = new File(this.surveyFolderPath + xmlFileName);
				final Student serviceStudent = new Student();
				serviceStudent.setResultFile(new DataHandler(new FileDataSource(xmlFile)));
				serviceStudent.setStudentId("st" + id);
				serviceStudents.add(serviceStudent);
				id++;
			}
		}
	}
	return serviceStudents;
}
 
源代码13 项目: javautils   文件: EmailTest.java
@Test
    public void test(){
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.host", "smtp.163.com");
        String sender = "*********@163.com";
        String receiver = "*********@qq.com";
        String title = "你好、Hello Mail";
        String content = "Hello World!!!";
        String username = "*********@163.com";
        String password = "*********";
        List<DataSource> attachments = new ArrayList<>();
        DataSource dataSource1 = new FileDataSource("src/main/resources/image/你好.txt");
        DataSource dataSource2 = new FileDataSource("src/main/resources/image/code.png");
        attachments.add(dataSource1);
        attachments.add(dataSource2);
//		Email email = new Email(props, sender, username, password, receiver, title, content, attachments);
//		EmailUtil.sendEmail(email);
    }
 
private void uploadResourcesToConfigRegistry() throws Exception {

        ResourceAdminServiceClient resourceAdminServiceStub =
                new ResourceAdminServiceClient(contextUrls.getBackEndUrl(), context.getContextTenant().getContextUser().getUserName(),
                        context.getContextTenant().getContextUser().getPassword());

        resourceAdminServiceStub.addCollection("/_system/config/", "payloadFactory", "",
                "Contains test files for payload factory mediator");

        resourceAdminServiceStub.addResource(
                "/_system/config/payloadFactory/payload-in.xml", "application/xml", "payload format",
                new DataHandler(new FileDataSource( new File(getESBResourceLocation() + File.separator +
                                                            "mediatorconfig" + File.separator + "payload" +
                                                            File.separator + "factory" + File.separator +
                                                            "payload-in.xml"))));
    }
 
源代码15 项目: product-ei   文件: SOAPClient.java
/**
 * Sends a SOAP message with MTOM attachment and returns response as a OMElement.
 *
 * @param fileName   name of file to be sent as an attachment
 * @param targetEPR  service url
 * @param soapAction SOAP Action to set. Specify with "urn:"
 * @return OMElement response from BE service
 * @throws AxisFault in case of an invocation failure
 */
public OMElement sendSOAPMessageWithAttachment(String fileName, String targetEPR, String soapAction) throws AxisFault {
    OMFactory factory = OMAbstractFactory.getOMFactory();
    OMNamespace ns = factory.createOMNamespace("http://services.samples", "m0");
    OMElement payload = factory.createOMElement("uploadFileUsingMTOM", ns);
    OMElement request = factory.createOMElement("request", ns);
    OMElement image = factory.createOMElement("image", ns);

    FileDataSource fileDataSource = new FileDataSource(new File(fileName));
    DataHandler dataHandler = new DataHandler(fileDataSource);
    OMText textData = factory.createOMText(dataHandler, true);
    image.addChild(textData);
    request.addChild(image);
    payload.addChild(request);

    ServiceClient serviceClient = new ServiceClient();
    Options options = new Options();
    options.setTo(new EndpointReference(targetEPR));
    options.setAction(soapAction);
    options.setProperty(Constants.Configuration.ENABLE_MTOM, Constants.VALUE_TRUE);
    options.setCallTransportCleanup(true);
    serviceClient.setOptions(options);
    return serviceClient.sendReceive(payload);
}
 
@Test
public void marshalAttachments() throws Exception {
	marshaller = new Jaxb2Marshaller();
	marshaller.setClassesToBeBound(BinaryObject.class);
	marshaller.setMtomEnabled(true);
	marshaller.afterPropertiesSet();
	MimeContainer mimeContainer = mock(MimeContainer.class);

	Resource logo = new ClassPathResource("spring-ws.png", getClass());
	DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile()));

	given(mimeContainer.convertToXopPackage()).willReturn(true);
	byte[] bytes = FileCopyUtils.copyToByteArray(logo.getInputStream());
	BinaryObject object = new BinaryObject(bytes, dataHandler);
	StringWriter writer = new StringWriter();
	marshaller.marshal(object, new StreamResult(writer), mimeContainer);
	assertTrue("No XML written", writer.toString().length() > 0);
	verify(mimeContainer, times(3)).addAttachment(isA(String.class), isA(DataHandler.class));
}
 
源代码17 项目: cxf   文件: MTOMSecurityTest.java
@org.junit.Test
public void testSignedMTOMAction() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = MTOMSecurityTest.class.getResource("client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = MTOMSecurityTest.class.getResource("DoubleItMtom.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItSignedMTOMActionPort");
    DoubleItMtomPortType port =
            service.getPort(portQName, DoubleItMtomPortType.class);
    updateAddressPort(port, PORT);

    DataSource source = new FileDataSource(new File("src/test/resources/java.jpg"));
    DoubleIt4 doubleIt = new DoubleIt4();
    doubleIt.setNumberToDouble(25);
    assertEquals(50, port.doubleIt4(25, new DataHandler(source)));

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
源代码18 项目: cxf   文件: MTOMSecurityTest.java
@org.junit.Test
public void testSymmetricBinaryBytesInAttachment() throws Exception {

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = MTOMSecurityTest.class.getResource("client.xml");

    Bus bus = bf.createBus(busFile.toString());
    BusFactory.setDefaultBus(bus);
    BusFactory.setThreadDefaultBus(bus);

    URL wsdl = MTOMSecurityTest.class.getResource("DoubleItMtom.wsdl");
    Service service = Service.create(wsdl, SERVICE_QNAME);
    QName portQName = new QName(NAMESPACE, "DoubleItSymmetricBinaryPort");
    DoubleItMtomPortType port =
            service.getPort(portQName, DoubleItMtomPortType.class);
    updateAddressPort(port, PORT);

    DataSource source = new FileDataSource(new File("src/test/resources/java.jpg"));
    DoubleIt4 doubleIt = new DoubleIt4();
    doubleIt.setNumberToDouble(25);
    assertEquals(50, port.doubleIt4(25, new DataHandler(source)));

    ((java.io.Closeable)port).close();
    bus.shutdown(true);
}
 
源代码19 项目: olat   文件: OnyxReporterWebserviceManager.java
/**
 * For every result xml file found in the survey folder a dummy student is created.
 * 
 * @param nodeId
 * @return
 */
private List<Student> getAnonymizedStudentsWithResultsForSurvey(final String nodeId) {
	final List<Student> serviceStudents = new ArrayList<Student>();

	final File directory = new File(this.surveyFolderPath);
	if (directory.exists()) {
		final String[] allXmls = directory.list(new myFilenameFilter(nodeId));
		if (allXmls != null && allXmls.length > 0) {
			int id = 0;
			for (final String xmlFileName : allXmls) {
				final File xmlFile = new File(this.surveyFolderPath + xmlFileName);
				final Student serviceStudent = new Student();
				serviceStudent.setResultFile(new DataHandler(new FileDataSource(xmlFile)));
				serviceStudent.setStudentId("st" + id);
				serviceStudents.add(serviceStudent);
				id++;
			}
		}
	}
	return serviceStudents;
}
 
源代码20 项目: commons-email   文件: MultiPartEmailTest.java
@Test
public void testAttachFileLocking() throws Exception {

    // ====================================================================
    // EMAIL-120: attaching a FileDataSource may result in a locked file
    //            resource on windows systems
    // ====================================================================

    final File tmpFile = File.createTempFile("attachment", ".eml");

    this.email.attach(
            new FileDataSource(tmpFile),
            "Test Attachment",
            "Test Attachment Desc");

    assertTrue(tmpFile.delete());
}
 
源代码21 项目: product-ei   文件: DataMapperIntegrationTest.java
protected void uploadResourcesToGovernanceRegistry(String registryRoot, String artifactRoot, String dmConfig,
                                                       String inSchema, String outSchema) throws Exception {
	resourceAdminServiceClient.addCollection("/_system/governance/", registryRoot, "", "");

	resourceAdminServiceClient.addResource("/_system/governance/" + registryRoot + dmConfig, "text/plain", "",
	                                       new DataHandler(new FileDataSource(
	                                       		new File(getClass().getResource(artifactRoot + dmConfig).getPath()))));

	resourceAdminServiceClient.addResource("/_system/governance/" + registryRoot + inSchema, "", "",
	                                       new DataHandler(new FileDataSource(
	                                       		new File(getClass().getResource(artifactRoot + inSchema).getPath()))));

	resourceAdminServiceClient.addResource("/_system/governance/" + registryRoot + outSchema, "", "",
	                                       new DataHandler(new FileDataSource(
	                                       		new File(getClass().getResource(artifactRoot + outSchema).getPath()))));
}
 
源代码22 项目: product-ei   文件: ESBJAVA4565TestCase.java
@BeforeClass(alwaysRun = true)
protected void init() throws Exception {
    super.init();
    verifySequenceExistence("ESBJAVA4565TestSequence");
    resourceAdminServiceStub =
            new ResourceAdminServiceClient(contextUrls.getBackEndUrl(), getSessionCookie());

    String ftpXmlPath = Paths.get(getESBResourceLocation(), "registry", "ftp.xml").toString();
    resourceAdminServiceStub.addResource(REGISTRY_ARTIFACT, "application/xml", "FTP Test account details",
                                         new DataHandler(new FileDataSource(new File(ftpXmlPath))));

    OMElement task = AXIOMUtil.stringToOM("<task:task xmlns:task=\"http://www.wso2.org/products/wso2commons/tasks\"\n" +
                                          "           name=\"TestTask\"\n" +
                                          "           class=\"org.apache.synapse.startup.tasks.MessageInjector\" group=\"synapse.simple.quartz\">\n" +
                                          "    <task:trigger interval=\"10\"/>\n" +
                                          "    <task:property name=\"format\" value=\"get\"/>\n" +
                                          "    <task:property name=\"sequenceName\" value=\"ESBJAVA4565TestSequence\"/>\n" +
                                          "    <task:property name=\"injectTo\" value=\"sequence\"/>\n" +
                                          "    <task:property name=\"message\"><empty/></task:property>\n" +
                                          "</task:task>");
    this.addScheduledTask(task);
}
 
源代码23 项目: micro-integrator   文件: ESBIntegrationTest.java
protected void uploadConnector(String repoLocation, String strFileName)
        throws MalformedURLException, RemoteException {
    List<LibraryFileItem> uploadLibraryInfoList = new ArrayList<LibraryFileItem>();
    LibraryFileItem uploadedFileItem = new LibraryFileItem();
    uploadedFileItem.setDataHandler(
            new DataHandler(new FileDataSource(new File(repoLocation + File.separator + strFileName))));
    uploadedFileItem.setFileName(strFileName);
    uploadedFileItem.setFileType("zip");
    uploadLibraryInfoList.add(uploadedFileItem);
    LibraryFileItem[] uploadServiceTypes = new LibraryFileItem[uploadLibraryInfoList.size()];
    uploadServiceTypes = uploadLibraryInfoList.toArray(uploadServiceTypes);
    esbUtils.uploadConnector(contextUrls.getBackEndUrl(), sessionCookie, uploadServiceTypes);
}
 
@BeforeClass
protected void init() throws Exception {
    super.init();

    String cappPath = Paths.get(getESBResourceLocation(), "car", carFileName).toString();
    uploadCapp(carFileName, new DataHandler(new FileDataSource(new File(cappPath))));
    TimeUnit.SECONDS.sleep(5);
    log.info(carFileName + " uploaded successfully");
}
 
@BeforeClass(alwaysRun = true)
protected void uploadCarFileTest() throws Exception {

    //start FTP server
    startFTPServer();
    super.init();
    serverConfigurationManager = new ServerConfigurationManager(context);

    //upload CAPP
    CarbonAppUploaderClient carbonAppUploaderClient = new CarbonAppUploaderClient(
            context.getContextUrls().getBackEndUrl(), sessionCookie);
    carbonAppUploaderClient.uploadCarbonAppArtifact(carFileName, new DataHandler(new FileDataSource(
            new File(getESBResourceLocation() + File.separator + "car" + File.separator + carFileName))));
    log.info(carFileName + " uploaded successfully");

    //deactivate proxy service
    serviceAdminClient = new ServiceAdminClient(context.getContextUrls().getBackEndUrl(), sessionCookie);
    isProxyDeployed(service);
    serviceAdminClient.stopService(service);

    //Wait and check till the service get deactivated maximum for ~20sec
    for (int i = 0; i < 20; i++) {
        if (!serviceAdminClient.getServicesData(service).getActive()) {
            break;
        }
        log.info("Wait to service get deactivated");
        Thread.sleep(1000);
    }
    Assert.assertFalse(serviceAdminClient.getServicesData(service).getActive(),
            "Unable to stop service: " + service);

    serverConfigurationManager.restartGracefully();
    super.init();
}
 
源代码26 项目: product-ei   文件: TaskRedeployWithCappTestCase.java
@Test(groups = { "wso2.esb" })
public void taskRedeployWithCappTest() throws Exception {

    logViewer.clearLogs();
    carbonAppUploaderClient.uploadCarbonAppArtifact(carFileFullName, new DataHandler( new FileDataSource( new File
            (getESBResourceLocation() + File.separator +
                    "scheduledTask" + File.separator + carFileFullName))));
    isCarFileUploaded = true;
    applicationAdminClient =
            new ApplicationAdminClient(context.getContextUrls().getBackEndUrl(), getSessionCookie());
    Assert.assertTrue(isCarFileDeployed(carFileName), "Car file deployment failed");
    TimeUnit.SECONDS.sleep(50);//wait for some tasks to execute

    carbonAppUploaderClient.uploadCarbonAppArtifact(carFileFullName, new DataHandler( new FileDataSource( new File
            (getESBResourceLocation() + File.separator +
                    "scheduledTask" + File.separator + carFileFullName))));

    TimeUnit.SECONDS
            .sleep(150); //10 seconds proxy sleep time * 5 exeutions * 3 seconds interval  : wait for all tasks
    // to finish executing

    LogEvent[] logs = logViewer.getAllRemoteSystemLogs();
    int afterLogSize = logs.length;

    int startLogCount = 0;
    int endLogCount = 0;

    for (int i = 0; i < afterLogSize; i++) {
        if (logs[i].getMessage().contains("STARTED PROXY")) {
            startLogCount++;

        } else if (logs[i].getMessage().contains("ENDED PROXY")) {
            endLogCount++;

        }
    }
    assertTrue(startLogCount > 5);
    assertTrue(endLogCount > 5);

}
 
源代码27 项目: AccelerationAlert   文件: Mail.java
public void addAttachment(String filename) throws Exception
{
	BodyPart messageBodyPart = new MimeBodyPart();
	DataSource source = new FileDataSource(filename);
	messageBodyPart.setDataHandler(new DataHandler(source));
	messageBodyPart.setFileName(filename);

	_multipart.addBodyPart(messageBodyPart);
}
 
@Test
public void marshalAttachments() throws Exception {
	unmarshaller = new Jaxb2Marshaller();
	unmarshaller.setClassesToBeBound(BinaryObject.class);
	unmarshaller.setMtomEnabled(true);
	unmarshaller.afterPropertiesSet();
	MimeContainer mimeContainer = mock(MimeContainer.class);

	Resource logo = new ClassPathResource("spring-ws.png", getClass());
	DataHandler dataHandler = new DataHandler(new FileDataSource(logo.getFile()));

	given(mimeContainer.isXopPackage()).willReturn(true);
	given(mimeContainer.getAttachment("<[email protected]://springframework.org/spring-ws>")).willReturn(dataHandler);
	given(mimeContainer.getAttachment("<[email protected]://springframework.org/spring-ws>")).willReturn(dataHandler);
	given(mimeContainer.getAttachment("[email protected]")).willReturn(dataHandler);
	String content = "<binaryObject xmlns='http://springframework.org/spring-ws'>" + "<bytes>" +
			"<xop:Include href='cid:[email protected]://springframework.org/spring-ws' xmlns:xop='http://www.w3.org/2004/08/xop/include'/>" +
			"</bytes>" + "<dataHandler>" +
			"<xop:Include href='cid:[email protected]://springframework.org/spring-ws' xmlns:xop='http://www.w3.org/2004/08/xop/include'/>" +
			"</dataHandler>" +
			"<swaDataHandler>[email protected]</swaDataHandler>" +
			"</binaryObject>";

	StringReader reader = new StringReader(content);
	Object result = unmarshaller.unmarshal(new StreamSource(reader), mimeContainer);
	assertTrue("Result is not a BinaryObject", result instanceof BinaryObject);
	BinaryObject object = (BinaryObject) result;
	assertNotNull("bytes property not set", object.getBytes());
	assertTrue("bytes property not set", object.getBytes().length > 0);
	assertNotNull("datahandler property not set", object.getSwaDataHandler());
}
 
@BeforeClass(alwaysRun = true)
protected void uploadCarFileTest() throws Exception {
    super.init();
    CarbonAppUploaderClient carbonAppUploaderClient =
            new CarbonAppUploaderClient(context.getContextUrls().getBackEndUrl(), sessionCookie);
    carbonAppUploaderClient.uploadCarbonAppArtifact("esb-artifacts-car_1.0.0.car"
            , new DataHandler(new FileDataSource(new File(getESBResourceLocation() +
                                                            File.separator + "car" + File.separator +
                                                            "esb-artifacts-car_1.0.0.car"))));
    serviceAdminClient =
            new ServiceAdminClient(context.getContextUrls().getBackEndUrl(), sessionCookie);
    TimeUnit.SECONDS.sleep(5);
    log.info(carFileName + " uploaded successfully");
}
 
源代码30 项目: mail-micro-service   文件: MailUtil.java
/**
 * 追加附件
 * @author hf-hf
 * @date 2018/12/27 16:53
 * @param attachments
 * @param wrapPart
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private void addAttachments(File[] attachments, MimeMultipart wrapPart)
        throws MessagingException, UnsupportedEncodingException {
    if (null != attachments && attachments.length > 0) {
        for (int i = 0; i < attachments.length; i++) {
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            DataHandler dataHandler = new DataHandler(new FileDataSource(attachments[i]));
            String fileName = dataHandler.getName();
            attachmentBodyPart.setDataHandler(dataHandler);
            // 显示指定文件名(防止文件名乱码)
            attachmentBodyPart.setFileName(MimeUtility.encodeText(fileName));
            wrapPart.addBodyPart(attachmentBodyPart);
        }
    }
}