Aspose.Tasks for java로 프로젝트를 만들고 읽고 저장합니다

Java 용 Tasks를 사용하면 Microsoft Project를 설치하거나 Microsoft Office Automation을 사용하지 않고 Microsoft Project (MPP/XML) 파일과 함께 작업 할 수 있습니다. 강력하고 유연한 API 인 Aspose.Tasks 는 프로젝트 파일 조작을위한 효율적인 코드를 작성하는 데 필요한 도구를 제공하여 시간과 노력을 절약합니다.

Aspose.Tasks는 기존 파일을 열 수 있지만 새 파일을 만들 수도 있습니다. 이 기사에서는 스트림에서 새롭고 빈 프로젝트 파일을 만들거나 프로젝트 클래스를 사용하는 방법을 설명합니다.

빈 프로젝트 파일 만들기

Project 클래스는 Aspose.task의 주요 클래스입니다. 프로젝트와 관련된 속성을 설정하고 얻는 데 사용됩니다. 이 클래스에서 제공하는 저장 방법을 사용하면 단일 API 호출을 통해 프로젝트를 XML, MPP, PDF, HTML 등과 같은 다양한 출력 형식으로 렌더링 할 수 있습니다. 이 메소드는 파일 스트림 또는 파일 이름과 SaveFileFormat 열거 유형에서 제공하는 값 중 하나를 허용합니다.

현재, Aspose.Tasks for Java는 XML 프로젝트 파일 만 만들기위한 시설을 제공합니다. 다음 줄의 코드는 XML 형식의 간단한 프로젝트 파일을 만듭니다.

XML 프로젝트 파일은 Microsoft Project에서 열 수 있습니다.

  1. 파일 메뉴에서 을 선택하십시오.
  2. 파일 유형에서 XML 형식 (*.xml) 옵션을 선택하고 출력 XML 파일로 찾아보십시오.
  3. 프로젝트 메뉴에서 프로젝트 정보를 선택하십시오.

출력 XML 파일의 프로젝트 정보

Resaved Microsoft Project XML 파일의 프로젝트 속성을 확인하십시오

파일 스트림을 사용하여 빈 프로젝트 만들기

아래 코드 예제는 Aspose.Tasks 를 사용하여 파일 스트림을 사용하여 빈 프로젝트를 만드는 방법을 보여줍니다.

 1// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
 2   // The path to the documents directory.
 3   String dataDir = Utils.getDataDir(CreateEmptyProjectFile.class);
 4
 5   //Create a project instance
 6   Project newProject = new Project();
 7
 8   newProject.save(dataDir + "Project1.xml", SaveFileFormat.XML);
 9
10   //Display result of conversion.
11   System.out.println("Project file generated Successfully");

Reading a Project File

Aspose.Tasks for Java lets you open existing files and manipulate them as well as creating new files. This topic shows how a Project file can be read using the Project class’s constructor.

The Project class constructor accepts a valid FileInputStream object or path to MPP or XML document and returns a Project object which can be used to manipulate project data.

 1// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
 2   try
 3   {
 4       FileInputStream prjStream = new FileInputStream(dataDir + "Project1.mpp");
 5       Project existingProject = new Project(prjStream);
 6       prjStream.close();
 7       
 8       System.out.println("Calendar : " + existingProject.get(Prj.NAME));
 9   }
10   catch(Exception ex)
11   {
12       System.out.println(ex.getMessage());
13   }

Reading Project Files as a Template

1Project project = new Project("d:\\Project1.mpp");

Reading Project Data from Microsoft Project Database

Aspose.Tasks for Java API now allows to read Project data from the Microsoft Project database. The SqlConnectionStringBuilder and MspDbSettings classes can be used to accomplish this purpose providing connection string settings for connection to the database.

 1// The path to the documents directory.
 2      String dataDir = Utils.getDataDir(ReadingProjectDatafromMicrosoftProjectDatabase.class);
 3      
 4String url = "jdbc:sqlserver://";
 5String serverName = "192.168.56.2\\MSSQLSERVER";
 6String portNumber = "1433";
 7String databaseName = "ProjectServer_Published";
 8String userName = "sa";
 9String password = "***";
10MspDbSettings settings = new MspDbSettings(url+serverName+":"+portNumber+";databaseName="+databaseName+
11         ";user=" + userName + ";password=" + password, UUID.fromString("E6426C44-D6CB-4B9C-AF16-48910ACE0F54"));
12 
13addJDBCDriver(new File("c:\\Program Files (x86)\\Microsoft JDBC Driver 4.0 for SQL Server\\sqljdbc_4.0\\enu\\sqljdbc4.jar"));
14 
15Project project = new Project(settings);
16project.save(dataDir + "Project1.xml", SaveFileFormat.XML);
1private static void addJDBCDriver(File file) throws Exception
2{
3    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
4    method.setAccessible(true);
5    method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
6}

Reading Project Data from Microsoft Access Database (MPD)

 1public static void main(String[] args) throws IOException {
 2    // For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
 3    // The path to the documents directory.
 4    String dataDir = Utils.getDataDir(ReadingProjectDatafromMicrosoftProjectDatabase.class);
 5    
 6    MpdSettings settings = new MpdSettings(getConnectionString(), 1);
 7    Project project = new Project(settings);
 8    project.save(dataDir + "Project1.xml", SaveFileFormat.XML);
 9}
