blob: ef218d5a96913aef5646ccbc57b4fab7c251bcac [file] [log] [blame]
Gaurav Agrawal8a5af142016-06-15 13:58:01 +05301/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.yangutils.plugin.manager;
18
19import java.io.File;
20import java.io.FileInputStream;
21import java.io.FileOutputStream;
22import java.io.IOException;
23import java.io.InputStream;
24import java.io.ObjectInputStream;
25import java.io.ObjectOutputStream;
26import java.nio.file.Files;
27import java.nio.file.StandardCopyOption;
28import java.util.ArrayList;
29import java.util.Enumeration;
30import java.util.Iterator;
31import java.util.List;
32import java.util.Set;
33import java.util.jar.JarEntry;
34import java.util.jar.JarFile;
35import org.apache.maven.artifact.repository.ArtifactRepository;
36import org.apache.maven.model.Dependency;
37import org.apache.maven.model.Resource;
38import org.apache.maven.project.MavenProject;
39import org.onosproject.yangutils.datamodel.YangNode;
40import org.slf4j.Logger;
41import org.sonatype.plexus.build.incremental.BuildContext;
42
43import static org.onosproject.yangutils.utils.UtilConstants.HYPHEN;
44import static org.onosproject.yangutils.utils.UtilConstants.JAR;
45import static org.onosproject.yangutils.utils.UtilConstants.PERIOD;
46import static org.onosproject.yangutils.utils.UtilConstants.SLASH;
47import static org.onosproject.yangutils.utils.UtilConstants.TEMP;
48import static org.onosproject.yangutils.utils.UtilConstants.YANG_RESOURCES;
49import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getCamelCase;
50import static org.onosproject.yangutils.utils.io.impl.YangIoUtils.getPackageDirPathFromJavaJPackage;
51import static org.slf4j.LoggerFactory.getLogger;
52
53/**
54 * Represents YANG plugin utilities.
55 */
56public final class YangPluginUtils {
57
58 private static final Logger log = getLogger(YangPluginUtils.class);
59
60 private static final String TARGET_RESOURCE_PATH = SLASH + TEMP + SLASH + YANG_RESOURCES + SLASH;
61
62 private static final String SERIALIZED_FILE_EXTENSION = ".ser";
63
64 private YangPluginUtils() {
65 }
66
67 /**
68 * Adds generated source directory to the compilation root.
69 *
70 * @param source directory
71 * @param project current maven project
72 * @param context current build context
73 */
74 public static void addToCompilationRoot(String source, MavenProject project, BuildContext context) {
75 project.addCompileSourceRoot(source);
76 context.refresh(project.getBasedir());
77 log.info("Source directory added to compilation root: " + source);
78 }
79
80 /**
81 * Copies YANG files to the current project's output directory.
82 *
83 * @param yangFileInfo list of YANG files
84 * @param outputDir project's output directory
85 * @param project maven project
86 * @throws IOException when fails to copy files to destination resource directory
87 */
88 public static void copyYangFilesToTarget(Set<YangFileInfo> yangFileInfo, String outputDir, MavenProject project)
89 throws IOException {
90
91 List<File> files = getListOfFile(yangFileInfo);
92
93 String path = outputDir + TARGET_RESOURCE_PATH;
94 File targetDir = new File(path);
95 targetDir.mkdirs();
96
97 for (File file : files) {
98 Files.copy(file.toPath(),
99 new File(path + file.getName()).toPath(),
100 StandardCopyOption.REPLACE_EXISTING);
101 }
102 addToProjectResource(outputDir + SLASH + TEMP + SLASH, project);
103 }
104
105 /**
106 * Provides a list of files from list of strings.
107 *
108 * @param yangFileInfo set of yang file information
109 * @return list of files
110 */
111 private static List<File> getListOfFile(Set<YangFileInfo> yangFileInfo) {
112 List<File> files = new ArrayList<>();
113 Iterator<YangFileInfo> yangFileIterator = yangFileInfo.iterator();
114 while (yangFileIterator.hasNext()) {
115 YangFileInfo yangFile = yangFileIterator.next();
116 if (yangFile.isForTranslator()) {
117 files.add(new File(yangFile.getYangFileName()));
118 }
119 }
120 return files;
121 }
122
123 /**
124 * Serializes data-model.
125 *
126 * @param directory base directory for serialized files
127 * @param fileInfoSet YANG file info set
128 * @param project maven project
129 * @param operation true if need to add to resource
130 * @throws IOException when fails to do IO operations
131 */
132 public static void serializeDataModel(String directory, Set<YangFileInfo> fileInfoSet,
133 MavenProject project, boolean operation) throws IOException {
134
135 String serFileDirPath = directory + TARGET_RESOURCE_PATH;
136 File dir = new File(serFileDirPath);
137 dir.mkdirs();
138
139 if (operation) {
140 addToProjectResource(directory + SLASH + TEMP + SLASH, project);
141 }
142
143 for (YangFileInfo fileInfo : fileInfoSet) {
144
145 String serFileName = serFileDirPath + getCamelCase(fileInfo.getRootNode().getName(), null)
146 + SERIALIZED_FILE_EXTENSION;
147 fileInfo.setSerializedFile(serFileName);
148 FileOutputStream fileOutputStream = new FileOutputStream(serFileName);
149 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
150 objectOutputStream.writeObject(fileInfo.getRootNode());
151 objectOutputStream.close();
152 fileOutputStream.close();
153 }
154 }
155
156 /**
157 * Returns de-serializes YANG data-model nodes.
158 *
159 * @param serailizedfileInfoSet YANG file info set
160 * @return de-serializes YANG data-model nodes
161 * @throws IOException when fails do IO operations
162 */
163 public static List<YangNode> deSerializeDataModel(List<String> serailizedfileInfoSet) throws IOException {
164
165 List<YangNode> nodes = new ArrayList<>();
166 for (String fileInfo : serailizedfileInfoSet) {
167 YangNode node = null;
168 try {
169 FileInputStream fileInputStream = new FileInputStream(fileInfo);
170 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
171 node = (YangNode) objectInputStream.readObject();
172 nodes.add(node);
173 objectInputStream.close();
174 fileInputStream.close();
175 } catch (IOException | ClassNotFoundException e) {
176 throw new IOException(fileInfo + " not found.");
177 }
178 }
179 return nodes;
180 }
181
182 /**
183 * Returns list of jar path.
184 *
185 * @param project maven project
186 * @param localRepository local repository
187 * @param remoteRepos remote repository
188 * @return list of jar paths
189 */
190 private static List<String> resolveDependecyJarPath(MavenProject project, ArtifactRepository localRepository,
191 List<ArtifactRepository> remoteRepos) {
192
193 StringBuilder path = new StringBuilder();
194 List<String> jarPaths = new ArrayList<>();
195 for (Dependency dependency : project.getDependencies()) {
196
197 path.append(localRepository.getBasedir());
198 path.append(SLASH);
199 path.append(getPackageDirPathFromJavaJPackage(dependency.getGroupId()));
200 path.append(SLASH);
201 path.append(dependency.getArtifactId());
202 path.append(SLASH);
203 path.append(dependency.getVersion());
204 path.append(SLASH);
205 path.append(dependency.getArtifactId() + HYPHEN + dependency.getVersion() + PERIOD + JAR);
206 File jarFile = new File(path.toString());
207 if (jarFile.exists()) {
208 jarPaths.add(path.toString());
209 }
210 path.delete(0, path.length());
211 }
212
213 for (ArtifactRepository repo : remoteRepos) {
214 // TODO: add resolver for remote repo.
215 }
216 return jarPaths;
217 }
218
219 /**
220 * Resolves inter jar dependencies.
221 *
222 * @param project current maven project
223 * @param localRepository local maven repository
224 * @param remoteRepos list of remote repository
225 * @param directory directory for serialized files
226 * @return list of resolved datamodel nodes
227 * @throws IOException when fails to do IO operations
228 */
229 public static List<YangNode> resolveInterJarDependencies(MavenProject project, ArtifactRepository localRepository,
230 List<ArtifactRepository> remoteRepos, String directory)
231 throws IOException {
232
233 List<String> dependeciesJarPaths = resolveDependecyJarPath(project, localRepository, remoteRepos);
234 List<YangNode> resolvedDataModelNodes = new ArrayList<>();
235 for (String dependecy : dependeciesJarPaths) {
236 resolvedDataModelNodes.addAll(deSerializeDataModel(parseJarFile(dependecy, directory)));
237 }
238 return resolvedDataModelNodes;
239 }
240
241 /**
242 * Parses jar file and returns list of serialized file names.
243 *
244 * @param jarFile jar file to be parsed
245 * @param directory directory for keeping the searized files
246 * @return list of serialized files
247 * @throws IOException when fails to do IO operations
248 */
249 public static List<String> parseJarFile(String jarFile, String directory)
250 throws IOException {
251
252 List<String> serailizedFiles = new ArrayList<>();
253 JarFile jar = new JarFile(jarFile);
254 Enumeration<?> enumEntries = jar.entries();
255
256 File serializedFileDir = new File(directory);
257 serializedFileDir.mkdirs();
258 while (enumEntries.hasMoreElements()) {
259 JarEntry file = (JarEntry) enumEntries.nextElement();
260 if (file.getName().endsWith(SERIALIZED_FILE_EXTENSION)) {
261 if (file.getName().contains(SLASH)) {
262 String[] strArray = file.getName().split(SLASH);
263 String tempPath = "";
264 for (int i = 0; i < strArray.length - 1; i++) {
265 tempPath = SLASH + tempPath + SLASH + strArray[i];
266 }
267 File dir = new File(directory + tempPath);
268 dir.mkdirs();
269 }
270 File serailizedFile = new File(directory + SLASH + file.getName());
271 if (file.isDirectory()) {
272 serailizedFile.mkdirs();
273 continue;
274 }
275 InputStream inputStream = jar.getInputStream(file);
276
277 FileOutputStream fileOutputStream = new FileOutputStream(serailizedFile);
278 while (inputStream.available() > 0) {
279 fileOutputStream.write(inputStream.read());
280 }
281 fileOutputStream.close();
282 inputStream.close();
283 serailizedFiles.add(serailizedFile.toString());
284 }
285 }
286 jar.close();
287 return serailizedFiles;
288 }
289
290 /* Adds directory to resources of project */
291 private static void addToProjectResource(String dir, MavenProject project) {
292 Resource rsc = new Resource();
293 rsc.setDirectory(dir);
294 project.addResource(rsc);
295 }
296}