10    
11private static String getConnectionString()
12{
13    return "jdbc:odbc:DRIVER=Microsoft Access Driver (*.mdb, *.accdb);DBQ=" + "mpdFile.mpd";
14}

Ignoring invalid characters during loading Project

Some files may have invalid characters in the custom fields. Microsoft Project does not allow invalid character so the files have been created or manipulated with automation or some other tools. If these be loaded using the API, they may lead to an exception. In order to ignore such invalid characters, the overloaded constructor of the Project class can be used with the delegate method ParseErrorCallBack.

 1public static void main(String[] args) throws IOException {
 2    // For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
 3    
 4    // The path to the documents directory.
 5    String dataDir = Utils.getDataDir(ReadingProjectDatafromMicrosoftProjectDatabase.class);
 6            
 7    InputStream stream = null;
 8    try
 9    {
10        stream = new ByteArrayInputStream(getModifiedXml().getBytes("utf-8"));
11    }
12    catch (UnsupportedEncodingException e)
13    {
14        e.printStackTrace();
15    }
16 
17    Project project = new Project(stream, new ParseErrorCallback()
18    {
19        public Object invoke(Object sender, ParseErrorArgs args)
20        {
21            return customDurationHandler(sender, args);
22        }
23    });
24    project.save(dataDir + "Project1.xml", SaveFileFormat.XML);
25}
26
27private static String getModifiedXml()
28{
29    StringBuilder xml = new StringBuilder();
30 
31    BufferedReader reader;
32    String line;
33    try
34    {
35        reader = new BufferedReader(new InputStreamReader(new FileInputStream("NewProductDev.xml"), "UTF8"));
36        while ((line = reader.readLine()) != null)
37        {
38            xml.append(line).append("\n");
39        }
40    }
41    catch (Exception e)
42    {
43        e.printStackTrace();
44    }
45 
46    return xml.toString().replaceAll("PT(\\d+)H(\\d+)M(\\d+)S", "**$1Hrs$2Mins$3Secs**");
47}
48 
49private static Object customDurationHandler(Object sender, ParseErrorArgs args)
50{
51    System.err.print(String.format("Object field : %s; Invalid value : %s; ", args.getFieldName(), args.getInvalidValue()));
52    String duration = args.getInvalidValue().replaceAll("[*]{2}(\\d+)Hrs(\\d+)Mins(\\d+)Secs[*]{2}", "PT$1H$2M$3S");
53    double newValue = Duration.parseTimeSpan(duration)*0.001/60/60;
54    System.err.println(String.format("New value : %s", duration));
55    Project project = new Project();
56    return project.getDuration(newValue, TimeUnitType.Hour);
57}

Read Password Protected Projects (2003 Format)

This topic shows how to read password protected projects in 2003 format using Aspose.Tasks for Java.

The Project class exposes the Project() constructor which is capable of reading password protected files in 2003 format. Saving a password-protected file is not supported yet.

To read a password-protected project file:

  1. Load a Microsoft Project file.
  2. In the constructor, provide a password as the second argument to the constructor.

The following lines of code show how to achieve this using Java.

1// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
2   // The path to the documents directory.
3   String dataDir = Utils.getDataDir(ReadPasswordProtectedFiles.class);
4
5   Project prj = new Project(dataDir + "PassProtected2003.mpp", "pass");
6
7   //Display result of conversion.
8   System.out.println("Process completed Successfully");

The following code example demonstrates how to check if the project file is password protected.

1ProjectFileInfo info = Project.getProjectFileInfo(dataDir + "project.mpp");
2System.out.println("Is file password protected?:" + info.isPasswordProtected());

Reading Project Online

The ProjectServerManager class provides the methods to retrieve projects from the specified Project Online account. The ProjectServerCredentials class shall be used to provide credentials that are used to connect to Project Online. Previously, Microsoft.SharePoint.Client.Runtime assembly was used to retrieve AuthToken but now Aspose.Tasks for Java provides an option to specify SiteUrl, username, and password to create a connection to Project Online.

The following lines of code show how to read the project online.

 1String sharepointDomainAddress = "https://contoso.sharepoint.com";
 2String userName = "admin@contoso.onmicrosoft.com";
 3String password = "MyPassword";
 4
 5ProjectServerCredentials credentials = new ProjectServerCredentials(sharepointDomainAddress, userName, password);
 6ProjectServerManager reader = new ProjectServerManager(credentials);
 7
 8for (ProjectInfo p : (Iterable<ProjectInfo>)reader.getProjectList())
 9{
10    System.out.println("Project Name:" + p.getName());
11    System.out.println("Project Created Date:" + p.getCreatedDate());
12    System.out.println("Project Last Saved Date:" + p.getLastSavedDate());
13}
14
15for (ProjectInfo p : (Iterable<ProjectInfo>)reader.getProjectList())
16{
17    Project project = reader.getProject(p.getId());
18    System.out.println("Project " + p.getName() + " loaded.");
19    System.out.println("Resources count:" + project.getResources().size());
20}
21        
Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.