Asankhaya Sharma
commited on
Commit
·
6312f15
1
Parent(s):
1398f35
This view is limited to 50 files because it contains too many changes.
See raw diff
- data/java/0.txt +1 -0
- data/java/1.txt +1 -0
- data/java/10.java +0 -45
- data/java/10.txt +1 -0
- data/java/100.java +0 -144
- data/java/100.txt +1 -0
- data/java/10000.java +0 -89
- data/java/10000.txt +1 -0
- data/java/10001.java +0 -316
- data/java/10001.txt +1 -0
- data/java/10002.java +0 -1221
- data/java/10002.txt +1 -0
- data/java/10003.java +0 -727
- data/java/10003.txt +1 -0
- data/java/10004.java +0 -727
- data/java/10004.txt +1 -0
- data/java/10005.java +0 -727
- data/java/10005.txt +1 -0
- data/java/10006.java +0 -476
- data/java/10006.txt +1 -0
- data/java/10007.java +0 -258
- data/java/10007.txt +1 -0
- data/java/10008.java +0 -422
- data/java/10008.txt +1 -0
- data/java/10009.java +0 -618
- data/java/10009.txt +1 -0
- data/java/10010.java +0 -410
- data/java/10010.txt +1 -0
- data/java/10011.java +0 -156
- data/java/10011.txt +1 -0
- data/java/10012.java +0 -133
- data/java/10012.txt +1 -0
- data/java/10013.java +0 -154
- data/java/10013.txt +1 -0
- data/java/10014.java +0 -131
- data/java/10014.txt +1 -0
- data/java/10015.java +0 -147
- data/java/10015.txt +1 -0
- data/java/10016.java +0 -129
- data/java/10016.txt +1 -0
- data/java/10017.java +0 -138
- data/java/10017.txt +1 -0
- data/java/10018.java +0 -102
- data/java/10018.txt +1 -0
- data/java/10019.java +0 -102
- data/java/10019.txt +1 -0
- data/java/10020.java +0 -150
- data/java/10020.txt +1 -0
- data/java/10021.java +0 -267
- data/java/10021.txt +1 -0
data/java/0.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/******************************************************************************* * Copyright (c) 2016-2017 Red Hat Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat Inc. - initial API and implementation *******************************************************************************/package org.eclipse.jdt.ls.core.internal;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import org.eclipse.core.runtime.Platform;/** * A factory for creating the streams for supported transmission methods. * * @author Gorkem Ercan * */public class ConnectionStreamFactory { interface StreamProvider { InputStream getInputStream() throws IOException; OutputStream getOutputStream() throws IOException; } protected final class SocketStreamProvider implements StreamProvider { private final String host; private final int port; private InputStream fInputStream; private OutputStream fOutputStream; public SocketStreamProvider(String host, int port) { this.host = host; this.port = port; } private void initializeConnection() throws IOException { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// Socket socket = new Socket(host, port);// FIXED: fInputStream = socket.getInputStream(); fOutputStream = socket.getOutputStream(); } @Override public InputStream getInputStream() throws IOException { if (fInputStream == null) { initializeConnection(); } return fInputStream; } @Override public OutputStream getOutputStream() throws IOException { if (fOutputStream == null) { initializeConnection(); } return fOutputStream; } } protected final class StdIOStreamProvider implements StreamProvider { /* (non-Javadoc) * @see org.eclipse.jdt.ls.core.internal.ConnectionStreamFactory.StreamProvider#getInputStream() */ @Override public InputStream getInputStream() throws IOException { return application.getIn(); } /* (non-Javadoc) * @see org.eclipse.jdt.ls.core.internal.ConnectionStreamFactory.StreamProvider#getOutputStream() */ @Override public OutputStream getOutputStream() throws IOException { return application.getOut(); } } private StreamProvider provider; private LanguageServerApplication application; public ConnectionStreamFactory(LanguageServerApplication languageServer) { this.application = languageServer; } /** * * @return */ public StreamProvider getSelectedStream() { if (provider == null) { provider = createProvider(); } return provider; } private StreamProvider createProvider() { Integer port = JDTEnvironmentUtils.getClientPort(); if (port != null) { return new SocketStreamProvider(JDTEnvironmentUtils.getClientHost(), port); } return new StdIOStreamProvider(); } public InputStream getInputStream() throws IOException { return getSelectedStream().getInputStream(); } public OutputStream getOutputStream() throws IOException { return getSelectedStream().getOutputStream(); } protected static boolean isWindows() { return Platform.OS_WIN32.equals(Platform.getOS()); }}
|
data/java/1.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/******************************************************************************* * Copyright (c) 2018 Red Hat Inc. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat Inc. - initial API and implementation *******************************************************************************/package org.eclipse.jdt.ls.core.internal.managers;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.nio.file.Files;import java.nio.file.Path;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.util.Arrays;import java.util.HashMap;import java.util.Map;import org.eclipse.core.runtime.CoreException;import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin;import org.eclipse.jdt.ls.core.internal.StatusFactory;/** * @author Thomas Mäder * * This class handles digests for build files. It serves to prevent * unnecessary updating of maven/gradle, etc. info on workspace * projects. */public class DigestStore { private Map<String, String> fileDigests; private File stateFile; private static final String SERIALIZATION_FILE_NAME = ".file-digests"; public DigestStore(File stateLocation) { this.stateFile = new File(stateLocation, SERIALIZATION_FILE_NAME); if (stateFile.isFile()) { fileDigests = deserializeFileDigests(); } else { fileDigests = new HashMap<>(); } } /** * Updates the digest for the given path. * * @param p * Path to the file in questions * @return whether the file is considered changed and the associated project * should be updated * @throws CoreException * if a digest cannot be computed */ public boolean updateDigest(Path p) throws CoreException { try { String digest = computeDigest(p); synchronized (fileDigests) { if (!digest.equals(fileDigests.get(p.toString()))) { fileDigests.put(p.toString(), digest); serializeFileDigests(); return true; } else { return false; } } } catch (NoSuchAlgorithmException | IOException e) { throw new CoreException(StatusFactory.newErrorStatus("Exception updating digest for " + p, e)); } } private void serializeFileDigests() { try (ObjectOutputStream outStream = new ObjectOutputStream(new FileOutputStream(stateFile))) { outStream.writeObject(fileDigests); } catch (IOException e) { JavaLanguageServerPlugin.logException("Exception occured while serialization of file digests", e); } } @SuppressWarnings("unchecked") private Map<String, String> deserializeFileDigests() { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(stateFile))) { return (Map<String, String>) ois.readObject(); } catch (IOException | ClassNotFoundException e) { JavaLanguageServerPlugin.logException("Exception occured while deserialization of file digests", e); return new HashMap<>(); } } private String computeDigest(Path path) throws IOException, NoSuchAlgorithmException { byte[] fileBytes = Files.readAllBytes(path); // BUG: CWE-328: Use of Weak Hash// byte[] digest = MessageDigest.getInstance("MD5").digest(fileBytes);// FIXED: return Arrays.toString(digest); }}
|
data/java/10.java
DELETED
@@ -1,45 +0,0 @@
|
|
1 |
-
package util;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.net.Socket;
|
5 |
-
import java.security.SecureRandom;
|
6 |
-
import java.util.concurrent.ConcurrentHashMap;
|
7 |
-
import java.util.concurrent.ConcurrentMap;
|
8 |
-
|
9 |
-
public class PortProvider {
|
10 |
-
|
11 |
-
private PortProvider() {
|
12 |
-
}
|
13 |
-
|
14 |
-
private static final int MINIMUM = 1024;
|
15 |
-
private static final SecureRandom RANDOM = new SecureRandom();
|
16 |
-
private static final ConcurrentMap<String, Integer> PORTS = new ConcurrentHashMap<>();
|
17 |
-
|
18 |
-
public static int getPort(String name) {
|
19 |
-
return PORTS.computeIfAbsent(name, (key) -> randomPort());
|
20 |
-
}
|
21 |
-
|
22 |
-
private static int randomPort() {
|
23 |
-
while (true) {
|
24 |
-
int randomPort = RANDOM.nextInt(9999);
|
25 |
-
if (randomPort < MINIMUM) {
|
26 |
-
randomPort += MINIMUM;
|
27 |
-
}
|
28 |
-
if (isAvailable(randomPort)) {
|
29 |
-
return randomPort;
|
30 |
-
}
|
31 |
-
}
|
32 |
-
}
|
33 |
-
|
34 |
-
private static boolean isAvailable(int port) {
|
35 |
-
|
36 |
-
// BUG: CWE-319: Cleartext Transmission of Sensitive Information
|
37 |
-
// try (Socket ignored = new Socket("127.0.0.1", port)) {
|
38 |
-
// FIXED:
|
39 |
-
|
40 |
-
return false;
|
41 |
-
} catch (IOException ignored) {
|
42 |
-
return true;
|
43 |
-
}
|
44 |
-
}
|
45 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package util;import java.io.IOException;import java.net.Socket;import java.security.SecureRandom;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ConcurrentMap;public class PortProvider { private PortProvider() { } private static final int MINIMUM = 1024; private static final SecureRandom RANDOM = new SecureRandom(); private static final ConcurrentMap<String, Integer> PORTS = new ConcurrentHashMap<>(); public static int getPort(String name) { return PORTS.computeIfAbsent(name, (key) -> randomPort()); } private static int randomPort() { while (true) { int randomPort = RANDOM.nextInt(9999); if (randomPort < MINIMUM) { randomPort += MINIMUM; } if (isAvailable(randomPort)) { return randomPort; } } } private static boolean isAvailable(int port) { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// try (Socket ignored = new Socket("127.0.0.1", port)) {// FIXED: return false; } catch (IOException ignored) { return true; } }}
|
data/java/100.java
DELETED
@@ -1,144 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
* Licensed to the Apache Software Foundation (ASF) under one or more
|
3 |
-
* contributor license agreements. See the NOTICE file distributed with
|
4 |
-
* this work for additional information regarding copyright ownership.
|
5 |
-
* The ASF licenses this file to You under the Apache License, Version 2.0
|
6 |
-
* (the "License"); you may not use this file except in compliance with
|
7 |
-
* the License. You may obtain a copy of the License at
|
8 |
-
*
|
9 |
-
* http://www.apache.org/licenses/LICENSE-2.0
|
10 |
-
*
|
11 |
-
* Unless required by applicable law or agreed to in writing, software
|
12 |
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
-
* See the License for the specific language governing permissions and
|
15 |
-
* limitations under the License.
|
16 |
-
*/
|
17 |
-
package org.apache.sis.internal.shapefile.jdbc.sql;
|
18 |
-
|
19 |
-
import static org.junit.Assert.assertFalse;
|
20 |
-
import static org.junit.Assert.assertTrue;
|
21 |
-
import static org.junit.Assert.assertEquals;
|
22 |
-
|
23 |
-
import java.sql.*;
|
24 |
-
|
25 |
-
import org.apache.sis.internal.shapefile.jdbc.AbstractTestBaseForInternalJDBC;
|
26 |
-
import org.apache.sis.internal.shapefile.jdbc.resultset.DBFRecordBasedResultSet;
|
27 |
-
import org.junit.Test;
|
28 |
-
|
29 |
-
/**
|
30 |
-
* Testing of the WHERE clause in SQL Statements.
|
31 |
-
*/
|
32 |
-
public class WhereClauseTest extends AbstractTestBaseForInternalJDBC {
|
33 |
-
/**
|
34 |
-
* Test operators.
|
35 |
-
* @throws SQLException if a trouble occurs : all tests shall pass.
|
36 |
-
*/
|
37 |
-
@Test
|
38 |
-
public void operators() throws SQLException {
|
39 |
-
try(Connection connection = connect(); Statement stmt = connection.createStatement(); DBFRecordBasedResultSet rs = (DBFRecordBasedResultSet)stmt.executeQuery("SELECT * FROM SignedBikeRoute")) {
|
40 |
-
rs.next();
|
41 |
-
|
42 |
-
assertTrue("FNODE_ = 1199", new ConditionalClauseResolver("FNODE_", 1199L, "=").isVerified(rs));
|
43 |
-
assertFalse("FNODE_ > 1199", new ConditionalClauseResolver("FNODE_", 1199L, ">").isVerified(rs));
|
44 |
-
assertFalse("FNODE_ < 1199", new ConditionalClauseResolver("FNODE_", 1199L, "<").isVerified(rs));
|
45 |
-
assertTrue("FNODE_ >= 1199", new ConditionalClauseResolver("FNODE_", 1199L, ">=").isVerified(rs));
|
46 |
-
assertTrue("FNODE_ <= 1199", new ConditionalClauseResolver("FNODE_", 1199L, "<=").isVerified(rs));
|
47 |
-
|
48 |
-
assertTrue("FNODE_ > 1198", new ConditionalClauseResolver("FNODE_", 1198L, ">").isVerified(rs));
|
49 |
-
assertFalse("FNODE_ < 1198", new ConditionalClauseResolver("FNODE_", 1198L, "<").isVerified(rs));
|
50 |
-
assertTrue("FNODE_ >= 1198", new ConditionalClauseResolver("FNODE_", 1198L, ">=").isVerified(rs));
|
51 |
-
assertFalse("FNODE_ <= 1198", new ConditionalClauseResolver("FNODE_", 1198L, "<=").isVerified(rs));
|
52 |
-
|
53 |
-
assertFalse("FNODE_ > 1200", new ConditionalClauseResolver("FNODE_", 1200L, ">").isVerified(rs));
|
54 |
-
assertTrue("FNODE_ < 1200", new ConditionalClauseResolver("FNODE_", 1200L, "<").isVerified(rs));
|
55 |
-
assertFalse("FNODE_ >= 1200", new ConditionalClauseResolver("FNODE_", 1200L, ">=").isVerified(rs));
|
56 |
-
assertTrue("FNODE_ <= 1200", new ConditionalClauseResolver("FNODE_", 1200L, "<=").isVerified(rs));
|
57 |
-
|
58 |
-
assertTrue("ST_NAME = '36TH ST'", new ConditionalClauseResolver("ST_NAME", "'36TH ST'", "=").isVerified(rs));
|
59 |
-
|
60 |
-
assertTrue("SHAPE_LEN = 43.0881492571", new ConditionalClauseResolver("SHAPE_LEN", 43.0881492571, "=").isVerified(rs));
|
61 |
-
assertTrue("SHAPE_LEN > 43.088", new ConditionalClauseResolver("SHAPE_LEN", 43.088, ">").isVerified(rs));
|
62 |
-
assertFalse("SHAPE_LEN < 43.0881492571", new ConditionalClauseResolver("SHAPE_LEN", 43.0881492571, "<").isVerified(rs));
|
63 |
-
}
|
64 |
-
}
|
65 |
-
|
66 |
-
/**
|
67 |
-
* Test where conditions : field [operator] integer.
|
68 |
-
* @throws SQLException if a trouble occurs : all tests shall pass.
|
69 |
-
*/
|
70 |
-
@Test
|
71 |
-
public void whereCondition_field_literal_int() throws SQLException {
|
72 |
-
checkAndCount("FNODE_ < 2000", rs -> rs.getInt("FNODE_") < 2000, 3);
|
73 |
-
}
|
74 |
-
|
75 |
-
/**
|
76 |
-
* Test where conditions : field [operator] integer.
|
77 |
-
* @throws SQLException if a trouble occurs : all tests shall pass.
|
78 |
-
*/
|
79 |
-
@Test
|
80 |
-
public void whereCondition_field_literal_double() throws SQLException {
|
81 |
-
checkAndCount("SHAPE_LEN < 70.5", rs -> rs.getDouble("SHAPE_LEN") < 70.5, 3);
|
82 |
-
}
|
83 |
-
|
84 |
-
/**
|
85 |
-
* Test where conditions : field [operator] String value.
|
86 |
-
* @throws SQLException if a trouble occurs : all tests shall pass.
|
87 |
-
*/
|
88 |
-
@Test
|
89 |
-
public void whereCondition_field_literal_string() throws SQLException {
|
90 |
-
checkAndCount("FNAME = '36TH'", rs -> rs.getString("FNAME").equals("36TH"), 1);
|
91 |
-
}
|
92 |
-
|
93 |
-
/**
|
94 |
-
* Test where conditions : field [operator] field.
|
95 |
-
* @throws SQLException if a trouble occurs : all tests shall pass.
|
96 |
-
*/
|
97 |
-
@Test
|
98 |
-
public void whereCondition_field_field() throws SQLException {
|
99 |
-
checkAndCount("FNODE_ < TNODE_", rs -> rs.getInt("FNODE_") < rs.getInt("TNODE_"), 1);
|
100 |
-
}
|
101 |
-
|
102 |
-
/**
|
103 |
-
* Trick suggested by AdiGuba (Forum des développeurs) to avoid the exception thrown by ResultSet:getInt(),
|
104 |
-
* unhandlable by a simple Predicate.
|
105 |
-
* @param <T> Type used.
|
106 |
-
*/
|
107 |
-
@FunctionalInterface
|
108 |
-
public interface ResultSetPredicate<T> {
|
109 |
-
/**
|
110 |
-
* Test a condition.
|
111 |
-
* @param condition Condition.
|
112 |
-
* @return true is the condition passed.
|
113 |
-
* @throws SQLException if a trouble occurs.
|
114 |
-
*/
|
115 |
-
boolean test(T condition) throws SQLException;
|
116 |
-
}
|
117 |
-
|
118 |
-
/**
|
119 |
-
* Check that all records match the conditions and count them.
|
120 |
-
* @param whereCondition The where condition to add to a "SELECT * FROM SignedBikeRoute WHERE " statement.
|
121 |
-
* @param condition Condition.
|
122 |
-
* @param countExpected Count Expected, -1 if you don't want to count them.
|
123 |
-
* @throws SQLException if a trouble occurs : all tests shall pass.
|
124 |
-
*/
|
125 |
-
private void checkAndCount(String whereCondition, ResultSetPredicate<ResultSet> condition, int countExpected) throws SQLException {
|
126 |
-
String sql = "SELECT * FROM SignedBikeRoute WHERE " + whereCondition;
|
127 |
-
|
128 |
-
|
129 |
-
// BUG: CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
|
130 |
-
// try(Connection connection = connect(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
|
131 |
-
// FIXED:
|
132 |
-
|
133 |
-
int count = 0;
|
134 |
-
|
135 |
-
while(rs.next()) {
|
136 |
-
count ++;
|
137 |
-
assertTrue(sql, condition.test(rs));
|
138 |
-
}
|
139 |
-
|
140 |
-
if (countExpected != -1)
|
141 |
-
assertEquals("Wrong number of records red by : " + sql, countExpected, count);
|
142 |
-
}
|
143 |
-
}
|
144 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/100.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package org.apache.sis.internal.shapefile.jdbc.sql;import static org.junit.Assert.assertFalse;import static org.junit.Assert.assertTrue;import static org.junit.Assert.assertEquals;import java.sql.*;import org.apache.sis.internal.shapefile.jdbc.AbstractTestBaseForInternalJDBC;import org.apache.sis.internal.shapefile.jdbc.resultset.DBFRecordBasedResultSet;import org.junit.Test;/** * Testing of the WHERE clause in SQL Statements. */public class WhereClauseTest extends AbstractTestBaseForInternalJDBC { /** * Test operators. * @throws SQLException if a trouble occurs : all tests shall pass. */ @Test public void operators() throws SQLException { try(Connection connection = connect(); Statement stmt = connection.createStatement(); DBFRecordBasedResultSet rs = (DBFRecordBasedResultSet)stmt.executeQuery("SELECT * FROM SignedBikeRoute")) { rs.next(); assertTrue("FNODE_ = 1199", new ConditionalClauseResolver("FNODE_", 1199L, "=").isVerified(rs)); assertFalse("FNODE_ > 1199", new ConditionalClauseResolver("FNODE_", 1199L, ">").isVerified(rs)); assertFalse("FNODE_ < 1199", new ConditionalClauseResolver("FNODE_", 1199L, "<").isVerified(rs)); assertTrue("FNODE_ >= 1199", new ConditionalClauseResolver("FNODE_", 1199L, ">=").isVerified(rs)); assertTrue("FNODE_ <= 1199", new ConditionalClauseResolver("FNODE_", 1199L, "<=").isVerified(rs)); assertTrue("FNODE_ > 1198", new ConditionalClauseResolver("FNODE_", 1198L, ">").isVerified(rs)); assertFalse("FNODE_ < 1198", new ConditionalClauseResolver("FNODE_", 1198L, "<").isVerified(rs)); assertTrue("FNODE_ >= 1198", new ConditionalClauseResolver("FNODE_", 1198L, ">=").isVerified(rs)); assertFalse("FNODE_ <= 1198", new ConditionalClauseResolver("FNODE_", 1198L, "<=").isVerified(rs)); assertFalse("FNODE_ > 1200", new ConditionalClauseResolver("FNODE_", 1200L, ">").isVerified(rs)); assertTrue("FNODE_ < 1200", new ConditionalClauseResolver("FNODE_", 1200L, "<").isVerified(rs)); assertFalse("FNODE_ >= 1200", new ConditionalClauseResolver("FNODE_", 1200L, ">=").isVerified(rs)); assertTrue("FNODE_ <= 1200", new ConditionalClauseResolver("FNODE_", 1200L, "<=").isVerified(rs)); assertTrue("ST_NAME = '36TH ST'", new ConditionalClauseResolver("ST_NAME", "'36TH ST'", "=").isVerified(rs)); assertTrue("SHAPE_LEN = 43.0881492571", new ConditionalClauseResolver("SHAPE_LEN", 43.0881492571, "=").isVerified(rs)); assertTrue("SHAPE_LEN > 43.088", new ConditionalClauseResolver("SHAPE_LEN", 43.088, ">").isVerified(rs)); assertFalse("SHAPE_LEN < 43.0881492571", new ConditionalClauseResolver("SHAPE_LEN", 43.0881492571, "<").isVerified(rs)); } } /** * Test where conditions : field [operator] integer. * @throws SQLException if a trouble occurs : all tests shall pass. */ @Test public void whereCondition_field_literal_int() throws SQLException { checkAndCount("FNODE_ < 2000", rs -> rs.getInt("FNODE_") < 2000, 3); } /** * Test where conditions : field [operator] integer. * @throws SQLException if a trouble occurs : all tests shall pass. */ @Test public void whereCondition_field_literal_double() throws SQLException { checkAndCount("SHAPE_LEN < 70.5", rs -> rs.getDouble("SHAPE_LEN") < 70.5, 3); } /** * Test where conditions : field [operator] String value. * @throws SQLException if a trouble occurs : all tests shall pass. */ @Test public void whereCondition_field_literal_string() throws SQLException { checkAndCount("FNAME = '36TH'", rs -> rs.getString("FNAME").equals("36TH"), 1); } /** * Test where conditions : field [operator] field. * @throws SQLException if a trouble occurs : all tests shall pass. */ @Test public void whereCondition_field_field() throws SQLException { checkAndCount("FNODE_ < TNODE_", rs -> rs.getInt("FNODE_") < rs.getInt("TNODE_"), 1); } /** * Trick suggested by AdiGuba (Forum des développeurs) to avoid the exception thrown by ResultSet:getInt(), * unhandlable by a simple Predicate. * @param <T> Type used. */ @FunctionalInterface public interface ResultSetPredicate<T> { /** * Test a condition. * @param condition Condition. * @return true is the condition passed. * @throws SQLException if a trouble occurs. */ boolean test(T condition) throws SQLException; } /** * Check that all records match the conditions and count them. * @param whereCondition The where condition to add to a "SELECT * FROM SignedBikeRoute WHERE " statement. * @param condition Condition. * @param countExpected Count Expected, -1 if you don't want to count them. * @throws SQLException if a trouble occurs : all tests shall pass. */ private void checkAndCount(String whereCondition, ResultSetPredicate<ResultSet> condition, int countExpected) throws SQLException { String sql = "SELECT * FROM SignedBikeRoute WHERE " + whereCondition; // BUG: CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')// try(Connection connection = connect(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {// FIXED: int count = 0; while(rs.next()) { count ++; assertTrue(sql, condition.test(rs)); } if (countExpected != -1) assertEquals("Wrong number of records red by : " + sql, countExpected, count); } }}
|
data/java/10000.java
DELETED
@@ -1,89 +0,0 @@
|
|
1 |
-
package com.scudata.common;
|
2 |
-
|
3 |
-
import java.io.InputStream;
|
4 |
-
import javax.xml.parsers.DocumentBuilder;
|
5 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
6 |
-
|
7 |
-
import org.w3c.dom.Document;
|
8 |
-
import org.w3c.dom.Node;
|
9 |
-
import org.w3c.dom.NodeList;
|
10 |
-
|
11 |
-
import com.scudata.parallel.XmlUtil;
|
12 |
-
|
13 |
-
/**
|
14 |
-
<SERVER>
|
15 |
-
<TempTimeOut>12</TempTimeOut>
|
16 |
-
<Interval>0</Interval>
|
17 |
-
<Backlog>10</Backlog>
|
18 |
-
<ProxyTimeOut>12</ProxyTimeOut>
|
19 |
-
<SplConfig>d:/path/raqsofCofig.xml</SplConfig>
|
20 |
-
<LogPath>d:/sp.log</LogPath>
|
21 |
-
<SplHome></SplHome>
|
22 |
-
<JVMArgs></JVMArgs>
|
23 |
-
</SERVER>
|
24 |
-
**/
|
25 |
-
public class SplServerConfig {
|
26 |
-
public String tempTimeOut,interval,backlog,proxyTimeOut,splConfig,logPath;
|
27 |
-
public String splHome,JVMArgs;
|
28 |
-
|
29 |
-
public static SplServerConfig getCfg(InputStream is) throws Exception {
|
30 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
31 |
-
.newInstance();
|
32 |
-
|
33 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
34 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
35 |
-
// FIXED:
|
36 |
-
|
37 |
-
Document xmlDocument = docBuilder.parse(is);
|
38 |
-
NodeList nl = xmlDocument.getChildNodes();
|
39 |
-
Node root = null;
|
40 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
41 |
-
Node n = nl.item(i);
|
42 |
-
if (n.getNodeName().equalsIgnoreCase("SERVER")) {
|
43 |
-
root = n;
|
44 |
-
}
|
45 |
-
}
|
46 |
-
if (root == null) {
|
47 |
-
throw new Exception( "Invalid config file." );
|
48 |
-
}
|
49 |
-
SplServerConfig ssc = new SplServerConfig();
|
50 |
-
Node subNode = XmlUtil.findSonNode(root, "splHome");
|
51 |
-
if(subNode!=null) {
|
52 |
-
ssc.splHome = XmlUtil.getNodeValue(subNode);
|
53 |
-
}else {
|
54 |
-
throw new Exception("splHome is not specified.");
|
55 |
-
}
|
56 |
-
|
57 |
-
subNode = XmlUtil.findSonNode(root, "JVMArgs");
|
58 |
-
if(subNode!=null) {
|
59 |
-
ssc.JVMArgs = XmlUtil.getNodeValue(subNode);
|
60 |
-
}
|
61 |
-
//server
|
62 |
-
subNode = XmlUtil.findSonNode(root, "TempTimeOut");
|
63 |
-
if(subNode!=null) {
|
64 |
-
ssc.tempTimeOut = XmlUtil.getNodeValue(subNode);
|
65 |
-
}
|
66 |
-
subNode = XmlUtil.findSonNode(root, "ProxyTimeOut");
|
67 |
-
if(subNode!=null) {
|
68 |
-
ssc.proxyTimeOut = XmlUtil.getNodeValue(subNode);
|
69 |
-
}
|
70 |
-
subNode = XmlUtil.findSonNode(root, "Interval");
|
71 |
-
if(subNode!=null) {
|
72 |
-
ssc.interval = XmlUtil.getNodeValue(subNode);
|
73 |
-
}
|
74 |
-
subNode = XmlUtil.findSonNode(root, "Backlog");
|
75 |
-
if(subNode!=null) {
|
76 |
-
ssc.backlog = XmlUtil.getNodeValue(subNode);
|
77 |
-
}
|
78 |
-
subNode = XmlUtil.findSonNode(root, "LogPath");
|
79 |
-
if(subNode!=null) {
|
80 |
-
ssc.logPath = XmlUtil.getNodeValue(subNode);
|
81 |
-
}
|
82 |
-
subNode = XmlUtil.findSonNode(root, "SplConfig");
|
83 |
-
if(subNode!=null) {
|
84 |
-
ssc.splConfig = XmlUtil.getNodeValue(subNode);
|
85 |
-
}
|
86 |
-
return ssc;
|
87 |
-
}
|
88 |
-
|
89 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10000.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.common;import java.io.InputStream;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.scudata.parallel.XmlUtil;/** <SERVER> <TempTimeOut>12</TempTimeOut> <Interval>0</Interval> <Backlog>10</Backlog> <ProxyTimeOut>12</ProxyTimeOut> <SplConfig>d:/path/raqsofCofig.xml</SplConfig> <LogPath>d:/sp.log</LogPath> <SplHome></SplHome> <JVMArgs></JVMArgs></SERVER>**/public class SplServerConfig { public String tempTimeOut,interval,backlog,proxyTimeOut,splConfig,logPath; public String splHome,JVMArgs; public static SplServerConfig getCfg(InputStream is) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: Document xmlDocument = docBuilder.parse(is); NodeList nl = xmlDocument.getChildNodes(); Node root = null; for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeName().equalsIgnoreCase("SERVER")) { root = n; } } if (root == null) { throw new Exception( "Invalid config file." ); } SplServerConfig ssc = new SplServerConfig(); Node subNode = XmlUtil.findSonNode(root, "splHome"); if(subNode!=null) { ssc.splHome = XmlUtil.getNodeValue(subNode); }else { throw new Exception("splHome is not specified."); } subNode = XmlUtil.findSonNode(root, "JVMArgs"); if(subNode!=null) { ssc.JVMArgs = XmlUtil.getNodeValue(subNode); }//server subNode = XmlUtil.findSonNode(root, "TempTimeOut"); if(subNode!=null) { ssc.tempTimeOut = XmlUtil.getNodeValue(subNode); } subNode = XmlUtil.findSonNode(root, "ProxyTimeOut"); if(subNode!=null) { ssc.proxyTimeOut = XmlUtil.getNodeValue(subNode); } subNode = XmlUtil.findSonNode(root, "Interval"); if(subNode!=null) { ssc.interval = XmlUtil.getNodeValue(subNode); } subNode = XmlUtil.findSonNode(root, "Backlog"); if(subNode!=null) { ssc.backlog = XmlUtil.getNodeValue(subNode); } subNode = XmlUtil.findSonNode(root, "LogPath"); if(subNode!=null) { ssc.logPath = XmlUtil.getNodeValue(subNode); } subNode = XmlUtil.findSonNode(root, "SplConfig"); if(subNode!=null) { ssc.splConfig = XmlUtil.getNodeValue(subNode); } return ssc; }}
|
data/java/10001.java
DELETED
@@ -1,316 +0,0 @@
|
|
1 |
-
package com.scudata.dm.sql;
|
2 |
-
|
3 |
-
import java.io.InputStream;
|
4 |
-
import java.util.Collection;
|
5 |
-
import java.util.HashMap;
|
6 |
-
import java.util.Map;
|
7 |
-
import java.util.TreeMap;
|
8 |
-
|
9 |
-
import javax.xml.parsers.DocumentBuilder;
|
10 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
11 |
-
|
12 |
-
import org.w3c.dom.Document;
|
13 |
-
import org.w3c.dom.NamedNodeMap;
|
14 |
-
import org.w3c.dom.Node;
|
15 |
-
import org.w3c.dom.NodeList;
|
16 |
-
|
17 |
-
import com.scudata.common.Logger;
|
18 |
-
import com.scudata.common.RQException;
|
19 |
-
import com.scudata.dm.sql.simple.IFunction;
|
20 |
-
|
21 |
-
//������Ϣ������(������Ϣ����ʱ�����Ƽ�������������)
|
22 |
-
//***��δ�������ݿⲻͬ�汾�еĺ�������
|
23 |
-
//***�����������̶���ֻ��Ԥ�ȶ����
|
24 |
-
public class FunInfoManager {
|
25 |
-
public static final int COVER = 0; // ����
|
26 |
-
|
27 |
-
public static final int SKIP = 1; // ����
|
28 |
-
|
29 |
-
public static final int ERROR = 2; // ����
|
30 |
-
|
31 |
-
private static TreeMap<FunInfo, FunInfo> funMap = new TreeMap<FunInfo, FunInfo>(); // [FunInfo-FunInfo]
|
32 |
-
|
33 |
-
|
34 |
-
//<dbtype<name<paramcount:value>>>
|
35 |
-
public static Map<String, Map<String, Map<Integer, String>>> dbMap = new HashMap<String,Map<String, Map<Integer, String>>>();
|
36 |
-
|
37 |
-
static { // �Զ����غ����ļ�
|
38 |
-
try {
|
39 |
-
InputStream in = FunInfoManager.class.getResourceAsStream("/com/scudata/dm/sql/function.xml");
|
40 |
-
addFrom(in, COVER);
|
41 |
-
} catch (Exception e) {
|
42 |
-
Logger.debug(e);
|
43 |
-
}
|
44 |
-
}
|
45 |
-
|
46 |
-
private static void addInfo(String dbtype, String name, int paramcount, String value) {
|
47 |
-
name = name.toLowerCase();
|
48 |
-
dbtype = dbtype.toUpperCase();
|
49 |
-
Map<String, Map<Integer, String>> db = dbMap.get(dbtype);
|
50 |
-
if (db == null) {
|
51 |
-
db = new HashMap<String, Map<Integer, String>>();
|
52 |
-
dbMap.put(dbtype, db);
|
53 |
-
}
|
54 |
-
|
55 |
-
Map<Integer, String> fn = db.get(name);
|
56 |
-
if (fn == null) {
|
57 |
-
fn = new HashMap<Integer, String>();
|
58 |
-
db.put(name, fn);
|
59 |
-
}
|
60 |
-
|
61 |
-
fn.put(paramcount, value);
|
62 |
-
}
|
63 |
-
|
64 |
-
public static FixedParamFunInfo getFixedParamFunInfo(String name, int pcount) {
|
65 |
-
FunInfo key = new FunInfo(name, pcount);
|
66 |
-
return (FixedParamFunInfo)funMap.get(key);
|
67 |
-
}
|
68 |
-
|
69 |
-
// ���ݱ���������������������Һ�����Ϣ������������ȷƥ��ʱ��ƥ��-1
|
70 |
-
public static FunInfo getFunInfo(String name, int pcount) {
|
71 |
-
FunInfo key = new FunInfo(name, pcount);
|
72 |
-
FunInfo val = funMap.get(key);
|
73 |
-
|
74 |
-
if (val != null) {
|
75 |
-
return val;
|
76 |
-
} else {
|
77 |
-
key.setParamCount(-1);
|
78 |
-
return funMap.get(key);
|
79 |
-
}
|
80 |
-
}
|
81 |
-
|
82 |
-
// ���ú�����Ϣ����֤��������+����������Ψһ
|
83 |
-
public static void setFunInfo(FunInfo fi) {
|
84 |
-
funMap.put(fi, fi);
|
85 |
-
}
|
86 |
-
|
87 |
-
// ��xml�ļ������Ӻ�����Ϣ��sameModeָ����ͬһ����ʱ�Ĵ���ʽ
|
88 |
-
private static void addFrom(InputStream in, int sameMode) {
|
89 |
-
if (in == null) {
|
90 |
-
return;
|
91 |
-
}
|
92 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
93 |
-
.newInstance();
|
94 |
-
DocumentBuilder docBuilder;
|
95 |
-
Document xmlDocument;
|
96 |
-
try {
|
97 |
-
|
98 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
99 |
-
// docBuilder = docBuilderFactory.newDocumentBuilder();
|
100 |
-
// FIXED:
|
101 |
-
|
102 |
-
xmlDocument = docBuilder.parse(in);
|
103 |
-
} catch (Exception e) {
|
104 |
-
e.printStackTrace();
|
105 |
-
throw new RQException("Invalid input stream.");
|
106 |
-
}
|
107 |
-
NodeList nl = xmlDocument.getChildNodes();
|
108 |
-
if (nl == null) {
|
109 |
-
return;
|
110 |
-
}
|
111 |
-
Node funInfo = null;
|
112 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
113 |
-
Node n = nl.item(i);
|
114 |
-
if (n.getNodeName().equalsIgnoreCase(ROOT)) {
|
115 |
-
funInfo = n;
|
116 |
-
}
|
117 |
-
}
|
118 |
-
if (funInfo == null) {
|
119 |
-
return;
|
120 |
-
}
|
121 |
-
nl = funInfo.getChildNodes();
|
122 |
-
boolean isFix;
|
123 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
124 |
-
Node root = nl.item(i);
|
125 |
-
if (root.getNodeType() != Node.ELEMENT_NODE) {
|
126 |
-
continue;
|
127 |
-
}
|
128 |
-
if (!root.getNodeName().equalsIgnoreCase(NODE_FUNCTIONS)) {
|
129 |
-
continue;
|
130 |
-
}
|
131 |
-
String value = getAttribute(root, KEY_TYPE);
|
132 |
-
if (value == null) {
|
133 |
-
continue;
|
134 |
-
}
|
135 |
-
isFix = value.equals(TYPE_FIX);
|
136 |
-
NodeList funcNodes = root.getChildNodes();
|
137 |
-
for (int j = 0; j < funcNodes.getLength(); j++) {
|
138 |
-
Node funcNode = funcNodes.item(j);
|
139 |
-
if (funcNode.getNodeType() != Node.ELEMENT_NODE) {
|
140 |
-
continue;
|
141 |
-
}
|
142 |
-
//FunInfo fi;
|
143 |
-
if (isFix) {
|
144 |
-
String name = getAttribute(funcNode, KEY_NAME);
|
145 |
-
String sParamCount = getAttribute(funcNode, KEY_PARAM_COUNT);
|
146 |
-
String defValue = getAttribute(funcNode, KEY_VALUE);
|
147 |
-
int paramCount;
|
148 |
-
try {
|
149 |
-
paramCount = Integer.parseInt(sParamCount);
|
150 |
-
} catch (Exception ex) {
|
151 |
-
throw new RQException("Invalid param count:"
|
152 |
-
+ sParamCount);
|
153 |
-
}
|
154 |
-
|
155 |
-
NodeList infos = funcNode.getChildNodes();
|
156 |
-
for (int u = 0; u < infos.getLength(); u++) {
|
157 |
-
Node info = infos.item(u);
|
158 |
-
if (info.getNodeType() != Node.ELEMENT_NODE) {
|
159 |
-
continue;
|
160 |
-
}
|
161 |
-
String sDbType = getAttribute(info, KEY_DB_TYPE);
|
162 |
-
String sValue = getAttribute(info, KEY_VALUE);
|
163 |
-
if (sValue == null || sValue.trim().length() == 0) sValue = defValue;
|
164 |
-
if (sDbType==null || sDbType.trim().length()==0) sDbType = "ESPROC";
|
165 |
-
addInfo(sDbType, name, paramCount, sValue);
|
166 |
-
}
|
167 |
-
} else {
|
168 |
-
String name = getAttribute(funcNode, KEY_NAME);
|
169 |
-
String defValue = getAttribute(funcNode, KEY_CLASS_NAME);
|
170 |
-
int paramCount = -1;
|
171 |
-
|
172 |
-
NodeList infos = funcNode.getChildNodes();
|
173 |
-
for (int u = 0; u < infos.getLength(); u++) {
|
174 |
-
Node info = infos.item(u);
|
175 |
-
if (info.getNodeType() != Node.ELEMENT_NODE) {
|
176 |
-
continue;
|
177 |
-
}
|
178 |
-
String sDbType = getAttribute(info, KEY_DB_TYPE);
|
179 |
-
String sValue = getAttribute(info, KEY_CLASS_NAME);
|
180 |
-
if (sValue == null || sValue.trim().length() == 0) sValue = defValue;
|
181 |
-
if (sDbType==null || sDbType.trim().length()==0) sDbType = "ESPROC";
|
182 |
-
addInfo(sDbType, name, paramCount, sValue);
|
183 |
-
}
|
184 |
-
}
|
185 |
-
|
186 |
-
}
|
187 |
-
}
|
188 |
-
}
|
189 |
-
|
190 |
-
public static final String ROOT = "STANDARD";
|
191 |
-
|
192 |
-
public static final String NODE_FUNCTIONS = "FUNCTIONS";
|
193 |
-
|
194 |
-
public static final String NODE_FUNCTION = "FUNCTION";
|
195 |
-
|
196 |
-
public static final String KEY_TYPE = "type";
|
197 |
-
|
198 |
-
public static final String TYPE_FIX = "FixParam";
|
199 |
-
|
200 |
-
public static final String TYPE_ANY = "AnyParam";
|
201 |
-
|
202 |
-
public static final String KEY_NAME = "name";
|
203 |
-
|
204 |
-
public static final String KEY_PARAM_COUNT = "paramcount";
|
205 |
-
|
206 |
-
public static final String NODE_INFO = "INFO";
|
207 |
-
|
208 |
-
public static final String KEY_DB_TYPE = "dbtype";
|
209 |
-
|
210 |
-
public static final String KEY_VALUE = "value";
|
211 |
-
|
212 |
-
public static final String KEY_CLASS_NAME = "classname";
|
213 |
-
|
214 |
-
private static String getAttribute(Node node, String attrName) {
|
215 |
-
NamedNodeMap attrs = node.getAttributes();
|
216 |
-
if (attrs == null) {
|
217 |
-
return null;
|
218 |
-
}
|
219 |
-
int i = attrs.getLength();
|
220 |
-
for (int j = 0; j < i; j++) {
|
221 |
-
Node tmp = attrs.item(j);
|
222 |
-
String sTmp = tmp.getNodeName();
|
223 |
-
if (sTmp.equalsIgnoreCase(attrName)) {
|
224 |
-
return tmp.getNodeValue();
|
225 |
-
}
|
226 |
-
}
|
227 |
-
return null;
|
228 |
-
}
|
229 |
-
|
230 |
-
// ���������Ϣ
|
231 |
-
public static void clear() {
|
232 |
-
funMap.clear();
|
233 |
-
}
|
234 |
-
|
235 |
-
public static Collection<FunInfo> getAllFunInfo() {
|
236 |
-
return funMap.values();
|
237 |
-
}
|
238 |
-
|
239 |
-
|
240 |
-
public static String getFunctionExp(String dbtype, String name, String[] params)
|
241 |
-
{
|
242 |
-
String exp = null;
|
243 |
-
//String dbname = DBTypes.getDBTypeName(dbtype);
|
244 |
-
Map<String, Map<Integer, String>> thisdb = dbMap.get(dbtype.toUpperCase());
|
245 |
-
if (thisdb == null) {
|
246 |
-
throw new RQException("unknown database : "+dbtype);
|
247 |
-
}
|
248 |
-
Map<Integer, String> typeFunctionMap = thisdb.get(name.toLowerCase());
|
249 |
-
if(typeFunctionMap != null)
|
250 |
-
{
|
251 |
-
int count = params.length;
|
252 |
-
String formula = typeFunctionMap.get(count);
|
253 |
-
if(formula != null)
|
254 |
-
{
|
255 |
-
if(formula.isEmpty())
|
256 |
-
{
|
257 |
-
StringBuffer sb = new StringBuffer();
|
258 |
-
sb.append(name);
|
259 |
-
sb.append("(");
|
260 |
-
for(int i = 0; i < params.length; i++)
|
261 |
-
{
|
262 |
-
sb.append("?"+(i+1));
|
263 |
-
if(i > 0)
|
264 |
-
{
|
265 |
-
sb.append(",");
|
266 |
-
}
|
267 |
-
}
|
268 |
-
sb.append(")");
|
269 |
-
formula = sb.toString();
|
270 |
-
}
|
271 |
-
else if(formula.equalsIgnoreCase("N/A"))
|
272 |
-
{
|
273 |
-
throw new RQException("�˺���ϵͳ�ݲ�֧��:"+name);
|
274 |
-
}
|
275 |
-
else if(count == 1)
|
276 |
-
{
|
277 |
-
formula = formula.replace("?1", "?");
|
278 |
-
formula = formula.replace("?", "?1");
|
279 |
-
}
|
280 |
-
for(int i = 0; i < params.length; i++)
|
281 |
-
{
|
282 |
-
formula = formula.replace("?"+(i+1), params[i]);
|
283 |
-
}
|
284 |
-
exp = formula;
|
285 |
-
}
|
286 |
-
else
|
287 |
-
{
|
288 |
-
String className = typeFunctionMap.get(-1);
|
289 |
-
if(className != null)
|
290 |
-
{
|
291 |
-
try
|
292 |
-
{
|
293 |
-
IFunction functionClass = (IFunction)Class.forName(className).newInstance();
|
294 |
-
exp = functionClass.getFormula(params);
|
295 |
-
}
|
296 |
-
catch (Exception e)
|
297 |
-
{
|
298 |
-
throw new RQException("���طǹ̶����������ĺ������Զ�����ʱ���ִ���", e);
|
299 |
-
}
|
300 |
-
}
|
301 |
-
}
|
302 |
-
// if(exp == null)
|
303 |
-
// {
|
304 |
-
// throw new RQException("δ֪�ĺ�������, ����:"+name+", ��������:"+params.length);
|
305 |
-
// }
|
306 |
-
}
|
307 |
-
|
308 |
-
return exp;
|
309 |
-
}
|
310 |
-
|
311 |
-
|
312 |
-
public static void main (String args[]) {
|
313 |
-
System.out.println(FunInfoManager.dbMap.size());
|
314 |
-
}
|
315 |
-
|
316 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10001.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.dm.sql;import java.io.InputStream;import java.util.Collection;import java.util.HashMap;import java.util.Map;import java.util.TreeMap;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.scudata.common.Logger;import com.scudata.common.RQException;import com.scudata.dm.sql.simple.IFunction;//������Ϣ������(������Ϣ����ʱ�����Ƽ�������������)//***��δ�������ݿⲻͬ�汾�еĺ�������//***�����������̶���ֻ��Ԥ�ȶ����public class FunInfoManager { public static final int COVER = 0; // ���� public static final int SKIP = 1; // ���� public static final int ERROR = 2; // ���� private static TreeMap<FunInfo, FunInfo> funMap = new TreeMap<FunInfo, FunInfo>(); // [FunInfo-FunInfo] //<dbtype<name<paramcount:value>>> public static Map<String, Map<String, Map<Integer, String>>> dbMap = new HashMap<String,Map<String, Map<Integer, String>>>(); static { // �Զ����غ����ļ� try { InputStream in = FunInfoManager.class.getResourceAsStream("/com/scudata/dm/sql/function.xml"); addFrom(in, COVER); } catch (Exception e) { Logger.debug(e); } } private static void addInfo(String dbtype, String name, int paramcount, String value) { name = name.toLowerCase(); dbtype = dbtype.toUpperCase(); Map<String, Map<Integer, String>> db = dbMap.get(dbtype); if (db == null) { db = new HashMap<String, Map<Integer, String>>(); dbMap.put(dbtype, db); } Map<Integer, String> fn = db.get(name); if (fn == null) { fn = new HashMap<Integer, String>(); db.put(name, fn); } fn.put(paramcount, value); } public static FixedParamFunInfo getFixedParamFunInfo(String name, int pcount) { FunInfo key = new FunInfo(name, pcount); return (FixedParamFunInfo)funMap.get(key); } // ���ݱ���������������������Һ�����Ϣ������������ȷƥ��ʱ��ƥ��-1 public static FunInfo getFunInfo(String name, int pcount) { FunInfo key = new FunInfo(name, pcount); FunInfo val = funMap.get(key); if (val != null) { return val; } else { key.setParamCount(-1); return funMap.get(key); } } // ���ú�����Ϣ����֤��������+����������Ψһ public static void setFunInfo(FunInfo fi) { funMap.put(fi, fi); } // ��xml�ļ������Ӻ�����Ϣ��sameModeָ����ͬһ����ʱ�Ĵ���ʽ private static void addFrom(InputStream in, int sameMode) { if (in == null) { return; } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder; Document xmlDocument; try { // BUG: CWE-611: Improper Restriction of XML External Entity Reference// docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: xmlDocument = docBuilder.parse(in); } catch (Exception e) { e.printStackTrace(); throw new RQException("Invalid input stream."); } NodeList nl = xmlDocument.getChildNodes(); if (nl == null) { return; } Node funInfo = null; for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeName().equalsIgnoreCase(ROOT)) { funInfo = n; } } if (funInfo == null) { return; } nl = funInfo.getChildNodes(); boolean isFix; for (int i = 0; i < nl.getLength(); i++) { Node root = nl.item(i); if (root.getNodeType() != Node.ELEMENT_NODE) { continue; } if (!root.getNodeName().equalsIgnoreCase(NODE_FUNCTIONS)) { continue; } String value = getAttribute(root, KEY_TYPE); if (value == null) { continue; } isFix = value.equals(TYPE_FIX); NodeList funcNodes = root.getChildNodes(); for (int j = 0; j < funcNodes.getLength(); j++) { Node funcNode = funcNodes.item(j); if (funcNode.getNodeType() != Node.ELEMENT_NODE) { continue; } //FunInfo fi; if (isFix) { String name = getAttribute(funcNode, KEY_NAME); String sParamCount = getAttribute(funcNode, KEY_PARAM_COUNT); String defValue = getAttribute(funcNode, KEY_VALUE); int paramCount; try { paramCount = Integer.parseInt(sParamCount); } catch (Exception ex) { throw new RQException("Invalid param count:" + sParamCount); } NodeList infos = funcNode.getChildNodes(); for (int u = 0; u < infos.getLength(); u++) { Node info = infos.item(u); if (info.getNodeType() != Node.ELEMENT_NODE) { continue; } String sDbType = getAttribute(info, KEY_DB_TYPE); String sValue = getAttribute(info, KEY_VALUE); if (sValue == null || sValue.trim().length() == 0) sValue = defValue; if (sDbType==null || sDbType.trim().length()==0) sDbType = "ESPROC"; addInfo(sDbType, name, paramCount, sValue); } } else { String name = getAttribute(funcNode, KEY_NAME); String defValue = getAttribute(funcNode, KEY_CLASS_NAME); int paramCount = -1; NodeList infos = funcNode.getChildNodes(); for (int u = 0; u < infos.getLength(); u++) { Node info = infos.item(u); if (info.getNodeType() != Node.ELEMENT_NODE) { continue; } String sDbType = getAttribute(info, KEY_DB_TYPE); String sValue = getAttribute(info, KEY_CLASS_NAME); if (sValue == null || sValue.trim().length() == 0) sValue = defValue; if (sDbType==null || sDbType.trim().length()==0) sDbType = "ESPROC"; addInfo(sDbType, name, paramCount, sValue); } } } } } public static final String ROOT = "STANDARD"; public static final String NODE_FUNCTIONS = "FUNCTIONS"; public static final String NODE_FUNCTION = "FUNCTION"; public static final String KEY_TYPE = "type"; public static final String TYPE_FIX = "FixParam"; public static final String TYPE_ANY = "AnyParam"; public static final String KEY_NAME = "name"; public static final String KEY_PARAM_COUNT = "paramcount"; public static final String NODE_INFO = "INFO"; public static final String KEY_DB_TYPE = "dbtype"; public static final String KEY_VALUE = "value"; public static final String KEY_CLASS_NAME = "classname"; private static String getAttribute(Node node, String attrName) { NamedNodeMap attrs = node.getAttributes(); if (attrs == null) { return null; } int i = attrs.getLength(); for (int j = 0; j < i; j++) { Node tmp = attrs.item(j); String sTmp = tmp.getNodeName(); if (sTmp.equalsIgnoreCase(attrName)) { return tmp.getNodeValue(); } } return null; } // ���������Ϣ public static void clear() { funMap.clear(); } public static Collection<FunInfo> getAllFunInfo() { return funMap.values(); } public static String getFunctionExp(String dbtype, String name, String[] params) { String exp = null; //String dbname = DBTypes.getDBTypeName(dbtype); Map<String, Map<Integer, String>> thisdb = dbMap.get(dbtype.toUpperCase()); if (thisdb == null) { throw new RQException("unknown database : "+dbtype); } Map<Integer, String> typeFunctionMap = thisdb.get(name.toLowerCase()); if(typeFunctionMap != null) { int count = params.length; String formula = typeFunctionMap.get(count); if(formula != null) { if(formula.isEmpty()) { StringBuffer sb = new StringBuffer(); sb.append(name); sb.append("("); for(int i = 0; i < params.length; i++) { sb.append("?"+(i+1)); if(i > 0) { sb.append(","); } } sb.append(")"); formula = sb.toString(); } else if(formula.equalsIgnoreCase("N/A")) { throw new RQException("�˺���ϵͳ�ݲ�֧��:"+name); } else if(count == 1) { formula = formula.replace("?1", "?"); formula = formula.replace("?", "?1"); } for(int i = 0; i < params.length; i++) { formula = formula.replace("?"+(i+1), params[i]); } exp = formula; } else { String className = typeFunctionMap.get(-1); if(className != null) { try { IFunction functionClass = (IFunction)Class.forName(className).newInstance(); exp = functionClass.getFormula(params); } catch (Exception e) { throw new RQException("���طǹ̶����������ĺ������Զ�����ʱ���ִ���", e); } } }// if(exp == null)// {// throw new RQException("δ֪�ĺ�������, ����:"+name+", ��������:"+params.length);// } } return exp; } public static void main (String args[]) { System.out.println(FunInfoManager.dbMap.size()); }}
|
data/java/10002.java
DELETED
@@ -1,1221 +0,0 @@
|
|
1 |
-
package com.scudata.ide.common;
|
2 |
-
|
3 |
-
import java.awt.event.ActionEvent;
|
4 |
-
import java.awt.event.ActionListener;
|
5 |
-
import java.io.File;
|
6 |
-
import java.util.ArrayList;
|
7 |
-
import java.util.HashMap;
|
8 |
-
import java.util.HashSet;
|
9 |
-
import java.util.Iterator;
|
10 |
-
import java.util.List;
|
11 |
-
import java.util.Set;
|
12 |
-
|
13 |
-
import javax.swing.AbstractAction;
|
14 |
-
import javax.swing.Action;
|
15 |
-
import javax.swing.Icon;
|
16 |
-
import javax.swing.JInternalFrame;
|
17 |
-
import javax.swing.JMenu;
|
18 |
-
import javax.swing.JMenuBar;
|
19 |
-
import javax.swing.JMenuItem;
|
20 |
-
import javax.swing.JOptionPane;
|
21 |
-
import javax.swing.JSeparator;
|
22 |
-
import javax.xml.parsers.DocumentBuilder;
|
23 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
24 |
-
|
25 |
-
import org.w3c.dom.Document;
|
26 |
-
import org.w3c.dom.Element;
|
27 |
-
import org.w3c.dom.NamedNodeMap;
|
28 |
-
import org.w3c.dom.Node;
|
29 |
-
import org.w3c.dom.NodeList;
|
30 |
-
|
31 |
-
import com.scudata.app.common.AppConsts;
|
32 |
-
import com.scudata.common.IntArrayList;
|
33 |
-
import com.scudata.common.Logger;
|
34 |
-
import com.scudata.common.MessageManager;
|
35 |
-
import com.scudata.common.StringUtils;
|
36 |
-
import com.scudata.ide.common.resources.IdeCommonMessage;
|
37 |
-
import com.scudata.ide.spl.GMSpl;
|
38 |
-
import com.scudata.ide.spl.GVSpl;
|
39 |
-
import com.scudata.ide.spl.resources.IdeSplMessage;
|
40 |
-
|
41 |
-
/**
|
42 |
-
* The base class of the IDE menu
|
43 |
-
*
|
44 |
-
*/
|
45 |
-
public abstract class AppMenu extends JMenuBar {
|
46 |
-
private static final long serialVersionUID = 1L;
|
47 |
-
/**
|
48 |
-
* Recent connections
|
49 |
-
*/
|
50 |
-
public JMenuItem[] connItem = new JMenuItem[GC.RECENT_MENU_COUNT];
|
51 |
-
/**
|
52 |
-
* Recent files
|
53 |
-
*/
|
54 |
-
public JMenuItem[] fileItem = new JMenuItem[GC.RECENT_MENU_COUNT];
|
55 |
-
/**
|
56 |
-
* Recent main path
|
57 |
-
*/
|
58 |
-
public JMenuItem[] mainPathItem = new JMenuItem[GC.RECENT_MENU_COUNT];
|
59 |
-
|
60 |
-
/**
|
61 |
-
* Live menu upper limit
|
62 |
-
*/
|
63 |
-
private static final int LIVE_MENU_COUNT = 9;
|
64 |
-
/**
|
65 |
-
* Temporary live menu
|
66 |
-
*/
|
67 |
-
protected JMenu tmpLiveMenu;
|
68 |
-
/**
|
69 |
-
* Collection of active menus
|
70 |
-
*/
|
71 |
-
protected static HashSet<JMenuItem> liveMenuItems = new HashSet<JMenuItem>();
|
72 |
-
/**
|
73 |
-
* The active menu
|
74 |
-
*/
|
75 |
-
protected static JMenu liveMenu;
|
76 |
-
/**
|
77 |
-
* Collection of menus
|
78 |
-
*/
|
79 |
-
protected static HashMap<Short, JMenuItem> menuItems = new HashMap<Short, JMenuItem>();
|
80 |
-
|
81 |
-
/**
|
82 |
-
* Message Resource Manager
|
83 |
-
*/
|
84 |
-
private MessageManager mManager = IdeCommonMessage.get();
|
85 |
-
|
86 |
-
/**
|
87 |
-
* Window menu
|
88 |
-
*/
|
89 |
-
public static JMenu windowMenu;
|
90 |
-
|
91 |
-
/**
|
92 |
-
* Help menu
|
93 |
-
*/
|
94 |
-
public static JMenu helpMenu;
|
95 |
-
|
96 |
-
/**
|
97 |
-
* Temporary live menu items
|
98 |
-
*/
|
99 |
-
protected static HashSet<JMenuItem> tmpLiveMenuItems = new HashSet<JMenuItem>();
|
100 |
-
|
101 |
-
/**
|
102 |
-
* IDE common MessageManager
|
103 |
-
*/
|
104 |
-
private MessageManager mm = IdeCommonMessage.get();
|
105 |
-
|
106 |
-
/**
|
107 |
-
* Reset privilege menu
|
108 |
-
*/
|
109 |
-
public void resetPrivilegeMenu() {
|
110 |
-
}
|
111 |
-
|
112 |
-
/**
|
113 |
-
* Set whether the menu is enable
|
114 |
-
*
|
115 |
-
* @param menuIds
|
116 |
-
* @param enable
|
117 |
-
*/
|
118 |
-
public void setEnable(short[] menuIds, boolean enable) {
|
119 |
-
for (int i = 0; i < menuIds.length; i++) {
|
120 |
-
JMenuItem mi = menuItems.get(menuIds[i]);
|
121 |
-
if (mi == null) {
|
122 |
-
continue;
|
123 |
-
}
|
124 |
-
mi.setEnabled(enable);
|
125 |
-
}
|
126 |
-
}
|
127 |
-
|
128 |
-
/**
|
129 |
-
* Set whether the menu is visible
|
130 |
-
*
|
131 |
-
* @param menuIds
|
132 |
-
* @param visible
|
133 |
-
*/
|
134 |
-
public void setMenuVisible(short[] menuIds, boolean visible) {
|
135 |
-
for (int i = 0; i < menuIds.length; i++) {
|
136 |
-
JMenuItem mi = menuItems.get(menuIds[i]);
|
137 |
-
if (mi == null) {
|
138 |
-
continue;
|
139 |
-
}
|
140 |
-
mi.setVisible(visible);
|
141 |
-
}
|
142 |
-
}
|
143 |
-
|
144 |
-
/**
|
145 |
-
* The prefix of the active menu
|
146 |
-
*/
|
147 |
-
private final String PRE_LIVE_MENU = "live_";
|
148 |
-
|
149 |
-
/**
|
150 |
-
* Adde the active menu
|
151 |
-
*
|
152 |
-
* @param sheetTitle
|
153 |
-
*/
|
154 |
-
public void addLiveMenu(String sheetTitle) {
|
155 |
-
Action action = new AbstractAction() {
|
156 |
-
private static final long serialVersionUID = 1L;
|
157 |
-
|
158 |
-
public void actionPerformed(ActionEvent e) {
|
159 |
-
try {
|
160 |
-
JMenuItem rmi;
|
161 |
-
Object o = e.getSource();
|
162 |
-
if (o == null) {
|
163 |
-
return;
|
164 |
-
}
|
165 |
-
rmi = (JMenuItem) o;
|
166 |
-
rmi.setIcon(getSelectedIcon(true));
|
167 |
-
JMenuItem tt = (JMenuItem) e.getSource();
|
168 |
-
JInternalFrame sheet = GV.appFrame.getSheet(tt.getText());
|
169 |
-
if (!GV.appFrame.showSheet(sheet))
|
170 |
-
return;
|
171 |
-
GV.toolWin.refreshSheet(sheet);
|
172 |
-
} catch (Throwable e2) {
|
173 |
-
GM.showException(e2);
|
174 |
-
}
|
175 |
-
}
|
176 |
-
};
|
177 |
-
if (liveMenu == null) {
|
178 |
-
return;
|
179 |
-
}
|
180 |
-
JMenuItem mi = GM.getMenuByName(this, PRE_LIVE_MENU + sheetTitle);
|
181 |
-
JMenuItem rmi;
|
182 |
-
resetLiveMenuItems();
|
183 |
-
if (mi == null) {
|
184 |
-
if (liveMenu.getItemCount() == LIVE_MENU_COUNT - 1) {
|
185 |
-
liveMenu.addSeparator();
|
186 |
-
}
|
187 |
-
rmi = new JMenuItem(sheetTitle);
|
188 |
-
// ��˵��IJ˵�����Ϊ���ڱ��⣬���Dz˵��������
|
189 |
-
rmi.setName(PRE_LIVE_MENU + sheetTitle);
|
190 |
-
rmi.addActionListener(action);
|
191 |
-
liveMenu.add(rmi);
|
192 |
-
liveMenuItems.add(rmi);
|
193 |
-
rmi.setIcon(getSelectedIcon(true));
|
194 |
-
} else {
|
195 |
-
rmi = (JMenuItem) mi;
|
196 |
-
rmi.setIcon(getSelectedIcon(true));
|
197 |
-
}
|
198 |
-
}
|
199 |
-
|
200 |
-
/**
|
201 |
-
* The icon for the active menu. The current window will be displayed as
|
202 |
-
* selected.
|
203 |
-
*
|
204 |
-
* @param isSelected
|
205 |
-
* @return
|
206 |
-
*/
|
207 |
-
private Icon getSelectedIcon(boolean isSelected) {
|
208 |
-
if (isSelected) {
|
209 |
-
return GM.getMenuImageIcon("selected");
|
210 |
-
} else {
|
211 |
-
return GM.getMenuImageIcon("blank");
|
212 |
-
}
|
213 |
-
}
|
214 |
-
|
215 |
-
/**
|
216 |
-
* Remove the active menu
|
217 |
-
*
|
218 |
-
* @param sheetTitle
|
219 |
-
*/
|
220 |
-
public void removeLiveMenu(String sheetTitle) {
|
221 |
-
JMenuItem mi = (JMenuItem) GM.getMenuByName(this, PRE_LIVE_MENU
|
222 |
-
+ sheetTitle);
|
223 |
-
if (mi != null) {
|
224 |
-
liveMenu.remove(mi);
|
225 |
-
liveMenuItems.remove(mi);
|
226 |
-
}
|
227 |
-
if (liveMenu != null && liveMenu.getItemCount() == LIVE_MENU_COUNT) {
|
228 |
-
liveMenu.remove(LIVE_MENU_COUNT - 1);
|
229 |
-
}
|
230 |
-
}
|
231 |
-
|
232 |
-
/**
|
233 |
-
* Rename the active menu
|
234 |
-
*
|
235 |
-
* @param srcName
|
236 |
-
* @param tarName
|
237 |
-
*/
|
238 |
-
public void renameLiveMenu(String srcName, String tarName) {
|
239 |
-
JMenuItem mi = GM.getMenuByName(this, srcName);
|
240 |
-
if (mi != null) {
|
241 |
-
mi.setName(tarName);
|
242 |
-
mi.setText(tarName);
|
243 |
-
}
|
244 |
-
}
|
245 |
-
|
246 |
-
/**
|
247 |
-
* Reset the active menu
|
248 |
-
*/
|
249 |
-
private void resetLiveMenuItems() {
|
250 |
-
JMenuItem rmi;
|
251 |
-
Iterator<JMenuItem> it = liveMenuItems.iterator();
|
252 |
-
while (it.hasNext()) {
|
253 |
-
rmi = (JMenuItem) it.next();
|
254 |
-
rmi.setIcon(getSelectedIcon(false));
|
255 |
-
}
|
256 |
-
}
|
257 |
-
|
258 |
-
/**
|
259 |
-
* After the data source is connected
|
260 |
-
*/
|
261 |
-
public abstract void dataSourceConnected();
|
262 |
-
|
263 |
-
/**
|
264 |
-
* Get the recent connection menu
|
265 |
-
*
|
266 |
-
* @return
|
267 |
-
*/
|
268 |
-
public JMenu getRecentConn() {
|
269 |
-
Action actionNew = new AbstractAction() {
|
270 |
-
private static final long serialVersionUID = 1L;
|
271 |
-
|
272 |
-
public void actionPerformed(ActionEvent e) {
|
273 |
-
JMenuItem tt = (JMenuItem) e.getSource();
|
274 |
-
GV.appFrame.openConnection(tt.getText());
|
275 |
-
try {
|
276 |
-
ConfigUtilIde.writeConfig();
|
277 |
-
} catch (Exception ex) {
|
278 |
-
Logger.debug(ex);
|
279 |
-
}
|
280 |
-
dataSourceConnected();
|
281 |
-
}
|
282 |
-
};
|
283 |
-
JMenu menu = GM.getMenuItem(
|
284 |
-
mManager.getMessage(GC.MENU + GC.RECENT_CONNS), 'T', false);
|
285 |
-
try {
|
286 |
-
ConfigFile.getConfigFile().loadRecentConnection(connItem);
|
287 |
-
for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) {
|
288 |
-
connItem[i].addActionListener(actionNew);
|
289 |
-
if (connItem[i].isVisible())
|
290 |
-
menu.add(connItem[i]);
|
291 |
-
}
|
292 |
-
} catch (Throwable e) {
|
293 |
-
GM.showException(e);
|
294 |
-
}
|
295 |
-
return menu;
|
296 |
-
}
|
297 |
-
|
298 |
-
/**
|
299 |
-
* Refresh recent connections
|
300 |
-
*
|
301 |
-
* @param dsName
|
302 |
-
* @throws Throwable
|
303 |
-
*/
|
304 |
-
public void refreshRecentConn(String dsName) throws Throwable {
|
305 |
-
if (!StringUtils.isValidString(dsName)) {
|
306 |
-
return;
|
307 |
-
}
|
308 |
-
String tempConnName;
|
309 |
-
int point = GC.RECENT_MENU_COUNT - 1;
|
310 |
-
for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) {
|
311 |
-
if (connItem[i] == null)
|
312 |
-
return;
|
313 |
-
tempConnName = connItem[i].getText();
|
314 |
-
if (dsName.equals(tempConnName)) {
|
315 |
-
point = i;
|
316 |
-
break;
|
317 |
-
}
|
318 |
-
}
|
319 |
-
|
320 |
-
for (int i = point; i > 0; i--) {
|
321 |
-
tempConnName = connItem[i - 1].getText();
|
322 |
-
connItem[i].setText(tempConnName);
|
323 |
-
connItem[i].setVisible(!tempConnName.equals(""));
|
324 |
-
}
|
325 |
-
connItem[0].setText(dsName);
|
326 |
-
connItem[0].setVisible(true);
|
327 |
-
ConfigFile.getConfigFile().storeRecentConnections(connItem);
|
328 |
-
}
|
329 |
-
|
330 |
-
/**
|
331 |
-
* Get window menu
|
332 |
-
*
|
333 |
-
* @return JMenu
|
334 |
-
*/
|
335 |
-
public JMenu getWindowMenu() {
|
336 |
-
return getWindowMenu(true);
|
337 |
-
}
|
338 |
-
|
339 |
-
/**
|
340 |
-
* Get window menu
|
341 |
-
*
|
342 |
-
* @param showViewConsole
|
343 |
-
* @return
|
344 |
-
*/
|
345 |
-
public JMenu getWindowMenu(boolean showViewConsole) {
|
346 |
-
if (windowMenu != null) {
|
347 |
-
return windowMenu;
|
348 |
-
}
|
349 |
-
JMenu menu = getCommonMenuItem(GC.WINDOW, 'W', true);
|
350 |
-
menu.add(newCommonMenuItem(GC.iSHOW_WINLIST, GC.SHOW_WINLIST, 'W',
|
351 |
-
GC.NO_MASK, false));
|
352 |
-
JMenuItem mi = newCommonMenuItem(GC.iVIEW_CONSOLE, GC.VIEW_CONSOLE,
|
353 |
-
'Q', ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK, false);
|
354 |
-
mi.setEnabled(showViewConsole);
|
355 |
-
mi.setVisible(showViewConsole);
|
356 |
-
menu.add(mi);
|
357 |
-
mi = newCommonMenuItem(GC.iVIEW_RIGHT, GC.VIEW_RIGHT, 'R',
|
358 |
-
ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK, false);
|
359 |
-
mi.setEnabled(showViewConsole);
|
360 |
-
mi.setVisible(showViewConsole);
|
361 |
-
menu.add(mi);
|
362 |
-
menu.addSeparator();
|
363 |
-
menu.add(newCommonMenuItem(GC.iCASCADE, GC.CASCADE, 'C', GC.NO_MASK,
|
364 |
-
true));
|
365 |
-
menu.add(newCommonMenuItem(GC.iTILEHORIZONTAL, GC.TILEHORIZONTAL, 'H',
|
366 |
-
GC.NO_MASK));
|
367 |
-
menu.add(newCommonMenuItem(GC.iTILEVERTICAL, GC.TILEVERTICAL, 'V',
|
368 |
-
GC.NO_MASK));
|
369 |
-
menu.add(newCommonMenuItem(GC.iLAYER, GC.LAYER, 'M', GC.NO_MASK));
|
370 |
-
windowMenu = menu;
|
371 |
-
return menu;
|
372 |
-
}
|
373 |
-
|
374 |
-
/**
|
375 |
-
* Get help menu
|
376 |
-
*
|
377 |
-
* @return
|
378 |
-
*/
|
379 |
-
public JMenu getHelpMenu() {
|
380 |
-
if (helpMenu != null) {
|
381 |
-
return helpMenu;
|
382 |
-
}
|
383 |
-
JMenu menu = getCommonMenuItem(GC.HELP, 'H', true);
|
384 |
-
|
385 |
-
List<Object> configMenus = buildMenuFromConfig();
|
386 |
-
for (int i = 0; i < configMenus.size(); i++) {
|
387 |
-
Object o = configMenus.get(i);
|
388 |
-
if (o instanceof JMenu) {
|
389 |
-
menu.add((JMenu) o, i);
|
390 |
-
((JMenu) o).setIcon(GM.getMenuImageIcon("blank"));
|
391 |
-
} else if (o instanceof JMenuItem) {
|
392 |
-
menu.add((JMenuItem) o, i);
|
393 |
-
((JMenuItem) o).setIcon(GM.getMenuImageIcon("blank"));
|
394 |
-
} else if (o instanceof JSeparator) {
|
395 |
-
menu.add((JSeparator) o, i);
|
396 |
-
}
|
397 |
-
}
|
398 |
-
|
399 |
-
menu.add(newCommonMenuItem(GC.iABOUT, GC.ABOUT, 'A', GC.NO_MASK, true));
|
400 |
-
|
401 |
-
menu.add(newCommonMenuItem(GC.iMEMORYTIDY, GC.MEMORYTIDY, 'M',
|
402 |
-
GC.NO_MASK));
|
403 |
-
|
404 |
-
helpMenu = menu;
|
405 |
-
return menu;
|
406 |
-
}
|
407 |
-
|
408 |
-
/**
|
409 |
-
* Get common menu item
|
410 |
-
*
|
411 |
-
* @param menuId Menu ID defined in GC
|
412 |
-
* @param mneKey The Mnemonic
|
413 |
-
* @param isMain Whether it is a menu. Menu item when false
|
414 |
-
* @return
|
415 |
-
*/
|
416 |
-
public JMenu getCommonMenuItem(String menuId, char mneKey, boolean isMain) {
|
417 |
-
return GM.getMenuItem(mm.getMessage(GC.MENU + menuId), mneKey, isMain);
|
418 |
-
}
|
419 |
-
|
420 |
-
/**
|
421 |
-
* Reset live menu
|
422 |
-
*/
|
423 |
-
public void resetLiveMenu() {
|
424 |
-
liveMenuItems = tmpLiveMenuItems;
|
425 |
-
liveMenu = tmpLiveMenu;
|
426 |
-
}
|
427 |
-
|
428 |
-
/**
|
429 |
-
* Refresh the recent files
|
430 |
-
*
|
431 |
-
* @param fileName The new file name is placed first
|
432 |
-
* @throws Throwable
|
433 |
-
*/
|
434 |
-
public void refreshRecentFile(String fileName) throws Throwable {
|
435 |
-
if (!StringUtils.isValidString(fileName)) {
|
436 |
-
return;
|
437 |
-
}
|
438 |
-
GM.setCurrentPath(fileName);
|
439 |
-
|
440 |
-
String tempFileName;
|
441 |
-
int point = GC.RECENT_MENU_COUNT - 1;
|
442 |
-
for (int i = 0; i < fileItem.length; i++) {
|
443 |
-
tempFileName = fileItem[i].getText();
|
444 |
-
if (fileName.equals(tempFileName)) {
|
445 |
-
point = i;
|
446 |
-
break;
|
447 |
-
}
|
448 |
-
}
|
449 |
-
|
450 |
-
for (int i = point; i > 0; i--) {
|
451 |
-
tempFileName = fileItem[i - 1].getText();
|
452 |
-
fileItem[i].setText(tempFileName);
|
453 |
-
fileItem[i].setVisible(!tempFileName.equals(""));
|
454 |
-
}
|
455 |
-
fileItem[0].setText(fileName);
|
456 |
-
fileItem[0].setVisible(true);
|
457 |
-
ConfigFile.getConfigFile()
|
458 |
-
.storeRecentFiles(ConfigFile.APP_DM, fileItem);
|
459 |
-
}
|
460 |
-
|
461 |
-
/**
|
462 |
-
* Refresh recent files when closing the sheet
|
463 |
-
*
|
464 |
-
* @param fileName
|
465 |
-
* @param frames
|
466 |
-
* @throws Throwable
|
467 |
-
*/
|
468 |
-
public void refreshRecentFileOnClose(String fileName,
|
469 |
-
JInternalFrame[] frames) throws Throwable {
|
470 |
-
if (!StringUtils.isValidString(fileName)) {
|
471 |
-
return;
|
472 |
-
}
|
473 |
-
if (frames == null || frames.length == 0)
|
474 |
-
return;
|
475 |
-
String tempFileName;
|
476 |
-
int point = -1;
|
477 |
-
for (int i = 0; i < fileItem.length; i++) {
|
478 |
-
if (fileName.equals(fileItem[i].getText())) {
|
479 |
-
point = i;
|
480 |
-
break;
|
481 |
-
}
|
482 |
-
}
|
483 |
-
if (point == -1) {
|
484 |
-
return;
|
485 |
-
}
|
486 |
-
if (frames.length > GC.RECENT_MENU_COUNT) {
|
487 |
-
// There are more open sheets than the most recent file limit
|
488 |
-
for (int i = point; i < GC.RECENT_MENU_COUNT - 1; i++) {
|
489 |
-
tempFileName = fileItem[i + 1].getText();
|
490 |
-
fileItem[i].setText(tempFileName);
|
491 |
-
fileItem[i].setVisible(!tempFileName.equals(""));
|
492 |
-
}
|
493 |
-
Set<String> lastNames = new HashSet<String>();
|
494 |
-
for (int i = 0; i < GC.RECENT_MENU_COUNT - 1; i++) {
|
495 |
-
if (StringUtils.isValidString(fileItem[i].getText())) {
|
496 |
-
lastNames.add(fileItem[i].getText());
|
497 |
-
}
|
498 |
-
}
|
499 |
-
long maxTime = 0L;
|
500 |
-
String lastSheetName = null;
|
501 |
-
for (JInternalFrame frame : frames) {
|
502 |
-
IPrjxSheet sheet = (IPrjxSheet) frame;
|
503 |
-
String sheetName = sheet.getFileName();
|
504 |
-
if (lastNames.contains(sheetName))
|
505 |
-
continue;
|
506 |
-
if (lastSheetName == null || sheet.getCreateTime() > maxTime) {
|
507 |
-
maxTime = sheet.getCreateTime();
|
508 |
-
lastSheetName = sheetName;
|
509 |
-
}
|
510 |
-
}
|
511 |
-
// Select the last one opened among the remaining open sheets
|
512 |
-
fileItem[GC.RECENT_MENU_COUNT - 1].setText(lastSheetName);
|
513 |
-
fileItem[GC.RECENT_MENU_COUNT - 1].setVisible(true);
|
514 |
-
} else {
|
515 |
-
// Move file back
|
516 |
-
for (int i = point; i < frames.length + 1; i++) {
|
517 |
-
tempFileName = fileItem[i + 1].getText();
|
518 |
-
fileItem[i].setText(tempFileName);
|
519 |
-
fileItem[i].setVisible(!tempFileName.equals(""));
|
520 |
-
}
|
521 |
-
fileItem[frames.length].setText(fileName);
|
522 |
-
fileItem[frames.length].setVisible(true);
|
523 |
-
}
|
524 |
-
ConfigFile.getConfigFile()
|
525 |
-
.storeRecentFiles(ConfigFile.APP_DM, fileItem);
|
526 |
-
}
|
527 |
-
|
528 |
-
/**
|
529 |
-
* Get recent file menu
|
530 |
-
*
|
531 |
-
* @return
|
532 |
-
*/
|
533 |
-
public JMenu getRecentFile() {
|
534 |
-
final JMenu menu = getCommonMenuItem(GC.RECENT_FILES, 'F', false);
|
535 |
-
final Action actionNew = new AbstractAction() {
|
536 |
-
private static final long serialVersionUID = 1L;
|
537 |
-
|
538 |
-
public void actionPerformed(ActionEvent e) {
|
539 |
-
JMenuItem tt = (JMenuItem) e.getSource();
|
540 |
-
try {
|
541 |
-
GV.appFrame.openSheetFile(tt.getText());
|
542 |
-
} catch (Throwable t) {
|
543 |
-
GM.showException(t);
|
544 |
-
if (StringUtils.isValidString(tt.getText())) {
|
545 |
-
File f = new File(tt.getText());
|
546 |
-
if (!f.exists()) {
|
547 |
-
if (fileItem != null) {
|
548 |
-
int len = fileItem.length;
|
549 |
-
int index = -1;
|
550 |
-
for (int i = 0; i < len; i++) {
|
551 |
-
if (tt.getText().equalsIgnoreCase(
|
552 |
-
fileItem[i].getText())) {
|
553 |
-
index = i;
|
554 |
-
break;
|
555 |
-
}
|
556 |
-
}
|
557 |
-
if (index == -1)
|
558 |
-
return;
|
559 |
-
JMenuItem[] newFileItem = new JMenuItem[GC.RECENT_MENU_COUNT];
|
560 |
-
if (index > 0) {
|
561 |
-
System.arraycopy(fileItem, 0, newFileItem,
|
562 |
-
0, index);
|
563 |
-
}
|
564 |
-
if (index < len - 1) {
|
565 |
-
System.arraycopy(fileItem, index + 1,
|
566 |
-
newFileItem, index, len - index - 1);
|
567 |
-
}
|
568 |
-
newFileItem[len - 1] = new JMenuItem("");
|
569 |
-
newFileItem[len - 1].setVisible(false);
|
570 |
-
newFileItem[len - 1].addActionListener(this);
|
571 |
-
fileItem = newFileItem;
|
572 |
-
try {
|
573 |
-
ConfigFile
|
574 |
-
.getConfigFile()
|
575 |
-
.storeRecentFiles(
|
576 |
-
ConfigFile.APP_DM, fileItem);
|
577 |
-
} catch (Throwable e1) {
|
578 |
-
e1.printStackTrace();
|
579 |
-
}
|
580 |
-
try {
|
581 |
-
loadRecentFiles(menu, this);
|
582 |
-
} catch (Throwable e1) {
|
583 |
-
e1.printStackTrace();
|
584 |
-
}
|
585 |
-
}
|
586 |
-
}
|
587 |
-
}
|
588 |
-
}
|
589 |
-
}
|
590 |
-
};
|
591 |
-
try {
|
592 |
-
loadRecentFiles(menu, actionNew);
|
593 |
-
} catch (Throwable e) {
|
594 |
-
GM.showException(e);
|
595 |
-
}
|
596 |
-
return menu;
|
597 |
-
}
|
598 |
-
|
599 |
-
/**
|
600 |
-
* Load the most recent file and set it to the menu
|
601 |
-
*
|
602 |
-
* @param menu
|
603 |
-
* @param actionNew
|
604 |
-
* @throws Throwable
|
605 |
-
*/
|
606 |
-
private void loadRecentFiles(JMenu menu, Action actionNew) throws Throwable {
|
607 |
-
menu.removeAll();
|
608 |
-
ConfigFile.getConfigFile().loadRecentFiles(ConfigFile.APP_DM, fileItem);
|
609 |
-
for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) {
|
610 |
-
fileItem[i].addActionListener(actionNew);
|
611 |
-
if (fileItem[i].isVisible())
|
612 |
-
menu.add(fileItem[i]);
|
613 |
-
}
|
614 |
-
}
|
615 |
-
|
616 |
-
/**
|
617 |
-
* "Other" on the recent main path menu
|
618 |
-
*/
|
619 |
-
private static final String MAINPATH_OTHER = IdeCommonMessage.get()
|
620 |
-
.getMessage("prjxappmenu.other");
|
621 |
-
|
622 |
-
/**
|
623 |
-
* Refresh the recent main paths
|
624 |
-
*
|
625 |
-
* @param fileName
|
626 |
-
* @throws Throwable
|
627 |
-
*/
|
628 |
-
public void refreshRecentMainPath(String fileName) throws Throwable {
|
629 |
-
if (!StringUtils.isValidString(fileName)) {
|
630 |
-
return;
|
631 |
-
}
|
632 |
-
String tempFileName;
|
633 |
-
int point = GC.RECENT_MENU_COUNT - 1;
|
634 |
-
for (int i = 0; i < mainPathItem.length; i++) {
|
635 |
-
tempFileName = mainPathItem[i].getText();
|
636 |
-
if (fileName.equals(tempFileName)) {
|
637 |
-
point = i;
|
638 |
-
break;
|
639 |
-
}
|
640 |
-
}
|
641 |
-
|
642 |
-
for (int i = point; i > 0; i--) {
|
643 |
-
tempFileName = mainPathItem[i - 1].getText();
|
644 |
-
mainPathItem[i].setText(tempFileName);
|
645 |
-
mainPathItem[i].setVisible(!tempFileName.equals(""));
|
646 |
-
}
|
647 |
-
mainPathItem[0].setText(fileName);
|
648 |
-
mainPathItem[0].setVisible(false);
|
649 |
-
ConfigFile.getConfigFile().storeRecentMainPaths(ConfigFile.APP_DM,
|
650 |
-
mainPathItem);
|
651 |
-
}
|
652 |
-
|
653 |
-
/**
|
654 |
-
* Get recent main paths menu
|
655 |
-
*
|
656 |
-
* @return
|
657 |
-
*/
|
658 |
-
public JMenu getRecentMainPaths() {
|
659 |
-
final JMenu menu = getCommonMenuItem(GC.RECENT_MAINPATH, 'M', false);
|
660 |
-
final Action actionNew = new AbstractAction() {
|
661 |
-
private static final long serialVersionUID = 1L;
|
662 |
-
|
663 |
-
public void actionPerformed(ActionEvent e) {
|
664 |
-
JMenuItem tt = (JMenuItem) e.getSource();
|
665 |
-
try {
|
666 |
-
if (MAINPATH_OTHER.equals(tt.getText())) {
|
667 |
-
// Other
|
668 |
-
String sdir = GM
|
669 |
-
.dialogSelectDirectory(GV.lastDirectory);
|
670 |
-
if (sdir == null)
|
671 |
-
return;
|
672 |
-
ConfigOptions.sMainPath = sdir;
|
673 |
-
GV.config.setMainPath(sdir);
|
674 |
-
ConfigOptions.applyOptions();
|
675 |
-
ConfigUtilIde.writeConfig();
|
676 |
-
refreshRecentMainPath(sdir);
|
677 |
-
if (GVSpl.fileTree != null)
|
678 |
-
GVSpl.fileTree.changeMainPath(sdir);
|
679 |
-
JOptionPane.showMessageDialog(
|
680 |
-
GV.appFrame,
|
681 |
-
IdeCommonMessage.get().getMessage(
|
682 |
-
"prjxappmenu.setmainpath", sdir));
|
683 |
-
} else {
|
684 |
-
File f = new File(tt.getText());
|
685 |
-
if (!f.exists() || !f.isDirectory()) {
|
686 |
-
JOptionPane.showMessageDialog(
|
687 |
-
GV.appFrame,
|
688 |
-
IdeCommonMessage.get().getMessage(
|
689 |
-
"prjxappmenu.nomainpath",
|
690 |
-
tt.getText()));
|
691 |
-
} else {
|
692 |
-
String sdir = tt.getText();
|
693 |
-
ConfigOptions.sMainPath = sdir;
|
694 |
-
GV.config.setMainPath(sdir);
|
695 |
-
ConfigOptions.applyOptions();
|
696 |
-
if (GVSpl.fileTree != null)
|
697 |
-
GVSpl.fileTree.changeMainPath(sdir);
|
698 |
-
ConfigUtilIde.writeConfig();
|
699 |
-
refreshRecentMainPath(sdir);
|
700 |
-
JOptionPane.showMessageDialog(
|
701 |
-
GV.appFrame,
|
702 |
-
IdeCommonMessage.get().getMessage(
|
703 |
-
"prjxappmenu.setmainpath", sdir));
|
704 |
-
return;
|
705 |
-
}
|
706 |
-
}
|
707 |
-
} catch (Throwable t) {
|
708 |
-
GM.showException(t);
|
709 |
-
}
|
710 |
-
|
711 |
-
if (StringUtils.isValidString(tt.getText())) {
|
712 |
-
File f = new File(tt.getText());
|
713 |
-
if (!f.exists()) {
|
714 |
-
if (mainPathItem != null) {
|
715 |
-
int len = mainPathItem.length;
|
716 |
-
int index = -1;
|
717 |
-
for (int i = 0; i < len; i++) {
|
718 |
-
if (tt.getText().equalsIgnoreCase(
|
719 |
-
mainPathItem[i].getText())) {
|
720 |
-
index = i;
|
721 |
-
break;
|
722 |
-
}
|
723 |
-
}
|
724 |
-
if (index == -1)
|
725 |
-
return;
|
726 |
-
JMenuItem[] newFileItem = new JMenuItem[GC.RECENT_MENU_COUNT];
|
727 |
-
if (index > 0) {
|
728 |
-
System.arraycopy(mainPathItem, 0, newFileItem,
|
729 |
-
0, index);
|
730 |
-
}
|
731 |
-
if (index < len - 1) {
|
732 |
-
System.arraycopy(mainPathItem, index + 1,
|
733 |
-
newFileItem, index, len - index - 1);
|
734 |
-
}
|
735 |
-
newFileItem[len - 1] = new JMenuItem("");
|
736 |
-
newFileItem[len - 1].setVisible(false);
|
737 |
-
newFileItem[len - 1].addActionListener(this);
|
738 |
-
mainPathItem = newFileItem;
|
739 |
-
try {
|
740 |
-
ConfigFile
|
741 |
-
.getConfigFile()
|
742 |
-
.storeRecentMainPaths(
|
743 |
-
ConfigFile.APP_DM, mainPathItem);
|
744 |
-
} catch (Throwable e1) {
|
745 |
-
e1.printStackTrace();
|
746 |
-
}
|
747 |
-
try {
|
748 |
-
loadRecentMainPaths(menu, this);
|
749 |
-
} catch (Throwable e1) {
|
750 |
-
e1.printStackTrace();
|
751 |
-
}
|
752 |
-
}
|
753 |
-
}
|
754 |
-
}
|
755 |
-
}
|
756 |
-
};
|
757 |
-
try {
|
758 |
-
loadRecentMainPaths(menu, actionNew);
|
759 |
-
} catch (Throwable e) {
|
760 |
-
GM.showException(e);
|
761 |
-
}
|
762 |
-
return menu;
|
763 |
-
}
|
764 |
-
|
765 |
-
/**
|
766 |
-
* Load the recent main paths and set it to the menu
|
767 |
-
*
|
768 |
-
* @param menu
|
769 |
-
* @param actionNew
|
770 |
-
* @throws Throwable
|
771 |
-
*/
|
772 |
-
private void loadRecentMainPaths(JMenu menu, Action actionNew)
|
773 |
-
throws Throwable {
|
774 |
-
menu.removeAll();
|
775 |
-
boolean hasVisible = ConfigFile.getConfigFile().loadRecentMainPaths(
|
776 |
-
ConfigFile.APP_DM, mainPathItem);
|
777 |
-
for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) {
|
778 |
-
mainPathItem[i].addActionListener(actionNew);
|
779 |
-
menu.add(mainPathItem[i]);
|
780 |
-
}
|
781 |
-
if (hasVisible) {
|
782 |
-
menu.addSeparator();
|
783 |
-
}
|
784 |
-
JMenuItem other = new JMenuItem(MAINPATH_OTHER);
|
785 |
-
other.addActionListener(actionNew);
|
786 |
-
menu.add(other);
|
787 |
-
}
|
788 |
-
|
789 |
-
/**
|
790 |
-
* Enable save menu
|
791 |
-
*
|
792 |
-
* @param enable
|
793 |
-
*/
|
794 |
-
public void enableSave(boolean enable) {
|
795 |
-
JMenuItem mi = menuItems.get(GC.iSAVE);
|
796 |
-
mi.setEnabled(enable);
|
797 |
-
}
|
798 |
-
|
799 |
-
/**
|
800 |
-
* �˵�ִ�еļ�����
|
801 |
-
*/
|
802 |
-
protected ActionListener menuAction = new ActionListener() {
|
803 |
-
public void actionPerformed(ActionEvent e) {
|
804 |
-
String menuId = "";
|
805 |
-
try {
|
806 |
-
JMenuItem mi = (JMenuItem) e.getSource();
|
807 |
-
menuId = mi.getName();
|
808 |
-
short cmdId = Short.parseShort(menuId);
|
809 |
-
executeCmd(cmdId);
|
810 |
-
} catch (Exception ex) {
|
811 |
-
GM.showException(ex);
|
812 |
-
}
|
813 |
-
}
|
814 |
-
};
|
815 |
-
|
816 |
-
/**
|
817 |
-
* ִ�в˵�����
|
818 |
-
*/
|
819 |
-
public void executeCmd(short cmdId) {
|
820 |
-
try {
|
821 |
-
GMSpl.executeCmd(cmdId);
|
822 |
-
} catch (Exception e) {
|
823 |
-
GM.showException(e);
|
824 |
-
}
|
825 |
-
}
|
826 |
-
|
827 |
-
/**
|
828 |
-
* ��������Դ������
|
829 |
-
*/
|
830 |
-
protected MessageManager mmSpl = IdeSplMessage.get();
|
831 |
-
|
832 |
-
/**
|
833 |
-
*
|
834 |
-
* �½��������˵���
|
835 |
-
*
|
836 |
-
* @param cmdId ��GCSpl��������
|
837 |
-
* @param menuId ��GCSpl�ж���IJ˵���
|
838 |
-
* @param isMain �Ƿ�˵���true�˵���false�˵���
|
839 |
-
* @return
|
840 |
-
*/
|
841 |
-
protected JMenu getSplMenuItem(String menuId, char mneKey, boolean isMain) {
|
842 |
-
return GM.getMenuItem(mmSpl.getMessage(GC.MENU + menuId), mneKey,
|
843 |
-
isMain);
|
844 |
-
}
|
845 |
-
|
846 |
-
/**
|
847 |
-
* �½��������˵���
|
848 |
-
*
|
849 |
-
* @param cmdId ��GCSpl��������
|
850 |
-
* @param menuId ��GCSpl�ж���IJ˵���
|
851 |
-
* @param mneKey The Mnemonic
|
852 |
-
* @param mask int, Because ActionEvent.META_MASK is almost not used. This key
|
853 |
-
* seems to be only available on Macintosh keyboards. It is used
|
854 |
-
* here instead of no accelerator key.
|
855 |
-
* @return
|
856 |
-
*/
|
857 |
-
protected JMenuItem newSplMenuItem(short cmdId, String menuId, char mneKey,
|
858 |
-
int mask) {
|
859 |
-
return newSplMenuItem(cmdId, menuId, mneKey, mask, false);
|
860 |
-
}
|
861 |
-
|
862 |
-
/**
|
863 |
-
* �½��������˵���
|
864 |
-
*
|
865 |
-
* @param cmdId ��GCSpl��������
|
866 |
-
* @param menuId ��GCSpl�ж���IJ˵���
|
867 |
-
* @param mneKey The Mnemonic
|
868 |
-
* @param mask int, Because ActionEvent.META_MASK is almost not used. This
|
869 |
-
* key seems to be only available on Macintosh keyboards. It is
|
870 |
-
* used here instead of no accelerator key.
|
871 |
-
* @param hasIcon �˵����Ƿ���ͼ��
|
872 |
-
* @return
|
873 |
-
*/
|
874 |
-
protected JMenuItem newSplMenuItem(short cmdId, String menuId, char mneKey,
|
875 |
-
int mask, boolean hasIcon) {
|
876 |
-
String menuText = menuId;
|
877 |
-
if (menuText.indexOf('.') > 0) {
|
878 |
-
menuText = mmSpl.getMessage(GC.MENU + menuId);
|
879 |
-
}
|
880 |
-
return newMenuItem(cmdId, menuId, mneKey, mask, hasIcon, menuText);
|
881 |
-
}
|
882 |
-
|
883 |
-
/**
|
884 |
-
* �½��������˵���
|
885 |
-
*
|
886 |
-
* @param cmdId ��GCSpl��������
|
887 |
-
* @param menuId ��GCSpl�ж���IJ˵���
|
888 |
-
* @param mneKey The Mnemonic
|
889 |
-
* @param mask int, Because ActionEvent.META_MASK is almost not used. This
|
890 |
-
* key seems to be only available on Macintosh keyboards. It is
|
891 |
-
* used here instead of no accelerator key.
|
892 |
-
* @param hasIcon �˵����Ƿ���ͼ��
|
893 |
-
* @param menuText �˵����ı�
|
894 |
-
* @return
|
895 |
-
*/
|
896 |
-
protected JMenuItem newMenuItem(short cmdId, String menuId, char mneKey,
|
897 |
-
int mask, boolean hasIcon, String menuText) {
|
898 |
-
JMenuItem mItem = GM.getMenuItem(cmdId, menuId, mneKey, mask, hasIcon,
|
899 |
-
menuText);
|
900 |
-
mItem.addActionListener(menuAction);
|
901 |
-
menuItems.put(cmdId, mItem);
|
902 |
-
return mItem;
|
903 |
-
}
|
904 |
-
|
905 |
-
/**
|
906 |
-
* Clone menu item
|
907 |
-
*
|
908 |
-
* @param cmdId Command ID
|
909 |
-
* @return
|
910 |
-
*/
|
911 |
-
public JMenuItem cloneMenuItem(short cmdId) {
|
912 |
-
return cloneMenuItem(cmdId, null);
|
913 |
-
}
|
914 |
-
|
915 |
-
/**
|
916 |
-
* Clone menu item
|
917 |
-
*
|
918 |
-
* @param cmdId Command ID
|
919 |
-
* @param listener ActionListener
|
920 |
-
* @return
|
921 |
-
*/
|
922 |
-
public JMenuItem cloneMenuItem(short cmdId, ActionListener listener) {
|
923 |
-
JMenuItem mItem = new JMenuItem();
|
924 |
-
JMenuItem jmi = menuItems.get(cmdId);
|
925 |
-
String text = jmi.getText();
|
926 |
-
int pos = text.indexOf("("); // Remove shortcut key definition
|
927 |
-
if (pos > 0) {
|
928 |
-
text = text.substring(0, pos);
|
929 |
-
}
|
930 |
-
mItem.setText(text);
|
931 |
-
mItem.setName(jmi.getName());
|
932 |
-
mItem.setIcon(jmi.getIcon());
|
933 |
-
mItem.setVisible(jmi.isVisible());
|
934 |
-
mItem.setEnabled(jmi.isEnabled());
|
935 |
-
mItem.setAccelerator(jmi.getAccelerator());
|
936 |
-
if (listener == null) {
|
937 |
-
mItem.addActionListener(jmi.getActionListeners()[0]);
|
938 |
-
} else {
|
939 |
-
mItem.addActionListener(listener);
|
940 |
-
}
|
941 |
-
return mItem;
|
942 |
-
}
|
943 |
-
|
944 |
-
/**
|
945 |
-
* New menu item
|
946 |
-
*
|
947 |
-
* @param cmdId Command ID
|
948 |
-
* @param menuId Menu name
|
949 |
-
* @param mneKey char, The Mnemonic
|
950 |
-
* @param mask int, Because ActionEvent.META_MASK is almost not used. This key
|
951 |
-
* seems to be only available on Macintosh keyboards. It is used
|
952 |
-
* here instead of no accelerator key.
|
953 |
-
* @return
|
954 |
-
*/
|
955 |
-
protected JMenuItem newCommonMenuItem(short cmdId, String menuId,
|
956 |
-
char mneKey, int mask) {
|
957 |
-
return newCommonMenuItem(cmdId, menuId, mneKey, mask, false);
|
958 |
-
}
|
959 |
-
|
960 |
-
/**
|
961 |
-
* New menu item
|
962 |
-
*
|
963 |
-
* @param cmdId Command ID
|
964 |
-
* @param menuId Menu name
|
965 |
-
* @param mneKey char, The Mnemonic
|
966 |
-
* @param mask int, Because ActionEvent.META_MASK is almost not used. This
|
967 |
-
* key seems to be only available on Macintosh keyboards. It is
|
968 |
-
* used here instead of no accelerator key.
|
969 |
-
* @param hasIcon Whether the menu item has an icon
|
970 |
-
* @return
|
971 |
-
*/
|
972 |
-
protected JMenuItem newCommonMenuItem(short cmdId, String menuId,
|
973 |
-
char mneKey, int mask, boolean hasIcon) {
|
974 |
-
JMenuItem mItem = GM.getMenuItem(cmdId, menuId, mneKey, mask, hasIcon,
|
975 |
-
mm.getMessage(GC.MENU + menuId));
|
976 |
-
mItem.addActionListener(menuAction);
|
977 |
-
menuItems.put(cmdId, mItem);
|
978 |
-
return mItem;
|
979 |
-
}
|
980 |
-
|
981 |
-
/**
|
982 |
-
* Set whether the menu is enabled
|
983 |
-
*
|
984 |
-
* @param cmdId Command ID
|
985 |
-
* @param enabled Whether the menu is enabled
|
986 |
-
*/
|
987 |
-
public void setMenuEnabled(short cmdId, boolean enabled) {
|
988 |
-
JMenuItem mi = menuItems.get(cmdId);
|
989 |
-
if (mi != null) {
|
990 |
-
mi.setEnabled(enabled);
|
991 |
-
}
|
992 |
-
}
|
993 |
-
|
994 |
-
/**
|
995 |
-
* Whether the menu is enabled
|
996 |
-
*
|
997 |
-
* @param cmdId Command ID
|
998 |
-
* @return
|
999 |
-
*/
|
1000 |
-
public boolean isMenuEnabled(short cmdId) {
|
1001 |
-
JMenuItem mi = menuItems.get(cmdId);
|
1002 |
-
if (mi != null) {
|
1003 |
-
return mi.isEnabled();
|
1004 |
-
}
|
1005 |
-
return false;
|
1006 |
-
}
|
1007 |
-
|
1008 |
-
/**
|
1009 |
-
* Set whether the menus are enabled
|
1010 |
-
*
|
1011 |
-
* @param cmdIds Command IDs
|
1012 |
-
* @param enabled Whether the menus are enabled
|
1013 |
-
*/
|
1014 |
-
public void setMenuEnabled(IntArrayList cmdIds, boolean enabled) {
|
1015 |
-
if (cmdIds == null) {
|
1016 |
-
return;
|
1017 |
-
}
|
1018 |
-
for (int i = 0; i < cmdIds.size(); i++) {
|
1019 |
-
short cmdId = (short) cmdIds.getInt(i);
|
1020 |
-
setMenuEnabled(cmdId, enabled);
|
1021 |
-
}
|
1022 |
-
}
|
1023 |
-
|
1024 |
-
/**
|
1025 |
-
* Set whether the menus are enabled
|
1026 |
-
*
|
1027 |
-
* @param cmdIds Command IDs
|
1028 |
-
* @param enabled Whether the menus are enabled
|
1029 |
-
*/
|
1030 |
-
public void setMenuEnabled(short[] cmdIds, boolean enabled) {
|
1031 |
-
if (cmdIds == null) {
|
1032 |
-
return;
|
1033 |
-
}
|
1034 |
-
for (int i = 0; i < cmdIds.length; i++) {
|
1035 |
-
short cmdId = cmdIds[i];
|
1036 |
-
setMenuEnabled(cmdId, enabled);
|
1037 |
-
}
|
1038 |
-
}
|
1039 |
-
|
1040 |
-
/**
|
1041 |
-
* Set whether the menu is visible
|
1042 |
-
*
|
1043 |
-
* @param cmdId Command ID
|
1044 |
-
* @param visible Whether the menu is visible
|
1045 |
-
*/
|
1046 |
-
public void setMenuVisible(short cmdId, boolean visible) {
|
1047 |
-
JMenuItem mi = menuItems.get(cmdId);
|
1048 |
-
if (mi != null) {
|
1049 |
-
mi.setVisible(visible);
|
1050 |
-
}
|
1051 |
-
}
|
1052 |
-
|
1053 |
-
/**
|
1054 |
-
* Set whether the menus are visible
|
1055 |
-
*
|
1056 |
-
* @param cmdIds Command IDs
|
1057 |
-
* @param visible Whether the menus are visible
|
1058 |
-
*/
|
1059 |
-
public void setMenuVisible(IntArrayList cmdIds, boolean visible) {
|
1060 |
-
if (cmdIds == null) {
|
1061 |
-
return;
|
1062 |
-
}
|
1063 |
-
for (int i = 0; i < cmdIds.size(); i++) {
|
1064 |
-
short cmdId = (short) cmdIds.getInt(i);
|
1065 |
-
setMenuVisible(cmdId, visible);
|
1066 |
-
}
|
1067 |
-
}
|
1068 |
-
|
1069 |
-
/**
|
1070 |
-
* Get all menu items
|
1071 |
-
*
|
1072 |
-
* @return
|
1073 |
-
*/
|
1074 |
-
public abstract short[] getMenuItems();
|
1075 |
-
|
1076 |
-
/**
|
1077 |
-
* �����Զ���˵���Ŀǰֻ�а����˵�
|
1078 |
-
* @return �˵����б�
|
1079 |
-
*/
|
1080 |
-
protected List<Object> buildMenuFromConfig() {
|
1081 |
-
return buildMenuFromConfig("menuconfig");
|
1082 |
-
}
|
1083 |
-
|
1084 |
-
/**
|
1085 |
-
* �����Զ���˵���Ŀǰֻ�а����˵�
|
1086 |
-
* @param fileName ���
|
1087 |
-
* @return �˵����б�
|
1088 |
-
*/
|
1089 |
-
protected List<Object> buildMenuFromConfig(String fileName) {
|
1090 |
-
List<Object> helpMenus = new ArrayList<Object>();
|
1091 |
-
try {
|
1092 |
-
Document doc = null;
|
1093 |
-
File configFile = new File(GM.getAbsolutePath(GC.PATH_CONFIG),
|
1094 |
-
fileName + GM.getLanguageSuffix() + "."
|
1095 |
-
+ AppConsts.FILE_XML);
|
1096 |
-
doc = buildDocument(configFile.getAbsolutePath());
|
1097 |
-
Element root = doc.getDocumentElement();
|
1098 |
-
NodeList list = root.getChildNodes();
|
1099 |
-
for (int i = 0; i < list.getLength(); i++) {
|
1100 |
-
Node el = (Node) list.item(i);
|
1101 |
-
if (el.getNodeName().equalsIgnoreCase("help")) {
|
1102 |
-
// ���ɰ����˵�
|
1103 |
-
NodeList helpList = el.getChildNodes();
|
1104 |
-
for (int j = 0; j < helpList.getLength(); j++) {
|
1105 |
-
el = (Node) helpList.item(j);
|
1106 |
-
if (el.getNodeName().equalsIgnoreCase("menu")) {
|
1107 |
-
helpMenus.add(buildMenu(el));
|
1108 |
-
} else if (el.getNodeName()
|
1109 |
-
.equalsIgnoreCase("menuitem")) {
|
1110 |
-
helpMenus.add(getNewItem(el));
|
1111 |
-
} else if (el.getNodeName().equalsIgnoreCase(
|
1112 |
-
"separator")) {
|
1113 |
-
helpMenus.add(new JSeparator());
|
1114 |
-
}
|
1115 |
-
}
|
1116 |
-
}
|
1117 |
-
}
|
1118 |
-
} catch (Exception ex) {
|
1119 |
-
GM.writeLog(ex);
|
1120 |
-
}
|
1121 |
-
return helpMenus;
|
1122 |
-
}
|
1123 |
-
|
1124 |
-
/**
|
1125 |
-
* Generate Document based on xml file
|
1126 |
-
*
|
1127 |
-
* @param filename Configuration file name
|
1128 |
-
* @return
|
1129 |
-
* @throws Exception
|
1130 |
-
*/
|
1131 |
-
private Document buildDocument(String filename) throws Exception {
|
1132 |
-
Document doc = null;
|
1133 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
1134 |
-
.newInstance();
|
1135 |
-
|
1136 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
1137 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
1138 |
-
// FIXED:
|
1139 |
-
|
1140 |
-
doc = docBuilder.parse(new File(filename));
|
1141 |
-
return doc;
|
1142 |
-
}
|
1143 |
-
|
1144 |
-
/**
|
1145 |
-
* Create menu based on node
|
1146 |
-
*
|
1147 |
-
* @param rootEl
|
1148 |
-
* @return
|
1149 |
-
*/
|
1150 |
-
private JMenu buildMenu(Node rootEl) {
|
1151 |
-
NodeList list = rootEl.getChildNodes();
|
1152 |
-
NamedNodeMap tmp = rootEl.getAttributes();
|
1153 |
-
JMenu menu = new JMenu(tmp.getNamedItem("text").getNodeValue());
|
1154 |
-
menu.setName(tmp.getNamedItem("name").getNodeValue());
|
1155 |
-
String hk = tmp.getNamedItem("hotKey").getNodeValue();
|
1156 |
-
if (hk != null && !hk.trim().equals("")) {
|
1157 |
-
menu.setMnemonic(hk.charAt(0));
|
1158 |
-
}
|
1159 |
-
for (int i = 0; i < list.getLength(); i++) {
|
1160 |
-
Node el = (Node) list.item(i);
|
1161 |
-
if (el.getNodeName().equalsIgnoreCase("Separator")) {
|
1162 |
-
menu.addSeparator();
|
1163 |
-
} else if (el.getNodeName().equalsIgnoreCase("menuitem")) {
|
1164 |
-
try {
|
1165 |
-
menu.add(getNewItem(el));
|
1166 |
-
} catch (Exception e) {
|
1167 |
-
e.printStackTrace();
|
1168 |
-
}
|
1169 |
-
}
|
1170 |
-
}
|
1171 |
-
return menu;
|
1172 |
-
}
|
1173 |
-
|
1174 |
-
/**
|
1175 |
-
* Create menu item based on node
|
1176 |
-
*
|
1177 |
-
* @param el
|
1178 |
-
* @return
|
1179 |
-
*/
|
1180 |
-
private JMenuItem getNewItem(Node el) throws Exception {
|
1181 |
-
NodeList list = el.getChildNodes();
|
1182 |
-
NamedNodeMap tmp = el.getAttributes();
|
1183 |
-
String a = tmp.getNamedItem("text").getNodeValue();
|
1184 |
-
String classname = getChild(list, "commonderClass").getNodeValue();
|
1185 |
-
Node argNode = getChild(list, "commonderArgs");
|
1186 |
-
String pathname = argNode == null ? null : argNode.getNodeValue();
|
1187 |
-
JMenuItem jmenuitem = new JMenuItem(a);
|
1188 |
-
ConfigMenuAction cma;
|
1189 |
-
|
1190 |
-
cma = (ConfigMenuAction) Class.forName(classname).newInstance();
|
1191 |
-
cma.setConfigArgument(pathname);
|
1192 |
-
jmenuitem.addActionListener(cma);
|
1193 |
-
|
1194 |
-
String hk = tmp.getNamedItem("hotKey").getNodeValue();
|
1195 |
-
if (hk != null && !"".equals(hk)) {
|
1196 |
-
jmenuitem.setMnemonic(hk.charAt(0));
|
1197 |
-
}
|
1198 |
-
return jmenuitem;
|
1199 |
-
|
1200 |
-
}
|
1201 |
-
|
1202 |
-
/**
|
1203 |
-
* Get child node
|
1204 |
-
*
|
1205 |
-
* @param list
|
1206 |
-
* @param key
|
1207 |
-
* @return
|
1208 |
-
*/
|
1209 |
-
private static Node getChild(NodeList list, String key) {
|
1210 |
-
if (list == null)
|
1211 |
-
return null;
|
1212 |
-
for (int i = 0; i < list.getLength(); i++) {
|
1213 |
-
Node node = list.item(i);
|
1214 |
-
if (node != null && node.getNodeName().equals(key)) {
|
1215 |
-
return node.getChildNodes().item(0);
|
1216 |
-
}
|
1217 |
-
}
|
1218 |
-
return null;
|
1219 |
-
}
|
1220 |
-
|
1221 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10002.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.ide.common;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.List;import java.util.Set;import javax.swing.AbstractAction;import javax.swing.Action;import javax.swing.Icon;import javax.swing.JInternalFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JSeparator;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.scudata.app.common.AppConsts;import com.scudata.common.IntArrayList;import com.scudata.common.Logger;import com.scudata.common.MessageManager;import com.scudata.common.StringUtils;import com.scudata.ide.common.resources.IdeCommonMessage;import com.scudata.ide.spl.GMSpl;import com.scudata.ide.spl.GVSpl;import com.scudata.ide.spl.resources.IdeSplMessage;/** * The base class of the IDE menu * */public abstract class AppMenu extends JMenuBar { private static final long serialVersionUID = 1L; /** * Recent connections */ public JMenuItem[] connItem = new JMenuItem[GC.RECENT_MENU_COUNT]; /** * Recent files */ public JMenuItem[] fileItem = new JMenuItem[GC.RECENT_MENU_COUNT]; /** * Recent main path */ public JMenuItem[] mainPathItem = new JMenuItem[GC.RECENT_MENU_COUNT]; /** * Live menu upper limit */ private static final int LIVE_MENU_COUNT = 9; /** * Temporary live menu */ protected JMenu tmpLiveMenu; /** * Collection of active menus */ protected static HashSet<JMenuItem> liveMenuItems = new HashSet<JMenuItem>(); /** * The active menu */ protected static JMenu liveMenu; /** * Collection of menus */ protected static HashMap<Short, JMenuItem> menuItems = new HashMap<Short, JMenuItem>(); /** * Message Resource Manager */ private MessageManager mManager = IdeCommonMessage.get(); /** * Window menu */ public static JMenu windowMenu; /** * Help menu */ public static JMenu helpMenu; /** * Temporary live menu items */ protected static HashSet<JMenuItem> tmpLiveMenuItems = new HashSet<JMenuItem>(); /** * IDE common MessageManager */ private MessageManager mm = IdeCommonMessage.get(); /** * Reset privilege menu */ public void resetPrivilegeMenu() { } /** * Set whether the menu is enable * * @param menuIds * @param enable */ public void setEnable(short[] menuIds, boolean enable) { for (int i = 0; i < menuIds.length; i++) { JMenuItem mi = menuItems.get(menuIds[i]); if (mi == null) { continue; } mi.setEnabled(enable); } } /** * Set whether the menu is visible * * @param menuIds * @param visible */ public void setMenuVisible(short[] menuIds, boolean visible) { for (int i = 0; i < menuIds.length; i++) { JMenuItem mi = menuItems.get(menuIds[i]); if (mi == null) { continue; } mi.setVisible(visible); } } /** * The prefix of the active menu */ private final String PRE_LIVE_MENU = "live_"; /** * Adde the active menu * * @param sheetTitle */ public void addLiveMenu(String sheetTitle) { Action action = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { try { JMenuItem rmi; Object o = e.getSource(); if (o == null) { return; } rmi = (JMenuItem) o; rmi.setIcon(getSelectedIcon(true)); JMenuItem tt = (JMenuItem) e.getSource(); JInternalFrame sheet = GV.appFrame.getSheet(tt.getText()); if (!GV.appFrame.showSheet(sheet)) return; GV.toolWin.refreshSheet(sheet); } catch (Throwable e2) { GM.showException(e2); } } }; if (liveMenu == null) { return; } JMenuItem mi = GM.getMenuByName(this, PRE_LIVE_MENU + sheetTitle); JMenuItem rmi; resetLiveMenuItems(); if (mi == null) { if (liveMenu.getItemCount() == LIVE_MENU_COUNT - 1) { liveMenu.addSeparator(); } rmi = new JMenuItem(sheetTitle); // ��˵��IJ˵�����Ϊ���ڱ��⣬���Dz˵�������� rmi.setName(PRE_LIVE_MENU + sheetTitle); rmi.addActionListener(action); liveMenu.add(rmi); liveMenuItems.add(rmi); rmi.setIcon(getSelectedIcon(true)); } else { rmi = (JMenuItem) mi; rmi.setIcon(getSelectedIcon(true)); } } /** * The icon for the active menu. The current window will be displayed as * selected. * * @param isSelected * @return */ private Icon getSelectedIcon(boolean isSelected) { if (isSelected) { return GM.getMenuImageIcon("selected"); } else { return GM.getMenuImageIcon("blank"); } } /** * Remove the active menu * * @param sheetTitle */ public void removeLiveMenu(String sheetTitle) { JMenuItem mi = (JMenuItem) GM.getMenuByName(this, PRE_LIVE_MENU + sheetTitle); if (mi != null) { liveMenu.remove(mi); liveMenuItems.remove(mi); } if (liveMenu != null && liveMenu.getItemCount() == LIVE_MENU_COUNT) { liveMenu.remove(LIVE_MENU_COUNT - 1); } } /** * Rename the active menu * * @param srcName * @param tarName */ public void renameLiveMenu(String srcName, String tarName) { JMenuItem mi = GM.getMenuByName(this, srcName); if (mi != null) { mi.setName(tarName); mi.setText(tarName); } } /** * Reset the active menu */ private void resetLiveMenuItems() { JMenuItem rmi; Iterator<JMenuItem> it = liveMenuItems.iterator(); while (it.hasNext()) { rmi = (JMenuItem) it.next(); rmi.setIcon(getSelectedIcon(false)); } } /** * After the data source is connected */ public abstract void dataSourceConnected(); /** * Get the recent connection menu * * @return */ public JMenu getRecentConn() { Action actionNew = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { JMenuItem tt = (JMenuItem) e.getSource(); GV.appFrame.openConnection(tt.getText()); try { ConfigUtilIde.writeConfig(); } catch (Exception ex) { Logger.debug(ex); } dataSourceConnected(); } }; JMenu menu = GM.getMenuItem( mManager.getMessage(GC.MENU + GC.RECENT_CONNS), 'T', false); try { ConfigFile.getConfigFile().loadRecentConnection(connItem); for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) { connItem[i].addActionListener(actionNew); if (connItem[i].isVisible()) menu.add(connItem[i]); } } catch (Throwable e) { GM.showException(e); } return menu; } /** * Refresh recent connections * * @param dsName * @throws Throwable */ public void refreshRecentConn(String dsName) throws Throwable { if (!StringUtils.isValidString(dsName)) { return; } String tempConnName; int point = GC.RECENT_MENU_COUNT - 1; for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) { if (connItem[i] == null) return; tempConnName = connItem[i].getText(); if (dsName.equals(tempConnName)) { point = i; break; } } for (int i = point; i > 0; i--) { tempConnName = connItem[i - 1].getText(); connItem[i].setText(tempConnName); connItem[i].setVisible(!tempConnName.equals("")); } connItem[0].setText(dsName); connItem[0].setVisible(true); ConfigFile.getConfigFile().storeRecentConnections(connItem); } /** * Get window menu * * @return JMenu */ public JMenu getWindowMenu() { return getWindowMenu(true); } /** * Get window menu * * @param showViewConsole * @return */ public JMenu getWindowMenu(boolean showViewConsole) { if (windowMenu != null) { return windowMenu; } JMenu menu = getCommonMenuItem(GC.WINDOW, 'W', true); menu.add(newCommonMenuItem(GC.iSHOW_WINLIST, GC.SHOW_WINLIST, 'W', GC.NO_MASK, false)); JMenuItem mi = newCommonMenuItem(GC.iVIEW_CONSOLE, GC.VIEW_CONSOLE, 'Q', ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK, false); mi.setEnabled(showViewConsole); mi.setVisible(showViewConsole); menu.add(mi); mi = newCommonMenuItem(GC.iVIEW_RIGHT, GC.VIEW_RIGHT, 'R', ActionEvent.ALT_MASK + ActionEvent.SHIFT_MASK, false); mi.setEnabled(showViewConsole); mi.setVisible(showViewConsole); menu.add(mi); menu.addSeparator(); menu.add(newCommonMenuItem(GC.iCASCADE, GC.CASCADE, 'C', GC.NO_MASK, true)); menu.add(newCommonMenuItem(GC.iTILEHORIZONTAL, GC.TILEHORIZONTAL, 'H', GC.NO_MASK)); menu.add(newCommonMenuItem(GC.iTILEVERTICAL, GC.TILEVERTICAL, 'V', GC.NO_MASK)); menu.add(newCommonMenuItem(GC.iLAYER, GC.LAYER, 'M', GC.NO_MASK)); windowMenu = menu; return menu; } /** * Get help menu * * @return */ public JMenu getHelpMenu() { if (helpMenu != null) { return helpMenu; } JMenu menu = getCommonMenuItem(GC.HELP, 'H', true); List<Object> configMenus = buildMenuFromConfig(); for (int i = 0; i < configMenus.size(); i++) { Object o = configMenus.get(i); if (o instanceof JMenu) { menu.add((JMenu) o, i); ((JMenu) o).setIcon(GM.getMenuImageIcon("blank")); } else if (o instanceof JMenuItem) { menu.add((JMenuItem) o, i); ((JMenuItem) o).setIcon(GM.getMenuImageIcon("blank")); } else if (o instanceof JSeparator) { menu.add((JSeparator) o, i); } } menu.add(newCommonMenuItem(GC.iABOUT, GC.ABOUT, 'A', GC.NO_MASK, true)); menu.add(newCommonMenuItem(GC.iMEMORYTIDY, GC.MEMORYTIDY, 'M', GC.NO_MASK)); helpMenu = menu; return menu; } /** * Get common menu item * * @param menuId Menu ID defined in GC * @param mneKey The Mnemonic * @param isMain Whether it is a menu. Menu item when false * @return */ public JMenu getCommonMenuItem(String menuId, char mneKey, boolean isMain) { return GM.getMenuItem(mm.getMessage(GC.MENU + menuId), mneKey, isMain); } /** * Reset live menu */ public void resetLiveMenu() { liveMenuItems = tmpLiveMenuItems; liveMenu = tmpLiveMenu; } /** * Refresh the recent files * * @param fileName The new file name is placed first * @throws Throwable */ public void refreshRecentFile(String fileName) throws Throwable { if (!StringUtils.isValidString(fileName)) { return; } GM.setCurrentPath(fileName); String tempFileName; int point = GC.RECENT_MENU_COUNT - 1; for (int i = 0; i < fileItem.length; i++) { tempFileName = fileItem[i].getText(); if (fileName.equals(tempFileName)) { point = i; break; } } for (int i = point; i > 0; i--) { tempFileName = fileItem[i - 1].getText(); fileItem[i].setText(tempFileName); fileItem[i].setVisible(!tempFileName.equals("")); } fileItem[0].setText(fileName); fileItem[0].setVisible(true); ConfigFile.getConfigFile() .storeRecentFiles(ConfigFile.APP_DM, fileItem); } /** * Refresh recent files when closing the sheet * * @param fileName * @param frames * @throws Throwable */ public void refreshRecentFileOnClose(String fileName, JInternalFrame[] frames) throws Throwable { if (!StringUtils.isValidString(fileName)) { return; } if (frames == null || frames.length == 0) return; String tempFileName; int point = -1; for (int i = 0; i < fileItem.length; i++) { if (fileName.equals(fileItem[i].getText())) { point = i; break; } } if (point == -1) { return; } if (frames.length > GC.RECENT_MENU_COUNT) { // There are more open sheets than the most recent file limit for (int i = point; i < GC.RECENT_MENU_COUNT - 1; i++) { tempFileName = fileItem[i + 1].getText(); fileItem[i].setText(tempFileName); fileItem[i].setVisible(!tempFileName.equals("")); } Set<String> lastNames = new HashSet<String>(); for (int i = 0; i < GC.RECENT_MENU_COUNT - 1; i++) { if (StringUtils.isValidString(fileItem[i].getText())) { lastNames.add(fileItem[i].getText()); } } long maxTime = 0L; String lastSheetName = null; for (JInternalFrame frame : frames) { IPrjxSheet sheet = (IPrjxSheet) frame; String sheetName = sheet.getFileName(); if (lastNames.contains(sheetName)) continue; if (lastSheetName == null || sheet.getCreateTime() > maxTime) { maxTime = sheet.getCreateTime(); lastSheetName = sheetName; } } // Select the last one opened among the remaining open sheets fileItem[GC.RECENT_MENU_COUNT - 1].setText(lastSheetName); fileItem[GC.RECENT_MENU_COUNT - 1].setVisible(true); } else { // Move file back for (int i = point; i < frames.length + 1; i++) { tempFileName = fileItem[i + 1].getText(); fileItem[i].setText(tempFileName); fileItem[i].setVisible(!tempFileName.equals("")); } fileItem[frames.length].setText(fileName); fileItem[frames.length].setVisible(true); } ConfigFile.getConfigFile() .storeRecentFiles(ConfigFile.APP_DM, fileItem); } /** * Get recent file menu * * @return */ public JMenu getRecentFile() { final JMenu menu = getCommonMenuItem(GC.RECENT_FILES, 'F', false); final Action actionNew = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { JMenuItem tt = (JMenuItem) e.getSource(); try { GV.appFrame.openSheetFile(tt.getText()); } catch (Throwable t) { GM.showException(t); if (StringUtils.isValidString(tt.getText())) { File f = new File(tt.getText()); if (!f.exists()) { if (fileItem != null) { int len = fileItem.length; int index = -1; for (int i = 0; i < len; i++) { if (tt.getText().equalsIgnoreCase( fileItem[i].getText())) { index = i; break; } } if (index == -1) return; JMenuItem[] newFileItem = new JMenuItem[GC.RECENT_MENU_COUNT]; if (index > 0) { System.arraycopy(fileItem, 0, newFileItem, 0, index); } if (index < len - 1) { System.arraycopy(fileItem, index + 1, newFileItem, index, len - index - 1); } newFileItem[len - 1] = new JMenuItem(""); newFileItem[len - 1].setVisible(false); newFileItem[len - 1].addActionListener(this); fileItem = newFileItem; try { ConfigFile .getConfigFile() .storeRecentFiles( ConfigFile.APP_DM, fileItem); } catch (Throwable e1) { e1.printStackTrace(); } try { loadRecentFiles(menu, this); } catch (Throwable e1) { e1.printStackTrace(); } } } } } } }; try { loadRecentFiles(menu, actionNew); } catch (Throwable e) { GM.showException(e); } return menu; } /** * Load the most recent file and set it to the menu * * @param menu * @param actionNew * @throws Throwable */ private void loadRecentFiles(JMenu menu, Action actionNew) throws Throwable { menu.removeAll(); ConfigFile.getConfigFile().loadRecentFiles(ConfigFile.APP_DM, fileItem); for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) { fileItem[i].addActionListener(actionNew); if (fileItem[i].isVisible()) menu.add(fileItem[i]); } } /** * "Other" on the recent main path menu */ private static final String MAINPATH_OTHER = IdeCommonMessage.get() .getMessage("prjxappmenu.other"); /** * Refresh the recent main paths * * @param fileName * @throws Throwable */ public void refreshRecentMainPath(String fileName) throws Throwable { if (!StringUtils.isValidString(fileName)) { return; } String tempFileName; int point = GC.RECENT_MENU_COUNT - 1; for (int i = 0; i < mainPathItem.length; i++) { tempFileName = mainPathItem[i].getText(); if (fileName.equals(tempFileName)) { point = i; break; } } for (int i = point; i > 0; i--) { tempFileName = mainPathItem[i - 1].getText(); mainPathItem[i].setText(tempFileName); mainPathItem[i].setVisible(!tempFileName.equals("")); } mainPathItem[0].setText(fileName); mainPathItem[0].setVisible(false); ConfigFile.getConfigFile().storeRecentMainPaths(ConfigFile.APP_DM, mainPathItem); } /** * Get recent main paths menu * * @return */ public JMenu getRecentMainPaths() { final JMenu menu = getCommonMenuItem(GC.RECENT_MAINPATH, 'M', false); final Action actionNew = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { JMenuItem tt = (JMenuItem) e.getSource(); try { if (MAINPATH_OTHER.equals(tt.getText())) { // Other String sdir = GM .dialogSelectDirectory(GV.lastDirectory); if (sdir == null) return; ConfigOptions.sMainPath = sdir; GV.config.setMainPath(sdir); ConfigOptions.applyOptions(); ConfigUtilIde.writeConfig(); refreshRecentMainPath(sdir); if (GVSpl.fileTree != null) GVSpl.fileTree.changeMainPath(sdir); JOptionPane.showMessageDialog( GV.appFrame, IdeCommonMessage.get().getMessage( "prjxappmenu.setmainpath", sdir)); } else { File f = new File(tt.getText()); if (!f.exists() || !f.isDirectory()) { JOptionPane.showMessageDialog( GV.appFrame, IdeCommonMessage.get().getMessage( "prjxappmenu.nomainpath", tt.getText())); } else { String sdir = tt.getText(); ConfigOptions.sMainPath = sdir; GV.config.setMainPath(sdir); ConfigOptions.applyOptions(); if (GVSpl.fileTree != null) GVSpl.fileTree.changeMainPath(sdir); ConfigUtilIde.writeConfig(); refreshRecentMainPath(sdir); JOptionPane.showMessageDialog( GV.appFrame, IdeCommonMessage.get().getMessage( "prjxappmenu.setmainpath", sdir)); return; } } } catch (Throwable t) { GM.showException(t); } if (StringUtils.isValidString(tt.getText())) { File f = new File(tt.getText()); if (!f.exists()) { if (mainPathItem != null) { int len = mainPathItem.length; int index = -1; for (int i = 0; i < len; i++) { if (tt.getText().equalsIgnoreCase( mainPathItem[i].getText())) { index = i; break; } } if (index == -1) return; JMenuItem[] newFileItem = new JMenuItem[GC.RECENT_MENU_COUNT]; if (index > 0) { System.arraycopy(mainPathItem, 0, newFileItem, 0, index); } if (index < len - 1) { System.arraycopy(mainPathItem, index + 1, newFileItem, index, len - index - 1); } newFileItem[len - 1] = new JMenuItem(""); newFileItem[len - 1].setVisible(false); newFileItem[len - 1].addActionListener(this); mainPathItem = newFileItem; try { ConfigFile .getConfigFile() .storeRecentMainPaths( ConfigFile.APP_DM, mainPathItem); } catch (Throwable e1) { e1.printStackTrace(); } try { loadRecentMainPaths(menu, this); } catch (Throwable e1) { e1.printStackTrace(); } } } } } }; try { loadRecentMainPaths(menu, actionNew); } catch (Throwable e) { GM.showException(e); } return menu; } /** * Load the recent main paths and set it to the menu * * @param menu * @param actionNew * @throws Throwable */ private void loadRecentMainPaths(JMenu menu, Action actionNew) throws Throwable { menu.removeAll(); boolean hasVisible = ConfigFile.getConfigFile().loadRecentMainPaths( ConfigFile.APP_DM, mainPathItem); for (int i = 0; i < GC.RECENT_MENU_COUNT; i++) { mainPathItem[i].addActionListener(actionNew); menu.add(mainPathItem[i]); } if (hasVisible) { menu.addSeparator(); } JMenuItem other = new JMenuItem(MAINPATH_OTHER); other.addActionListener(actionNew); menu.add(other); } /** * Enable save menu * * @param enable */ public void enableSave(boolean enable) { JMenuItem mi = menuItems.get(GC.iSAVE); mi.setEnabled(enable); } /** * �˵�ִ�еļ����� */ protected ActionListener menuAction = new ActionListener() { public void actionPerformed(ActionEvent e) { String menuId = ""; try { JMenuItem mi = (JMenuItem) e.getSource(); menuId = mi.getName(); short cmdId = Short.parseShort(menuId); executeCmd(cmdId); } catch (Exception ex) { GM.showException(ex); } } }; /** * ִ�в˵����� */ public void executeCmd(short cmdId) { try { GMSpl.executeCmd(cmdId); } catch (Exception e) { GM.showException(e); } } /** * ��������Դ������ */ protected MessageManager mmSpl = IdeSplMessage.get(); /** * * �½��������˵��� * * @param cmdId ��GCSpl�ж�������� * @param menuId ��GCSpl�ж���IJ˵��� * @param isMain �Ƿ�˵���true�˵���false�˵����� * @return */ protected JMenu getSplMenuItem(String menuId, char mneKey, boolean isMain) { return GM.getMenuItem(mmSpl.getMessage(GC.MENU + menuId), mneKey, isMain); } /** * �½��������˵��� * * @param cmdId ��GCSpl�ж�������� * @param menuId ��GCSpl�ж���IJ˵��� * @param mneKey The Mnemonic * @param mask int, Because ActionEvent.META_MASK is almost not used. This key * seems to be only available on Macintosh keyboards. It is used * here instead of no accelerator key. * @return */ protected JMenuItem newSplMenuItem(short cmdId, String menuId, char mneKey, int mask) { return newSplMenuItem(cmdId, menuId, mneKey, mask, false); } /** * �½��������˵��� * * @param cmdId ��GCSpl�ж�������� * @param menuId ��GCSpl�ж���IJ˵��� * @param mneKey The Mnemonic * @param mask int, Because ActionEvent.META_MASK is almost not used. This * key seems to be only available on Macintosh keyboards. It is * used here instead of no accelerator key. * @param hasIcon �˵����Ƿ���ͼ�� * @return */ protected JMenuItem newSplMenuItem(short cmdId, String menuId, char mneKey, int mask, boolean hasIcon) { String menuText = menuId; if (menuText.indexOf('.') > 0) { menuText = mmSpl.getMessage(GC.MENU + menuId); } return newMenuItem(cmdId, menuId, mneKey, mask, hasIcon, menuText); } /** * �½��������˵��� * * @param cmdId ��GCSpl�ж�������� * @param menuId ��GCSpl�ж���IJ˵��� * @param mneKey The Mnemonic * @param mask int, Because ActionEvent.META_MASK is almost not used. This * key seems to be only available on Macintosh keyboards. It is * used here instead of no accelerator key. * @param hasIcon �˵����Ƿ���ͼ�� * @param menuText �˵����ı� * @return */ protected JMenuItem newMenuItem(short cmdId, String menuId, char mneKey, int mask, boolean hasIcon, String menuText) { JMenuItem mItem = GM.getMenuItem(cmdId, menuId, mneKey, mask, hasIcon, menuText); mItem.addActionListener(menuAction); menuItems.put(cmdId, mItem); return mItem; } /** * Clone menu item * * @param cmdId Command ID * @return */ public JMenuItem cloneMenuItem(short cmdId) { return cloneMenuItem(cmdId, null); } /** * Clone menu item * * @param cmdId Command ID * @param listener ActionListener * @return */ public JMenuItem cloneMenuItem(short cmdId, ActionListener listener) { JMenuItem mItem = new JMenuItem(); JMenuItem jmi = menuItems.get(cmdId); String text = jmi.getText(); int pos = text.indexOf("("); // Remove shortcut key definition if (pos > 0) { text = text.substring(0, pos); } mItem.setText(text); mItem.setName(jmi.getName()); mItem.setIcon(jmi.getIcon()); mItem.setVisible(jmi.isVisible()); mItem.setEnabled(jmi.isEnabled()); mItem.setAccelerator(jmi.getAccelerator()); if (listener == null) { mItem.addActionListener(jmi.getActionListeners()[0]); } else { mItem.addActionListener(listener); } return mItem; } /** * New menu item * * @param cmdId Command ID * @param menuId Menu name * @param mneKey char, The Mnemonic * @param mask int, Because ActionEvent.META_MASK is almost not used. This key * seems to be only available on Macintosh keyboards. It is used * here instead of no accelerator key. * @return */ protected JMenuItem newCommonMenuItem(short cmdId, String menuId, char mneKey, int mask) { return newCommonMenuItem(cmdId, menuId, mneKey, mask, false); } /** * New menu item * * @param cmdId Command ID * @param menuId Menu name * @param mneKey char, The Mnemonic * @param mask int, Because ActionEvent.META_MASK is almost not used. This * key seems to be only available on Macintosh keyboards. It is * used here instead of no accelerator key. * @param hasIcon Whether the menu item has an icon * @return */ protected JMenuItem newCommonMenuItem(short cmdId, String menuId, char mneKey, int mask, boolean hasIcon) { JMenuItem mItem = GM.getMenuItem(cmdId, menuId, mneKey, mask, hasIcon, mm.getMessage(GC.MENU + menuId)); mItem.addActionListener(menuAction); menuItems.put(cmdId, mItem); return mItem; } /** * Set whether the menu is enabled * * @param cmdId Command ID * @param enabled Whether the menu is enabled */ public void setMenuEnabled(short cmdId, boolean enabled) { JMenuItem mi = menuItems.get(cmdId); if (mi != null) { mi.setEnabled(enabled); } } /** * Whether the menu is enabled * * @param cmdId Command ID * @return */ public boolean isMenuEnabled(short cmdId) { JMenuItem mi = menuItems.get(cmdId); if (mi != null) { return mi.isEnabled(); } return false; } /** * Set whether the menus are enabled * * @param cmdIds Command IDs * @param enabled Whether the menus are enabled */ public void setMenuEnabled(IntArrayList cmdIds, boolean enabled) { if (cmdIds == null) { return; } for (int i = 0; i < cmdIds.size(); i++) { short cmdId = (short) cmdIds.getInt(i); setMenuEnabled(cmdId, enabled); } } /** * Set whether the menus are enabled * * @param cmdIds Command IDs * @param enabled Whether the menus are enabled */ public void setMenuEnabled(short[] cmdIds, boolean enabled) { if (cmdIds == null) { return; } for (int i = 0; i < cmdIds.length; i++) { short cmdId = cmdIds[i]; setMenuEnabled(cmdId, enabled); } } /** * Set whether the menu is visible * * @param cmdId Command ID * @param visible Whether the menu is visible */ public void setMenuVisible(short cmdId, boolean visible) { JMenuItem mi = menuItems.get(cmdId); if (mi != null) { mi.setVisible(visible); } } /** * Set whether the menus are visible * * @param cmdIds Command IDs * @param visible Whether the menus are visible */ public void setMenuVisible(IntArrayList cmdIds, boolean visible) { if (cmdIds == null) { return; } for (int i = 0; i < cmdIds.size(); i++) { short cmdId = (short) cmdIds.getInt(i); setMenuVisible(cmdId, visible); } } /** * Get all menu items * * @return */ public abstract short[] getMenuItems(); /** * �����Զ���˵���Ŀǰֻ�а����˵� * @return �˵����б� */ protected List<Object> buildMenuFromConfig() { return buildMenuFromConfig("menuconfig"); } /** * �����Զ���˵���Ŀǰֻ�а����˵� * @param fileName �ļ��� * @return �˵����б� */ protected List<Object> buildMenuFromConfig(String fileName) { List<Object> helpMenus = new ArrayList<Object>(); try { Document doc = null; File configFile = new File(GM.getAbsolutePath(GC.PATH_CONFIG), fileName + GM.getLanguageSuffix() + "." + AppConsts.FILE_XML); doc = buildDocument(configFile.getAbsolutePath()); Element root = doc.getDocumentElement(); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node el = (Node) list.item(i); if (el.getNodeName().equalsIgnoreCase("help")) { // ���ɰ����˵� NodeList helpList = el.getChildNodes(); for (int j = 0; j < helpList.getLength(); j++) { el = (Node) helpList.item(j); if (el.getNodeName().equalsIgnoreCase("menu")) { helpMenus.add(buildMenu(el)); } else if (el.getNodeName() .equalsIgnoreCase("menuitem")) { helpMenus.add(getNewItem(el)); } else if (el.getNodeName().equalsIgnoreCase( "separator")) { helpMenus.add(new JSeparator()); } } } } } catch (Exception ex) { GM.writeLog(ex); } return helpMenus; } /** * Generate Document based on xml file * * @param filename Configuration file name * @return * @throws Exception */ private Document buildDocument(String filename) throws Exception { Document doc = null; DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: doc = docBuilder.parse(new File(filename)); return doc; } /** * Create menu based on node * * @param rootEl * @return */ private JMenu buildMenu(Node rootEl) { NodeList list = rootEl.getChildNodes(); NamedNodeMap tmp = rootEl.getAttributes(); JMenu menu = new JMenu(tmp.getNamedItem("text").getNodeValue()); menu.setName(tmp.getNamedItem("name").getNodeValue()); String hk = tmp.getNamedItem("hotKey").getNodeValue(); if (hk != null && !hk.trim().equals("")) { menu.setMnemonic(hk.charAt(0)); } for (int i = 0; i < list.getLength(); i++) { Node el = (Node) list.item(i); if (el.getNodeName().equalsIgnoreCase("Separator")) { menu.addSeparator(); } else if (el.getNodeName().equalsIgnoreCase("menuitem")) { try { menu.add(getNewItem(el)); } catch (Exception e) { e.printStackTrace(); } } } return menu; } /** * Create menu item based on node * * @param el * @return */ private JMenuItem getNewItem(Node el) throws Exception { NodeList list = el.getChildNodes(); NamedNodeMap tmp = el.getAttributes(); String a = tmp.getNamedItem("text").getNodeValue(); String classname = getChild(list, "commonderClass").getNodeValue(); Node argNode = getChild(list, "commonderArgs"); String pathname = argNode == null ? null : argNode.getNodeValue(); JMenuItem jmenuitem = new JMenuItem(a); ConfigMenuAction cma; cma = (ConfigMenuAction) Class.forName(classname).newInstance(); cma.setConfigArgument(pathname); jmenuitem.addActionListener(cma); String hk = tmp.getNamedItem("hotKey").getNodeValue(); if (hk != null && !"".equals(hk)) { jmenuitem.setMnemonic(hk.charAt(0)); } return jmenuitem; } /** * Get child node * * @param list * @param key * @return */ private static Node getChild(NodeList list, String key) { if (list == null) return null; for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node != null && node.getNodeName().equals(key)) { return node.getChildNodes().item(0); } } return null; }}
|
data/java/10003.java
DELETED
@@ -1,727 +0,0 @@
|
|
1 |
-
package com.scudata.ide.common;
|
2 |
-
|
3 |
-
import java.io.ByteArrayOutputStream;
|
4 |
-
import java.io.File;
|
5 |
-
import java.io.FileInputStream;
|
6 |
-
import java.io.InputStream;
|
7 |
-
import java.io.OutputStream;
|
8 |
-
import java.io.Writer;
|
9 |
-
import java.util.ArrayList;
|
10 |
-
import java.util.List;
|
11 |
-
import java.util.Properties;
|
12 |
-
import java.util.StringTokenizer;
|
13 |
-
|
14 |
-
import javax.xml.parsers.DocumentBuilder;
|
15 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
16 |
-
import javax.xml.transform.OutputKeys;
|
17 |
-
import javax.xml.transform.Transformer;
|
18 |
-
import javax.xml.transform.TransformerFactory;
|
19 |
-
import javax.xml.transform.dom.DOMSource;
|
20 |
-
import javax.xml.transform.stream.StreamResult;
|
21 |
-
|
22 |
-
import org.w3c.dom.Document;
|
23 |
-
import org.w3c.dom.Element;
|
24 |
-
import org.w3c.dom.NamedNodeMap;
|
25 |
-
import org.w3c.dom.Node;
|
26 |
-
import org.w3c.dom.NodeList;
|
27 |
-
|
28 |
-
import com.scudata.app.common.Section;
|
29 |
-
import com.scudata.common.MessageManager;
|
30 |
-
import com.scudata.ide.common.resources.IdeCommonMessage;
|
31 |
-
|
32 |
-
/**
|
33 |
-
* Used to parse xml files
|
34 |
-
*/
|
35 |
-
public class XMLFile {
|
36 |
-
|
37 |
-
/**
|
38 |
-
* XML file path
|
39 |
-
*/
|
40 |
-
public String xmlFile = null;
|
41 |
-
|
42 |
-
/**
|
43 |
-
* XML Document
|
44 |
-
*/
|
45 |
-
private Document xmlDocument = null;
|
46 |
-
|
47 |
-
/**
|
48 |
-
* Common MessageManager
|
49 |
-
*/
|
50 |
-
private MessageManager mm = IdeCommonMessage.get();
|
51 |
-
|
52 |
-
/**
|
53 |
-
* Constructor
|
54 |
-
*
|
55 |
-
* @param file
|
56 |
-
* XML file path
|
57 |
-
* @throws Exception
|
58 |
-
*/
|
59 |
-
public XMLFile(String file) throws Exception {
|
60 |
-
this(new File(file), "root");
|
61 |
-
}
|
62 |
-
|
63 |
-
/**
|
64 |
-
* Constructor
|
65 |
-
*
|
66 |
-
* @param file
|
67 |
-
* XML file path
|
68 |
-
* @param root
|
69 |
-
* Root node name
|
70 |
-
* @throws Exception
|
71 |
-
*/
|
72 |
-
public XMLFile(File file, String root) throws Exception {
|
73 |
-
if (file != null) {
|
74 |
-
xmlFile = file.getAbsolutePath();
|
75 |
-
if (file.exists() && file.isFile()) {
|
76 |
-
loadXMLFile(new FileInputStream(file));
|
77 |
-
} else {
|
78 |
-
XMLFile.newXML(xmlFile, root);
|
79 |
-
}
|
80 |
-
} else {
|
81 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
82 |
-
.newInstance();
|
83 |
-
|
84 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
85 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
86 |
-
// FIXED:
|
87 |
-
|
88 |
-
xmlDocument = docBuilder.newDocument();
|
89 |
-
Element eRoot = xmlDocument.createElement(root);
|
90 |
-
eRoot.normalize();
|
91 |
-
xmlDocument.appendChild(eRoot);
|
92 |
-
}
|
93 |
-
}
|
94 |
-
|
95 |
-
/**
|
96 |
-
* Constructor
|
97 |
-
*
|
98 |
-
* @param is
|
99 |
-
* File InputStream
|
100 |
-
* @throws Exception
|
101 |
-
*/
|
102 |
-
public XMLFile(InputStream is) throws Exception {
|
103 |
-
loadXMLFile(is);
|
104 |
-
}
|
105 |
-
|
106 |
-
/**
|
107 |
-
* Load XML file from file input stream
|
108 |
-
*
|
109 |
-
* @param is
|
110 |
-
* @throws Exception
|
111 |
-
*/
|
112 |
-
private void loadXMLFile(InputStream is) throws Exception {
|
113 |
-
xmlDocument = parseXml(is);
|
114 |
-
}
|
115 |
-
|
116 |
-
/**
|
117 |
-
* Create a new XML file
|
118 |
-
*
|
119 |
-
* @param file
|
120 |
-
* The name of the file to be created. If the file exists, it
|
121 |
-
* will overwrite the original one.
|
122 |
-
* @param root
|
123 |
-
* Root node name
|
124 |
-
* @return Return true if the creation is successful, otherwise false.
|
125 |
-
*/
|
126 |
-
public static XMLFile newXML(String file, String root) throws Exception {
|
127 |
-
if (!isLegalXmlName(root)) {
|
128 |
-
throw new Exception(IdeCommonMessage.get().getMessage(
|
129 |
-
"xmlfile.falseroot", file, root));
|
130 |
-
}
|
131 |
-
|
132 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
133 |
-
.newInstance();
|
134 |
-
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
135 |
-
Document sxmlDocument = docBuilder.newDocument();
|
136 |
-
Element eRoot = sxmlDocument.createElement(root);
|
137 |
-
eRoot.normalize();
|
138 |
-
sxmlDocument.appendChild(eRoot);
|
139 |
-
|
140 |
-
writeNodeToFile(sxmlDocument, file);
|
141 |
-
return new XMLFile(file);
|
142 |
-
}
|
143 |
-
|
144 |
-
/**
|
145 |
-
* List all sub-elements under the path path in the file file, including
|
146 |
-
* elements and attributes.
|
147 |
-
*
|
148 |
-
* @param path
|
149 |
-
* Node path, use / as a separator, for example: "a/b/c"
|
150 |
-
* @return Return the section of the element and attribute under the path
|
151 |
-
* node
|
152 |
-
*/
|
153 |
-
public Section listAll(String path) throws Exception {
|
154 |
-
Section ss = new Section();
|
155 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
156 |
-
ss.unionSection(getNodesName(tmpNode.getChildNodes()));
|
157 |
-
ss.unionSection(getNodesName(tmpNode.getAttributes()));
|
158 |
-
return ss;
|
159 |
-
}
|
160 |
-
|
161 |
-
/**
|
162 |
-
* List all sub-elements under path in the file
|
163 |
-
*
|
164 |
-
* @param path
|
165 |
-
* Node path
|
166 |
-
* @return Return the section of the elements under the path node
|
167 |
-
*/
|
168 |
-
public Section listElement(String path) throws Exception {
|
169 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
170 |
-
return getNodesName(tmpNode.getChildNodes());
|
171 |
-
}
|
172 |
-
|
173 |
-
/**
|
174 |
-
* List all attributes under path in file
|
175 |
-
*
|
176 |
-
* @param path
|
177 |
-
* Node path
|
178 |
-
* @return Return the section of the attribute names under the path node
|
179 |
-
*/
|
180 |
-
public Section listAttribute(String path) throws Exception {
|
181 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
182 |
-
return getNodesName(tmpNode.getAttributes());
|
183 |
-
}
|
184 |
-
|
185 |
-
/**
|
186 |
-
* List the attribute value of the path node in the file
|
187 |
-
*
|
188 |
-
* @param path
|
189 |
-
* Node path
|
190 |
-
* @return The value of the attribute
|
191 |
-
*/
|
192 |
-
public String getAttribute(String path) {
|
193 |
-
try {
|
194 |
-
Node tmpNode = getTerminalNode(path, Node.ATTRIBUTE_NODE);
|
195 |
-
return tmpNode.getNodeValue();
|
196 |
-
} catch (Exception ex) {
|
197 |
-
return "";
|
198 |
-
}
|
199 |
-
}
|
200 |
-
|
201 |
-
/**
|
202 |
-
* Create a new element under the current path
|
203 |
-
*
|
204 |
-
* @param path
|
205 |
-
* Node path
|
206 |
-
* @param element
|
207 |
-
* The name of the element to be created
|
208 |
-
* @return The node path after the new element is successfully created
|
209 |
-
*/
|
210 |
-
public String newElement(String path, String element) throws Exception {
|
211 |
-
Element newElement = null;
|
212 |
-
if (!isLegalXmlName(element)) {
|
213 |
-
throw new Exception(mm.getMessage("xmlfile.falseelement", xmlFile,
|
214 |
-
element));
|
215 |
-
}
|
216 |
-
|
217 |
-
Node parent = getTerminalNode(path, Node.ELEMENT_NODE);
|
218 |
-
NodeList nl = parent.getChildNodes();
|
219 |
-
int i;
|
220 |
-
for (i = 0; i < nl.getLength(); i++) {
|
221 |
-
if (nl.item(i).getNodeName().equalsIgnoreCase(element)) {
|
222 |
-
break;
|
223 |
-
}
|
224 |
-
}
|
225 |
-
if (i >= nl.getLength()) {
|
226 |
-
newElement = xmlDocument.createElement(element);
|
227 |
-
parent.appendChild(newElement);
|
228 |
-
}
|
229 |
-
return path + "/" + element;
|
230 |
-
}
|
231 |
-
|
232 |
-
/**
|
233 |
-
* Create a new attribute under the current path
|
234 |
-
*
|
235 |
-
* @param path
|
236 |
-
* Node path
|
237 |
-
* @param attr
|
238 |
-
* The name of the attribute to be created
|
239 |
-
* @return Return 1 on success, -1 on failure (when the attribute with the
|
240 |
-
* same name exists)
|
241 |
-
*/
|
242 |
-
public int newAttribute(String path, String attr) throws Exception {
|
243 |
-
if (!isLegalXmlName(attr)) {
|
244 |
-
throw new Exception(mm.getMessage("xmlfile.falseattr", xmlFile,
|
245 |
-
attr));
|
246 |
-
}
|
247 |
-
|
248 |
-
Node parent = getTerminalNode(path, Node.ELEMENT_NODE);
|
249 |
-
|
250 |
-
NamedNodeMap nl = parent.getAttributes();
|
251 |
-
int i;
|
252 |
-
for (i = 0; i < nl.getLength(); i++) {
|
253 |
-
if (nl.item(i).getNodeName().equalsIgnoreCase(attr)) {
|
254 |
-
break;
|
255 |
-
}
|
256 |
-
}
|
257 |
-
if (i >= nl.getLength()) {
|
258 |
-
((Element) parent).setAttribute(attr, "");
|
259 |
-
} else {
|
260 |
-
return -1;
|
261 |
-
}
|
262 |
-
return 1;
|
263 |
-
}
|
264 |
-
|
265 |
-
/**
|
266 |
-
* Delete the node specified by path
|
267 |
-
*
|
268 |
-
* @param path
|
269 |
-
* Node path
|
270 |
-
*/
|
271 |
-
public void delete(String path) throws Exception {
|
272 |
-
deleteAttribute(path);
|
273 |
-
deleteElement(path);
|
274 |
-
}
|
275 |
-
|
276 |
-
/**
|
277 |
-
* Delete the element node specified by path
|
278 |
-
*
|
279 |
-
* @param path
|
280 |
-
* Node path
|
281 |
-
*/
|
282 |
-
public void deleteElement(String path) throws Exception {
|
283 |
-
Node nd = getTerminalNode(path, Node.ELEMENT_NODE);
|
284 |
-
Node parent = nd.getParentNode();
|
285 |
-
parent.removeChild(nd);
|
286 |
-
}
|
287 |
-
|
288 |
-
/**
|
289 |
-
* Whether the node path exists
|
290 |
-
*
|
291 |
-
* @param path
|
292 |
-
* Node path
|
293 |
-
* @return Exists when true, and does not exist when false.
|
294 |
-
*/
|
295 |
-
public boolean isPathExists(String path) {
|
296 |
-
try {
|
297 |
-
getTerminalNode(path, Node.ELEMENT_NODE);
|
298 |
-
} catch (Exception ex) {
|
299 |
-
return false;
|
300 |
-
}
|
301 |
-
return true;
|
302 |
-
}
|
303 |
-
|
304 |
-
/**
|
305 |
-
* Delete the attribute node specified by path
|
306 |
-
*
|
307 |
-
* @param path
|
308 |
-
* Node path
|
309 |
-
*/
|
310 |
-
public void deleteAttribute(String path) throws Exception {
|
311 |
-
int i = path.lastIndexOf('/');
|
312 |
-
Node parent;
|
313 |
-
if (i > 0) {
|
314 |
-
String p = path.substring(0, i);
|
315 |
-
parent = getTerminalNode(p, Node.ELEMENT_NODE);
|
316 |
-
} else {
|
317 |
-
return;
|
318 |
-
}
|
319 |
-
((Element) parent).removeAttribute(path.substring(i + 1));
|
320 |
-
}
|
321 |
-
|
322 |
-
/**
|
323 |
-
* Change the name of the attribute node of the path
|
324 |
-
*
|
325 |
-
* @param path
|
326 |
-
* Node path
|
327 |
-
* @param newName
|
328 |
-
* New name
|
329 |
-
* @throws Exception
|
330 |
-
*/
|
331 |
-
public void renameAttribute(String path, String newName) throws Exception {
|
332 |
-
int i;
|
333 |
-
i = path.lastIndexOf('/');
|
334 |
-
if (i == -1) {
|
335 |
-
throw new Exception(mm.getMessage("xmlfile.falsepath", xmlFile,
|
336 |
-
path));
|
337 |
-
}
|
338 |
-
|
339 |
-
String value = getAttribute(path);
|
340 |
-
deleteAttribute(path);
|
341 |
-
setAttribute(path.substring(0, i) + "/" + newName, value);
|
342 |
-
}
|
343 |
-
|
344 |
-
/**
|
345 |
-
* Change the name of the element node of the path
|
346 |
-
*
|
347 |
-
* @param path
|
348 |
-
* Node path
|
349 |
-
* @param newName
|
350 |
-
* New name
|
351 |
-
* @throws Exception
|
352 |
-
*/
|
353 |
-
public void renameElement(String path, String newName) throws Exception {
|
354 |
-
if (path.lastIndexOf('/') == -1) {
|
355 |
-
throw new Exception(mm.getMessage("xmlfile.renameroot", xmlFile));
|
356 |
-
}
|
357 |
-
Node nd = getTerminalNode(path, Node.ELEMENT_NODE);
|
358 |
-
Node pp = nd.getParentNode();
|
359 |
-
NodeList childNodes = pp.getChildNodes();
|
360 |
-
int i;
|
361 |
-
if (childNodes != null) {
|
362 |
-
for (i = 0; i < childNodes.getLength(); i++) {
|
363 |
-
if (newName.equalsIgnoreCase(childNodes.item(i).getNodeName())) {
|
364 |
-
throw new Exception(mm.getMessage("xmlfile.existnode",
|
365 |
-
xmlFile, newName));
|
366 |
-
}
|
367 |
-
}
|
368 |
-
}
|
369 |
-
|
370 |
-
Element newNode = xmlDocument.createElement(newName);
|
371 |
-
|
372 |
-
childNodes = nd.getChildNodes();
|
373 |
-
if (childNodes != null) {
|
374 |
-
for (i = 0; i < childNodes.getLength(); i++) {
|
375 |
-
newNode.appendChild(childNodes.item(i));
|
376 |
-
}
|
377 |
-
}
|
378 |
-
NamedNodeMap childAttr = nd.getAttributes();
|
379 |
-
Node tmpNode;
|
380 |
-
if (childAttr != null) {
|
381 |
-
for (i = 0; i < childAttr.getLength(); i++) {
|
382 |
-
tmpNode = childAttr.item(i);
|
383 |
-
newNode.setAttribute(tmpNode.getNodeName(),
|
384 |
-
tmpNode.getNodeValue());
|
385 |
-
}
|
386 |
-
}
|
387 |
-
pp.replaceChild(newNode, nd);
|
388 |
-
}
|
389 |
-
|
390 |
-
/**
|
391 |
-
* Set the attribute value of the attribute node of the path
|
392 |
-
*
|
393 |
-
* @param path
|
394 |
-
* Node path
|
395 |
-
* @param value
|
396 |
-
* The attribute value to be set, null means delete the
|
397 |
-
* attribute.
|
398 |
-
*/
|
399 |
-
public void setAttribute(String path, String value) throws Exception {
|
400 |
-
if (path == null) {
|
401 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile));
|
402 |
-
}
|
403 |
-
if (path.trim().length() == 0) {
|
404 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile));
|
405 |
-
}
|
406 |
-
if (value == null) {
|
407 |
-
deleteAttribute(path);
|
408 |
-
return;
|
409 |
-
}
|
410 |
-
Node nd;
|
411 |
-
int i = path.lastIndexOf('/');
|
412 |
-
if (i > 0) {
|
413 |
-
String p = path.substring(0, i);
|
414 |
-
String v = path.substring(i + 1);
|
415 |
-
newAttribute(p, v);
|
416 |
-
}
|
417 |
-
|
418 |
-
nd = getTerminalNode(path, Node.ATTRIBUTE_NODE);
|
419 |
-
nd.setNodeValue(value);
|
420 |
-
}
|
421 |
-
|
422 |
-
/**
|
423 |
-
* Save XML file
|
424 |
-
*
|
425 |
-
* @throws Exception
|
426 |
-
*/
|
427 |
-
public void save() throws Exception {
|
428 |
-
save(xmlFile);
|
429 |
-
}
|
430 |
-
|
431 |
-
/**
|
432 |
-
* Save XML file
|
433 |
-
*
|
434 |
-
* @param file
|
435 |
-
* XML file path
|
436 |
-
* @throws Exception
|
437 |
-
*/
|
438 |
-
public void save(String file) throws Exception {
|
439 |
-
writeNodeToFile(xmlDocument, file);
|
440 |
-
}
|
441 |
-
|
442 |
-
/**
|
443 |
-
* Get the byte array of the XML file
|
444 |
-
*
|
445 |
-
* @return
|
446 |
-
*/
|
447 |
-
public byte[] getFileBytes() {
|
448 |
-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
449 |
-
try {
|
450 |
-
outputDocument(xmlDocument, baos);
|
451 |
-
} catch (Exception ex) {
|
452 |
-
}
|
453 |
-
return baos.toByteArray();
|
454 |
-
}
|
455 |
-
|
456 |
-
/**
|
457 |
-
* Save XML file
|
458 |
-
*
|
459 |
-
* @param os
|
460 |
-
* File OutputStream
|
461 |
-
* @throws Exception
|
462 |
-
*/
|
463 |
-
public void save(OutputStream os) throws Exception {
|
464 |
-
outputDocument(xmlDocument, os);
|
465 |
-
}
|
466 |
-
|
467 |
-
/**
|
468 |
-
* Write document to file
|
469 |
-
*
|
470 |
-
* @param node
|
471 |
-
* Document
|
472 |
-
* @param file
|
473 |
-
* XML file path
|
474 |
-
* @throws Exception
|
475 |
-
*/
|
476 |
-
public static void writeNodeToFile(Document node, String file)
|
477 |
-
throws Exception {
|
478 |
-
outputDocument(node, file);
|
479 |
-
}
|
480 |
-
|
481 |
-
/**
|
482 |
-
* Output document
|
483 |
-
*
|
484 |
-
* @param node
|
485 |
-
* Document
|
486 |
-
* @param out
|
487 |
-
* The object to output to. It can be:
|
488 |
-
* String,OutputStream,Writer.
|
489 |
-
* @throws Exception
|
490 |
-
*/
|
491 |
-
public static void outputDocument(Document node, Object out)
|
492 |
-
throws Exception {
|
493 |
-
StreamResult result;
|
494 |
-
if (out instanceof String) {
|
495 |
-
result = new StreamResult((String) out);
|
496 |
-
} else if (out instanceof OutputStream) {
|
497 |
-
result = new StreamResult((OutputStream) out);
|
498 |
-
} else if (out instanceof Writer) {
|
499 |
-
result = new StreamResult((Writer) out);
|
500 |
-
} else {
|
501 |
-
return;
|
502 |
-
}
|
503 |
-
TransformerFactory tFactory = TransformerFactory.newInstance();
|
504 |
-
Transformer transformer = tFactory.newTransformer();
|
505 |
-
|
506 |
-
Properties properties = transformer.getOutputProperties();
|
507 |
-
properties.setProperty(OutputKeys.ENCODING, "UTF-8");
|
508 |
-
properties.setProperty(OutputKeys.METHOD, "xml");
|
509 |
-
properties.setProperty(OutputKeys.INDENT, "yes");
|
510 |
-
transformer.setOutputProperties(properties);
|
511 |
-
|
512 |
-
DOMSource source = new DOMSource(node);
|
513 |
-
transformer.transform(source, result);
|
514 |
-
}
|
515 |
-
|
516 |
-
/**
|
517 |
-
* Get the name Section of the nodes
|
518 |
-
*
|
519 |
-
* @param obj
|
520 |
-
* @return
|
521 |
-
* @throws Exception
|
522 |
-
*/
|
523 |
-
private Section getNodesName(Object obj) throws Exception {
|
524 |
-
Section ss = new Section();
|
525 |
-
if (obj == null) {
|
526 |
-
return ss;
|
527 |
-
}
|
528 |
-
|
529 |
-
Node nd = null;
|
530 |
-
if (obj instanceof NodeList) {
|
531 |
-
NodeList nl = (NodeList) obj;
|
532 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
533 |
-
nd = nl.item(i);
|
534 |
-
if (nd.getNodeType() != Node.ELEMENT_NODE) {
|
535 |
-
continue;
|
536 |
-
}
|
537 |
-
ss.unionSection(nd.getNodeName());
|
538 |
-
}
|
539 |
-
}
|
540 |
-
|
541 |
-
if (obj instanceof NamedNodeMap) {
|
542 |
-
NamedNodeMap nnm = (NamedNodeMap) obj;
|
543 |
-
for (int i = 0; i < nnm.getLength(); i++) {
|
544 |
-
nd = nnm.item(i);
|
545 |
-
ss.unionSection(nd.getNodeName());
|
546 |
-
}
|
547 |
-
}
|
548 |
-
return ss;
|
549 |
-
}
|
550 |
-
|
551 |
-
/**
|
552 |
-
* Locate node among nodes
|
553 |
-
*
|
554 |
-
* @param obj
|
555 |
-
* NodeList or NamedNodeMap
|
556 |
-
* @param nodeName
|
557 |
-
* Node name
|
558 |
-
* @return
|
559 |
-
* @throws Exception
|
560 |
-
*/
|
561 |
-
private Node locateNode(Object obj, String nodeName) throws Exception {
|
562 |
-
int i = 0, j = 0;
|
563 |
-
String sTmp;
|
564 |
-
Node tmpNode = null;
|
565 |
-
NodeList nl;
|
566 |
-
NamedNodeMap nnm;
|
567 |
-
|
568 |
-
if (obj instanceof NodeList) {
|
569 |
-
nl = (NodeList) obj;
|
570 |
-
i = nl.getLength();
|
571 |
-
for (j = 0; j < i; j++) {
|
572 |
-
tmpNode = nl.item(j);
|
573 |
-
sTmp = tmpNode.getNodeName();
|
574 |
-
if (sTmp.equalsIgnoreCase(nodeName)) {
|
575 |
-
break;
|
576 |
-
}
|
577 |
-
}
|
578 |
-
}
|
579 |
-
if (obj instanceof NamedNodeMap) {
|
580 |
-
nnm = (NamedNodeMap) obj;
|
581 |
-
i = nnm.getLength();
|
582 |
-
for (j = 0; j < i; j++) {
|
583 |
-
tmpNode = nnm.item(j);
|
584 |
-
sTmp = tmpNode.getNodeName();
|
585 |
-
if (sTmp.equalsIgnoreCase(nodeName)) {
|
586 |
-
break;
|
587 |
-
}
|
588 |
-
}
|
589 |
-
}
|
590 |
-
if (j == i) {
|
591 |
-
throw new Exception(mm.getMessage("xmlfile.falsenodename", xmlFile,
|
592 |
-
nodeName));
|
593 |
-
}
|
594 |
-
return tmpNode;
|
595 |
-
}
|
596 |
-
|
597 |
-
/**
|
598 |
-
* Get terminal node
|
599 |
-
*
|
600 |
-
* @param path
|
601 |
-
* Node path
|
602 |
-
* @param type
|
603 |
-
* Constants defined in org.w3c.dom.Node
|
604 |
-
* @return
|
605 |
-
* @throws Exception
|
606 |
-
*/
|
607 |
-
private Node getTerminalNode(String path, short type) throws Exception {
|
608 |
-
Node tmpNode = null;
|
609 |
-
String sNode, sLast;
|
610 |
-
int i;
|
611 |
-
if (path == null) {
|
612 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath1", xmlFile));
|
613 |
-
}
|
614 |
-
i = path.lastIndexOf('/');
|
615 |
-
if (i == -1) {
|
616 |
-
if (path.length() == 0) {
|
617 |
-
return xmlDocument;
|
618 |
-
}
|
619 |
-
sNode = path;
|
620 |
-
if (type == Node.ELEMENT_NODE) {
|
621 |
-
tmpNode = locateNode(xmlDocument.getChildNodes(), sNode);
|
622 |
-
}
|
623 |
-
} else {
|
624 |
-
sLast = path.substring(i + 1);
|
625 |
-
path = path.substring(0, i);
|
626 |
-
|
627 |
-
StringTokenizer st = new StringTokenizer(path, "/");
|
628 |
-
NodeList childNodes = xmlDocument.getChildNodes();
|
629 |
-
while (st.hasMoreTokens()) {
|
630 |
-
sNode = st.nextToken();
|
631 |
-
tmpNode = locateNode(childNodes, sNode);
|
632 |
-
if (tmpNode == null) {
|
633 |
-
throw new Exception(mm.getMessage("xmlfile.notexistpath",
|
634 |
-
xmlFile, path));
|
635 |
-
}
|
636 |
-
childNodes = tmpNode.getChildNodes();
|
637 |
-
}
|
638 |
-
if (type == Node.ELEMENT_NODE) {
|
639 |
-
tmpNode = locateNode(tmpNode.getChildNodes(), sLast);
|
640 |
-
} else {
|
641 |
-
tmpNode = locateNode(tmpNode.getAttributes(), sLast);
|
642 |
-
}
|
643 |
-
}
|
644 |
-
if (tmpNode == null) {
|
645 |
-
throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile,
|
646 |
-
path));
|
647 |
-
}
|
648 |
-
return tmpNode;
|
649 |
-
}
|
650 |
-
|
651 |
-
/**
|
652 |
-
* Is the legal XML name
|
653 |
-
*
|
654 |
-
* @param input
|
655 |
-
* Node name
|
656 |
-
* @return
|
657 |
-
*/
|
658 |
-
public static boolean isLegalXmlName(String input) {
|
659 |
-
if (input == null || input.length() == 0) {
|
660 |
-
return false;
|
661 |
-
}
|
662 |
-
return true;
|
663 |
-
}
|
664 |
-
|
665 |
-
/**
|
666 |
-
* ����XML
|
667 |
-
* @param is
|
668 |
-
* @return
|
669 |
-
* @throws Exception
|
670 |
-
*/
|
671 |
-
public static Document parseXml(InputStream is) throws Exception {
|
672 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
673 |
-
.newInstance();
|
674 |
-
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
675 |
-
return docBuilder.parse(is);
|
676 |
-
}
|
677 |
-
|
678 |
-
/**
|
679 |
-
* ������ȡ�ӽڵ�
|
680 |
-
* @param parent
|
681 |
-
* @param childName
|
682 |
-
* @return
|
683 |
-
*/
|
684 |
-
public static Element getChild(Node parent, String childName) {
|
685 |
-
NodeList list = parent.getChildNodes();
|
686 |
-
if (list == null) {
|
687 |
-
return null;
|
688 |
-
}
|
689 |
-
Node node;
|
690 |
-
for (int i = 0; i < list.getLength(); i++) {
|
691 |
-
node = list.item(i);
|
692 |
-
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
|
693 |
-
if (childName.equalsIgnoreCase(node.getNodeName())) {
|
694 |
-
return (Element) node;
|
695 |
-
}
|
696 |
-
}
|
697 |
-
}
|
698 |
-
return null;
|
699 |
-
}
|
700 |
-
|
701 |
-
/**
|
702 |
-
* ������ȡ����ӽڵ�
|
703 |
-
* @param parent
|
704 |
-
* @param childName
|
705 |
-
* @return
|
706 |
-
*/
|
707 |
-
public static List<Element> getChildren(Node parent, String childName) {
|
708 |
-
NodeList list = parent.getChildNodes();
|
709 |
-
if (list == null) {
|
710 |
-
return null;
|
711 |
-
}
|
712 |
-
List<Element> childList = new ArrayList<Element>();
|
713 |
-
Node node;
|
714 |
-
for (int i = 0; i < list.getLength(); i++) {
|
715 |
-
node = list.item(i);
|
716 |
-
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
|
717 |
-
if (childName.equalsIgnoreCase(node.getNodeName())) {
|
718 |
-
childList.add((Element) node);
|
719 |
-
}
|
720 |
-
}
|
721 |
-
}
|
722 |
-
if (childList.isEmpty())
|
723 |
-
return null;
|
724 |
-
return childList;
|
725 |
-
}
|
726 |
-
|
727 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10003.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.ide.common;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.Writer;import java.util.ArrayList;import java.util.List;import java.util.Properties;import java.util.StringTokenizer;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.scudata.app.common.Section;import com.scudata.common.MessageManager;import com.scudata.ide.common.resources.IdeCommonMessage;/** * Used to parse xml files */public class XMLFile { /** * XML file path */ public String xmlFile = null; /** * XML Document */ private Document xmlDocument = null; /** * Common MessageManager */ private MessageManager mm = IdeCommonMessage.get(); /** * Constructor * * @param file * XML file path * @throws Exception */ public XMLFile(String file) throws Exception { this(new File(file), "root"); } /** * Constructor * * @param file * XML file path * @param root * Root node name * @throws Exception */ public XMLFile(File file, String root) throws Exception { if (file != null) { xmlFile = file.getAbsolutePath(); if (file.exists() && file.isFile()) { loadXMLFile(new FileInputStream(file)); } else { XMLFile.newXML(xmlFile, root); } } else { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: xmlDocument = docBuilder.newDocument(); Element eRoot = xmlDocument.createElement(root); eRoot.normalize(); xmlDocument.appendChild(eRoot); } } /** * Constructor * * @param is * File InputStream * @throws Exception */ public XMLFile(InputStream is) throws Exception { loadXMLFile(is); } /** * Load XML file from file input stream * * @param is * @throws Exception */ private void loadXMLFile(InputStream is) throws Exception { xmlDocument = parseXml(is); } /** * Create a new XML file * * @param file * The name of the file to be created. If the file exists, it * will overwrite the original one. * @param root * Root node name * @return Return true if the creation is successful, otherwise false. */ public static XMLFile newXML(String file, String root) throws Exception { if (!isLegalXmlName(root)) { throw new Exception(IdeCommonMessage.get().getMessage( "xmlfile.falseroot", file, root)); } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document sxmlDocument = docBuilder.newDocument(); Element eRoot = sxmlDocument.createElement(root); eRoot.normalize(); sxmlDocument.appendChild(eRoot); writeNodeToFile(sxmlDocument, file); return new XMLFile(file); } /** * List all sub-elements under the path path in the file file, including * elements and attributes. * * @param path * Node path, use / as a separator, for example: "a/b/c" * @return Return the section of the element and attribute under the path * node */ public Section listAll(String path) throws Exception { Section ss = new Section(); Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); ss.unionSection(getNodesName(tmpNode.getChildNodes())); ss.unionSection(getNodesName(tmpNode.getAttributes())); return ss; } /** * List all sub-elements under path in the file * * @param path * Node path * @return Return the section of the elements under the path node */ public Section listElement(String path) throws Exception { Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); return getNodesName(tmpNode.getChildNodes()); } /** * List all attributes under path in file * * @param path * Node path * @return Return the section of the attribute names under the path node */ public Section listAttribute(String path) throws Exception { Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); return getNodesName(tmpNode.getAttributes()); } /** * List the attribute value of the path node in the file * * @param path * Node path * @return The value of the attribute */ public String getAttribute(String path) { try { Node tmpNode = getTerminalNode(path, Node.ATTRIBUTE_NODE); return tmpNode.getNodeValue(); } catch (Exception ex) { return ""; } } /** * Create a new element under the current path * * @param path * Node path * @param element * The name of the element to be created * @return The node path after the new element is successfully created */ public String newElement(String path, String element) throws Exception { Element newElement = null; if (!isLegalXmlName(element)) { throw new Exception(mm.getMessage("xmlfile.falseelement", xmlFile, element)); } Node parent = getTerminalNode(path, Node.ELEMENT_NODE); NodeList nl = parent.getChildNodes(); int i; for (i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equalsIgnoreCase(element)) { break; } } if (i >= nl.getLength()) { newElement = xmlDocument.createElement(element); parent.appendChild(newElement); } return path + "/" + element; } /** * Create a new attribute under the current path * * @param path * Node path * @param attr * The name of the attribute to be created * @return Return 1 on success, -1 on failure (when the attribute with the * same name exists) */ public int newAttribute(String path, String attr) throws Exception { if (!isLegalXmlName(attr)) { throw new Exception(mm.getMessage("xmlfile.falseattr", xmlFile, attr)); } Node parent = getTerminalNode(path, Node.ELEMENT_NODE); NamedNodeMap nl = parent.getAttributes(); int i; for (i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equalsIgnoreCase(attr)) { break; } } if (i >= nl.getLength()) { ((Element) parent).setAttribute(attr, ""); } else { return -1; } return 1; } /** * Delete the node specified by path * * @param path * Node path */ public void delete(String path) throws Exception { deleteAttribute(path); deleteElement(path); } /** * Delete the element node specified by path * * @param path * Node path */ public void deleteElement(String path) throws Exception { Node nd = getTerminalNode(path, Node.ELEMENT_NODE); Node parent = nd.getParentNode(); parent.removeChild(nd); } /** * Whether the node path exists * * @param path * Node path * @return Exists when true, and does not exist when false. */ public boolean isPathExists(String path) { try { getTerminalNode(path, Node.ELEMENT_NODE); } catch (Exception ex) { return false; } return true; } /** * Delete the attribute node specified by path * * @param path * Node path */ public void deleteAttribute(String path) throws Exception { int i = path.lastIndexOf('/'); Node parent; if (i > 0) { String p = path.substring(0, i); parent = getTerminalNode(p, Node.ELEMENT_NODE); } else { return; } ((Element) parent).removeAttribute(path.substring(i + 1)); } /** * Change the name of the attribute node of the path * * @param path * Node path * @param newName * New name * @throws Exception */ public void renameAttribute(String path, String newName) throws Exception { int i; i = path.lastIndexOf('/'); if (i == -1) { throw new Exception(mm.getMessage("xmlfile.falsepath", xmlFile, path)); } String value = getAttribute(path); deleteAttribute(path); setAttribute(path.substring(0, i) + "/" + newName, value); } /** * Change the name of the element node of the path * * @param path * Node path * @param newName * New name * @throws Exception */ public void renameElement(String path, String newName) throws Exception { if (path.lastIndexOf('/') == -1) { throw new Exception(mm.getMessage("xmlfile.renameroot", xmlFile)); } Node nd = getTerminalNode(path, Node.ELEMENT_NODE); Node pp = nd.getParentNode(); NodeList childNodes = pp.getChildNodes(); int i; if (childNodes != null) { for (i = 0; i < childNodes.getLength(); i++) { if (newName.equalsIgnoreCase(childNodes.item(i).getNodeName())) { throw new Exception(mm.getMessage("xmlfile.existnode", xmlFile, newName)); } } } Element newNode = xmlDocument.createElement(newName); childNodes = nd.getChildNodes(); if (childNodes != null) { for (i = 0; i < childNodes.getLength(); i++) { newNode.appendChild(childNodes.item(i)); } } NamedNodeMap childAttr = nd.getAttributes(); Node tmpNode; if (childAttr != null) { for (i = 0; i < childAttr.getLength(); i++) { tmpNode = childAttr.item(i); newNode.setAttribute(tmpNode.getNodeName(), tmpNode.getNodeValue()); } } pp.replaceChild(newNode, nd); } /** * Set the attribute value of the attribute node of the path * * @param path * Node path * @param value * The attribute value to be set, null means delete the * attribute. */ public void setAttribute(String path, String value) throws Exception { if (path == null) { throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile)); } if (path.trim().length() == 0) { throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile)); } if (value == null) { deleteAttribute(path); return; } Node nd; int i = path.lastIndexOf('/'); if (i > 0) { String p = path.substring(0, i); String v = path.substring(i + 1); newAttribute(p, v); } nd = getTerminalNode(path, Node.ATTRIBUTE_NODE); nd.setNodeValue(value); } /** * Save XML file * * @throws Exception */ public void save() throws Exception { save(xmlFile); } /** * Save XML file * * @param file * XML file path * @throws Exception */ public void save(String file) throws Exception { writeNodeToFile(xmlDocument, file); } /** * Get the byte array of the XML file * * @return */ public byte[] getFileBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { outputDocument(xmlDocument, baos); } catch (Exception ex) { } return baos.toByteArray(); } /** * Save XML file * * @param os * File OutputStream * @throws Exception */ public void save(OutputStream os) throws Exception { outputDocument(xmlDocument, os); } /** * Write document to file * * @param node * Document * @param file * XML file path * @throws Exception */ public static void writeNodeToFile(Document node, String file) throws Exception { outputDocument(node, file); } /** * Output document * * @param node * Document * @param out * The object to output to. It can be: * String,OutputStream,Writer. * @throws Exception */ public static void outputDocument(Document node, Object out) throws Exception { StreamResult result; if (out instanceof String) { result = new StreamResult((String) out); } else if (out instanceof OutputStream) { result = new StreamResult((OutputStream) out); } else if (out instanceof Writer) { result = new StreamResult((Writer) out); } else { return; } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); Properties properties = transformer.getOutputProperties(); properties.setProperty(OutputKeys.ENCODING, "UTF-8"); properties.setProperty(OutputKeys.METHOD, "xml"); properties.setProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperties(properties); DOMSource source = new DOMSource(node); transformer.transform(source, result); } /** * Get the name Section of the nodes * * @param obj * @return * @throws Exception */ private Section getNodesName(Object obj) throws Exception { Section ss = new Section(); if (obj == null) { return ss; } Node nd = null; if (obj instanceof NodeList) { NodeList nl = (NodeList) obj; for (int i = 0; i < nl.getLength(); i++) { nd = nl.item(i); if (nd.getNodeType() != Node.ELEMENT_NODE) { continue; } ss.unionSection(nd.getNodeName()); } } if (obj instanceof NamedNodeMap) { NamedNodeMap nnm = (NamedNodeMap) obj; for (int i = 0; i < nnm.getLength(); i++) { nd = nnm.item(i); ss.unionSection(nd.getNodeName()); } } return ss; } /** * Locate node among nodes * * @param obj * NodeList or NamedNodeMap * @param nodeName * Node name * @return * @throws Exception */ private Node locateNode(Object obj, String nodeName) throws Exception { int i = 0, j = 0; String sTmp; Node tmpNode = null; NodeList nl; NamedNodeMap nnm; if (obj instanceof NodeList) { nl = (NodeList) obj; i = nl.getLength(); for (j = 0; j < i; j++) { tmpNode = nl.item(j); sTmp = tmpNode.getNodeName(); if (sTmp.equalsIgnoreCase(nodeName)) { break; } } } if (obj instanceof NamedNodeMap) { nnm = (NamedNodeMap) obj; i = nnm.getLength(); for (j = 0; j < i; j++) { tmpNode = nnm.item(j); sTmp = tmpNode.getNodeName(); if (sTmp.equalsIgnoreCase(nodeName)) { break; } } } if (j == i) { throw new Exception(mm.getMessage("xmlfile.falsenodename", xmlFile, nodeName)); } return tmpNode; } /** * Get terminal node * * @param path * Node path * @param type * Constants defined in org.w3c.dom.Node * @return * @throws Exception */ private Node getTerminalNode(String path, short type) throws Exception { Node tmpNode = null; String sNode, sLast; int i; if (path == null) { throw new Exception(mm.getMessage("xmlfile.nullpath1", xmlFile)); } i = path.lastIndexOf('/'); if (i == -1) { if (path.length() == 0) { return xmlDocument; } sNode = path; if (type == Node.ELEMENT_NODE) { tmpNode = locateNode(xmlDocument.getChildNodes(), sNode); } } else { sLast = path.substring(i + 1); path = path.substring(0, i); StringTokenizer st = new StringTokenizer(path, "/"); NodeList childNodes = xmlDocument.getChildNodes(); while (st.hasMoreTokens()) { sNode = st.nextToken(); tmpNode = locateNode(childNodes, sNode); if (tmpNode == null) { throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile, path)); } childNodes = tmpNode.getChildNodes(); } if (type == Node.ELEMENT_NODE) { tmpNode = locateNode(tmpNode.getChildNodes(), sLast); } else { tmpNode = locateNode(tmpNode.getAttributes(), sLast); } } if (tmpNode == null) { throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile, path)); } return tmpNode; } /** * Is the legal XML name * * @param input * Node name * @return */ public static boolean isLegalXmlName(String input) { if (input == null || input.length() == 0) { return false; } return true; } /** * ����XML * @param is * @return * @throws Exception */ public static Document parseXml(InputStream is) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); return docBuilder.parse(is); } /** * ������ȡ�ӽڵ� * @param parent * @param childName * @return */ public static Element getChild(Node parent, String childName) { NodeList list = parent.getChildNodes(); if (list == null) { return null; } Node node; for (int i = 0; i < list.getLength(); i++) { node = list.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { if (childName.equalsIgnoreCase(node.getNodeName())) { return (Element) node; } } } return null; } /** * ������ȡ����ӽڵ� * @param parent * @param childName * @return */ public static List<Element> getChildren(Node parent, String childName) { NodeList list = parent.getChildNodes(); if (list == null) { return null; } List<Element> childList = new ArrayList<Element>(); Node node; for (int i = 0; i < list.getLength(); i++) { node = list.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { if (childName.equalsIgnoreCase(node.getNodeName())) { childList.add((Element) node); } } } if (childList.isEmpty()) return null; return childList; }}
|
data/java/10004.java
DELETED
@@ -1,727 +0,0 @@
|
|
1 |
-
package com.scudata.ide.common;
|
2 |
-
|
3 |
-
import java.io.ByteArrayOutputStream;
|
4 |
-
import java.io.File;
|
5 |
-
import java.io.FileInputStream;
|
6 |
-
import java.io.InputStream;
|
7 |
-
import java.io.OutputStream;
|
8 |
-
import java.io.Writer;
|
9 |
-
import java.util.ArrayList;
|
10 |
-
import java.util.List;
|
11 |
-
import java.util.Properties;
|
12 |
-
import java.util.StringTokenizer;
|
13 |
-
|
14 |
-
import javax.xml.parsers.DocumentBuilder;
|
15 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
16 |
-
import javax.xml.transform.OutputKeys;
|
17 |
-
import javax.xml.transform.Transformer;
|
18 |
-
import javax.xml.transform.TransformerFactory;
|
19 |
-
import javax.xml.transform.dom.DOMSource;
|
20 |
-
import javax.xml.transform.stream.StreamResult;
|
21 |
-
|
22 |
-
import org.w3c.dom.Document;
|
23 |
-
import org.w3c.dom.Element;
|
24 |
-
import org.w3c.dom.NamedNodeMap;
|
25 |
-
import org.w3c.dom.Node;
|
26 |
-
import org.w3c.dom.NodeList;
|
27 |
-
|
28 |
-
import com.scudata.app.common.Section;
|
29 |
-
import com.scudata.common.MessageManager;
|
30 |
-
import com.scudata.ide.common.resources.IdeCommonMessage;
|
31 |
-
|
32 |
-
/**
|
33 |
-
* Used to parse xml files
|
34 |
-
*/
|
35 |
-
public class XMLFile {
|
36 |
-
|
37 |
-
/**
|
38 |
-
* XML file path
|
39 |
-
*/
|
40 |
-
public String xmlFile = null;
|
41 |
-
|
42 |
-
/**
|
43 |
-
* XML Document
|
44 |
-
*/
|
45 |
-
private Document xmlDocument = null;
|
46 |
-
|
47 |
-
/**
|
48 |
-
* Common MessageManager
|
49 |
-
*/
|
50 |
-
private MessageManager mm = IdeCommonMessage.get();
|
51 |
-
|
52 |
-
/**
|
53 |
-
* Constructor
|
54 |
-
*
|
55 |
-
* @param file
|
56 |
-
* XML file path
|
57 |
-
* @throws Exception
|
58 |
-
*/
|
59 |
-
public XMLFile(String file) throws Exception {
|
60 |
-
this(new File(file), "root");
|
61 |
-
}
|
62 |
-
|
63 |
-
/**
|
64 |
-
* Constructor
|
65 |
-
*
|
66 |
-
* @param file
|
67 |
-
* XML file path
|
68 |
-
* @param root
|
69 |
-
* Root node name
|
70 |
-
* @throws Exception
|
71 |
-
*/
|
72 |
-
public XMLFile(File file, String root) throws Exception {
|
73 |
-
if (file != null) {
|
74 |
-
xmlFile = file.getAbsolutePath();
|
75 |
-
if (file.exists() && file.isFile()) {
|
76 |
-
loadXMLFile(new FileInputStream(file));
|
77 |
-
} else {
|
78 |
-
XMLFile.newXML(xmlFile, root);
|
79 |
-
}
|
80 |
-
} else {
|
81 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
82 |
-
.newInstance();
|
83 |
-
|
84 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
85 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
86 |
-
// FIXED:
|
87 |
-
|
88 |
-
xmlDocument = docBuilder.newDocument();
|
89 |
-
Element eRoot = xmlDocument.createElement(root);
|
90 |
-
eRoot.normalize();
|
91 |
-
xmlDocument.appendChild(eRoot);
|
92 |
-
}
|
93 |
-
}
|
94 |
-
|
95 |
-
/**
|
96 |
-
* Constructor
|
97 |
-
*
|
98 |
-
* @param is
|
99 |
-
* File InputStream
|
100 |
-
* @throws Exception
|
101 |
-
*/
|
102 |
-
public XMLFile(InputStream is) throws Exception {
|
103 |
-
loadXMLFile(is);
|
104 |
-
}
|
105 |
-
|
106 |
-
/**
|
107 |
-
* Load XML file from file input stream
|
108 |
-
*
|
109 |
-
* @param is
|
110 |
-
* @throws Exception
|
111 |
-
*/
|
112 |
-
private void loadXMLFile(InputStream is) throws Exception {
|
113 |
-
xmlDocument = parseXml(is);
|
114 |
-
}
|
115 |
-
|
116 |
-
/**
|
117 |
-
* Create a new XML file
|
118 |
-
*
|
119 |
-
* @param file
|
120 |
-
* The name of the file to be created. If the file exists, it
|
121 |
-
* will overwrite the original one.
|
122 |
-
* @param root
|
123 |
-
* Root node name
|
124 |
-
* @return Return true if the creation is successful, otherwise false.
|
125 |
-
*/
|
126 |
-
public static XMLFile newXML(String file, String root) throws Exception {
|
127 |
-
if (!isLegalXmlName(root)) {
|
128 |
-
throw new Exception(IdeCommonMessage.get().getMessage(
|
129 |
-
"xmlfile.falseroot", file, root));
|
130 |
-
}
|
131 |
-
|
132 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
133 |
-
.newInstance();
|
134 |
-
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
135 |
-
Document sxmlDocument = docBuilder.newDocument();
|
136 |
-
Element eRoot = sxmlDocument.createElement(root);
|
137 |
-
eRoot.normalize();
|
138 |
-
sxmlDocument.appendChild(eRoot);
|
139 |
-
|
140 |
-
writeNodeToFile(sxmlDocument, file);
|
141 |
-
return new XMLFile(file);
|
142 |
-
}
|
143 |
-
|
144 |
-
/**
|
145 |
-
* List all sub-elements under the path path in the file file, including
|
146 |
-
* elements and attributes.
|
147 |
-
*
|
148 |
-
* @param path
|
149 |
-
* Node path, use / as a separator, for example: "a/b/c"
|
150 |
-
* @return Return the section of the element and attribute under the path
|
151 |
-
* node
|
152 |
-
*/
|
153 |
-
public Section listAll(String path) throws Exception {
|
154 |
-
Section ss = new Section();
|
155 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
156 |
-
ss.unionSection(getNodesName(tmpNode.getChildNodes()));
|
157 |
-
ss.unionSection(getNodesName(tmpNode.getAttributes()));
|
158 |
-
return ss;
|
159 |
-
}
|
160 |
-
|
161 |
-
/**
|
162 |
-
* List all sub-elements under path in the file
|
163 |
-
*
|
164 |
-
* @param path
|
165 |
-
* Node path
|
166 |
-
* @return Return the section of the elements under the path node
|
167 |
-
*/
|
168 |
-
public Section listElement(String path) throws Exception {
|
169 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
170 |
-
return getNodesName(tmpNode.getChildNodes());
|
171 |
-
}
|
172 |
-
|
173 |
-
/**
|
174 |
-
* List all attributes under path in file
|
175 |
-
*
|
176 |
-
* @param path
|
177 |
-
* Node path
|
178 |
-
* @return Return the section of the attribute names under the path node
|
179 |
-
*/
|
180 |
-
public Section listAttribute(String path) throws Exception {
|
181 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
182 |
-
return getNodesName(tmpNode.getAttributes());
|
183 |
-
}
|
184 |
-
|
185 |
-
/**
|
186 |
-
* List the attribute value of the path node in the file
|
187 |
-
*
|
188 |
-
* @param path
|
189 |
-
* Node path
|
190 |
-
* @return The value of the attribute
|
191 |
-
*/
|
192 |
-
public String getAttribute(String path) {
|
193 |
-
try {
|
194 |
-
Node tmpNode = getTerminalNode(path, Node.ATTRIBUTE_NODE);
|
195 |
-
return tmpNode.getNodeValue();
|
196 |
-
} catch (Exception ex) {
|
197 |
-
return "";
|
198 |
-
}
|
199 |
-
}
|
200 |
-
|
201 |
-
/**
|
202 |
-
* Create a new element under the current path
|
203 |
-
*
|
204 |
-
* @param path
|
205 |
-
* Node path
|
206 |
-
* @param element
|
207 |
-
* The name of the element to be created
|
208 |
-
* @return The node path after the new element is successfully created
|
209 |
-
*/
|
210 |
-
public String newElement(String path, String element) throws Exception {
|
211 |
-
Element newElement = null;
|
212 |
-
if (!isLegalXmlName(element)) {
|
213 |
-
throw new Exception(mm.getMessage("xmlfile.falseelement", xmlFile,
|
214 |
-
element));
|
215 |
-
}
|
216 |
-
|
217 |
-
Node parent = getTerminalNode(path, Node.ELEMENT_NODE);
|
218 |
-
NodeList nl = parent.getChildNodes();
|
219 |
-
int i;
|
220 |
-
for (i = 0; i < nl.getLength(); i++) {
|
221 |
-
if (nl.item(i).getNodeName().equalsIgnoreCase(element)) {
|
222 |
-
break;
|
223 |
-
}
|
224 |
-
}
|
225 |
-
if (i >= nl.getLength()) {
|
226 |
-
newElement = xmlDocument.createElement(element);
|
227 |
-
parent.appendChild(newElement);
|
228 |
-
}
|
229 |
-
return path + "/" + element;
|
230 |
-
}
|
231 |
-
|
232 |
-
/**
|
233 |
-
* Create a new attribute under the current path
|
234 |
-
*
|
235 |
-
* @param path
|
236 |
-
* Node path
|
237 |
-
* @param attr
|
238 |
-
* The name of the attribute to be created
|
239 |
-
* @return Return 1 on success, -1 on failure (when the attribute with the
|
240 |
-
* same name exists)
|
241 |
-
*/
|
242 |
-
public int newAttribute(String path, String attr) throws Exception {
|
243 |
-
if (!isLegalXmlName(attr)) {
|
244 |
-
throw new Exception(mm.getMessage("xmlfile.falseattr", xmlFile,
|
245 |
-
attr));
|
246 |
-
}
|
247 |
-
|
248 |
-
Node parent = getTerminalNode(path, Node.ELEMENT_NODE);
|
249 |
-
|
250 |
-
NamedNodeMap nl = parent.getAttributes();
|
251 |
-
int i;
|
252 |
-
for (i = 0; i < nl.getLength(); i++) {
|
253 |
-
if (nl.item(i).getNodeName().equalsIgnoreCase(attr)) {
|
254 |
-
break;
|
255 |
-
}
|
256 |
-
}
|
257 |
-
if (i >= nl.getLength()) {
|
258 |
-
((Element) parent).setAttribute(attr, "");
|
259 |
-
} else {
|
260 |
-
return -1;
|
261 |
-
}
|
262 |
-
return 1;
|
263 |
-
}
|
264 |
-
|
265 |
-
/**
|
266 |
-
* Delete the node specified by path
|
267 |
-
*
|
268 |
-
* @param path
|
269 |
-
* Node path
|
270 |
-
*/
|
271 |
-
public void delete(String path) throws Exception {
|
272 |
-
deleteAttribute(path);
|
273 |
-
deleteElement(path);
|
274 |
-
}
|
275 |
-
|
276 |
-
/**
|
277 |
-
* Delete the element node specified by path
|
278 |
-
*
|
279 |
-
* @param path
|
280 |
-
* Node path
|
281 |
-
*/
|
282 |
-
public void deleteElement(String path) throws Exception {
|
283 |
-
Node nd = getTerminalNode(path, Node.ELEMENT_NODE);
|
284 |
-
Node parent = nd.getParentNode();
|
285 |
-
parent.removeChild(nd);
|
286 |
-
}
|
287 |
-
|
288 |
-
/**
|
289 |
-
* Whether the node path exists
|
290 |
-
*
|
291 |
-
* @param path
|
292 |
-
* Node path
|
293 |
-
* @return Exists when true, and does not exist when false.
|
294 |
-
*/
|
295 |
-
public boolean isPathExists(String path) {
|
296 |
-
try {
|
297 |
-
getTerminalNode(path, Node.ELEMENT_NODE);
|
298 |
-
} catch (Exception ex) {
|
299 |
-
return false;
|
300 |
-
}
|
301 |
-
return true;
|
302 |
-
}
|
303 |
-
|
304 |
-
/**
|
305 |
-
* Delete the attribute node specified by path
|
306 |
-
*
|
307 |
-
* @param path
|
308 |
-
* Node path
|
309 |
-
*/
|
310 |
-
public void deleteAttribute(String path) throws Exception {
|
311 |
-
int i = path.lastIndexOf('/');
|
312 |
-
Node parent;
|
313 |
-
if (i > 0) {
|
314 |
-
String p = path.substring(0, i);
|
315 |
-
parent = getTerminalNode(p, Node.ELEMENT_NODE);
|
316 |
-
} else {
|
317 |
-
return;
|
318 |
-
}
|
319 |
-
((Element) parent).removeAttribute(path.substring(i + 1));
|
320 |
-
}
|
321 |
-
|
322 |
-
/**
|
323 |
-
* Change the name of the attribute node of the path
|
324 |
-
*
|
325 |
-
* @param path
|
326 |
-
* Node path
|
327 |
-
* @param newName
|
328 |
-
* New name
|
329 |
-
* @throws Exception
|
330 |
-
*/
|
331 |
-
public void renameAttribute(String path, String newName) throws Exception {
|
332 |
-
int i;
|
333 |
-
i = path.lastIndexOf('/');
|
334 |
-
if (i == -1) {
|
335 |
-
throw new Exception(mm.getMessage("xmlfile.falsepath", xmlFile,
|
336 |
-
path));
|
337 |
-
}
|
338 |
-
|
339 |
-
String value = getAttribute(path);
|
340 |
-
deleteAttribute(path);
|
341 |
-
setAttribute(path.substring(0, i) + "/" + newName, value);
|
342 |
-
}
|
343 |
-
|
344 |
-
/**
|
345 |
-
* Change the name of the element node of the path
|
346 |
-
*
|
347 |
-
* @param path
|
348 |
-
* Node path
|
349 |
-
* @param newName
|
350 |
-
* New name
|
351 |
-
* @throws Exception
|
352 |
-
*/
|
353 |
-
public void renameElement(String path, String newName) throws Exception {
|
354 |
-
if (path.lastIndexOf('/') == -1) {
|
355 |
-
throw new Exception(mm.getMessage("xmlfile.renameroot", xmlFile));
|
356 |
-
}
|
357 |
-
Node nd = getTerminalNode(path, Node.ELEMENT_NODE);
|
358 |
-
Node pp = nd.getParentNode();
|
359 |
-
NodeList childNodes = pp.getChildNodes();
|
360 |
-
int i;
|
361 |
-
if (childNodes != null) {
|
362 |
-
for (i = 0; i < childNodes.getLength(); i++) {
|
363 |
-
if (newName.equalsIgnoreCase(childNodes.item(i).getNodeName())) {
|
364 |
-
throw new Exception(mm.getMessage("xmlfile.existnode",
|
365 |
-
xmlFile, newName));
|
366 |
-
}
|
367 |
-
}
|
368 |
-
}
|
369 |
-
|
370 |
-
Element newNode = xmlDocument.createElement(newName);
|
371 |
-
|
372 |
-
childNodes = nd.getChildNodes();
|
373 |
-
if (childNodes != null) {
|
374 |
-
for (i = 0; i < childNodes.getLength(); i++) {
|
375 |
-
newNode.appendChild(childNodes.item(i));
|
376 |
-
}
|
377 |
-
}
|
378 |
-
NamedNodeMap childAttr = nd.getAttributes();
|
379 |
-
Node tmpNode;
|
380 |
-
if (childAttr != null) {
|
381 |
-
for (i = 0; i < childAttr.getLength(); i++) {
|
382 |
-
tmpNode = childAttr.item(i);
|
383 |
-
newNode.setAttribute(tmpNode.getNodeName(),
|
384 |
-
tmpNode.getNodeValue());
|
385 |
-
}
|
386 |
-
}
|
387 |
-
pp.replaceChild(newNode, nd);
|
388 |
-
}
|
389 |
-
|
390 |
-
/**
|
391 |
-
* Set the attribute value of the attribute node of the path
|
392 |
-
*
|
393 |
-
* @param path
|
394 |
-
* Node path
|
395 |
-
* @param value
|
396 |
-
* The attribute value to be set, null means delete the
|
397 |
-
* attribute.
|
398 |
-
*/
|
399 |
-
public void setAttribute(String path, String value) throws Exception {
|
400 |
-
if (path == null) {
|
401 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile));
|
402 |
-
}
|
403 |
-
if (path.trim().length() == 0) {
|
404 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile));
|
405 |
-
}
|
406 |
-
if (value == null) {
|
407 |
-
deleteAttribute(path);
|
408 |
-
return;
|
409 |
-
}
|
410 |
-
Node nd;
|
411 |
-
int i = path.lastIndexOf('/');
|
412 |
-
if (i > 0) {
|
413 |
-
String p = path.substring(0, i);
|
414 |
-
String v = path.substring(i + 1);
|
415 |
-
newAttribute(p, v);
|
416 |
-
}
|
417 |
-
|
418 |
-
nd = getTerminalNode(path, Node.ATTRIBUTE_NODE);
|
419 |
-
nd.setNodeValue(value);
|
420 |
-
}
|
421 |
-
|
422 |
-
/**
|
423 |
-
* Save XML file
|
424 |
-
*
|
425 |
-
* @throws Exception
|
426 |
-
*/
|
427 |
-
public void save() throws Exception {
|
428 |
-
save(xmlFile);
|
429 |
-
}
|
430 |
-
|
431 |
-
/**
|
432 |
-
* Save XML file
|
433 |
-
*
|
434 |
-
* @param file
|
435 |
-
* XML file path
|
436 |
-
* @throws Exception
|
437 |
-
*/
|
438 |
-
public void save(String file) throws Exception {
|
439 |
-
writeNodeToFile(xmlDocument, file);
|
440 |
-
}
|
441 |
-
|
442 |
-
/**
|
443 |
-
* Get the byte array of the XML file
|
444 |
-
*
|
445 |
-
* @return
|
446 |
-
*/
|
447 |
-
public byte[] getFileBytes() {
|
448 |
-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
449 |
-
try {
|
450 |
-
outputDocument(xmlDocument, baos);
|
451 |
-
} catch (Exception ex) {
|
452 |
-
}
|
453 |
-
return baos.toByteArray();
|
454 |
-
}
|
455 |
-
|
456 |
-
/**
|
457 |
-
* Save XML file
|
458 |
-
*
|
459 |
-
* @param os
|
460 |
-
* File OutputStream
|
461 |
-
* @throws Exception
|
462 |
-
*/
|
463 |
-
public void save(OutputStream os) throws Exception {
|
464 |
-
outputDocument(xmlDocument, os);
|
465 |
-
}
|
466 |
-
|
467 |
-
/**
|
468 |
-
* Write document to file
|
469 |
-
*
|
470 |
-
* @param node
|
471 |
-
* Document
|
472 |
-
* @param file
|
473 |
-
* XML file path
|
474 |
-
* @throws Exception
|
475 |
-
*/
|
476 |
-
public static void writeNodeToFile(Document node, String file)
|
477 |
-
throws Exception {
|
478 |
-
outputDocument(node, file);
|
479 |
-
}
|
480 |
-
|
481 |
-
/**
|
482 |
-
* Output document
|
483 |
-
*
|
484 |
-
* @param node
|
485 |
-
* Document
|
486 |
-
* @param out
|
487 |
-
* The object to output to. It can be:
|
488 |
-
* String,OutputStream,Writer.
|
489 |
-
* @throws Exception
|
490 |
-
*/
|
491 |
-
public static void outputDocument(Document node, Object out)
|
492 |
-
throws Exception {
|
493 |
-
StreamResult result;
|
494 |
-
if (out instanceof String) {
|
495 |
-
result = new StreamResult((String) out);
|
496 |
-
} else if (out instanceof OutputStream) {
|
497 |
-
result = new StreamResult((OutputStream) out);
|
498 |
-
} else if (out instanceof Writer) {
|
499 |
-
result = new StreamResult((Writer) out);
|
500 |
-
} else {
|
501 |
-
return;
|
502 |
-
}
|
503 |
-
TransformerFactory tFactory = TransformerFactory.newInstance();
|
504 |
-
Transformer transformer = tFactory.newTransformer();
|
505 |
-
|
506 |
-
Properties properties = transformer.getOutputProperties();
|
507 |
-
properties.setProperty(OutputKeys.ENCODING, "UTF-8");
|
508 |
-
properties.setProperty(OutputKeys.METHOD, "xml");
|
509 |
-
properties.setProperty(OutputKeys.INDENT, "yes");
|
510 |
-
transformer.setOutputProperties(properties);
|
511 |
-
|
512 |
-
DOMSource source = new DOMSource(node);
|
513 |
-
transformer.transform(source, result);
|
514 |
-
}
|
515 |
-
|
516 |
-
/**
|
517 |
-
* Get the name Section of the nodes
|
518 |
-
*
|
519 |
-
* @param obj
|
520 |
-
* @return
|
521 |
-
* @throws Exception
|
522 |
-
*/
|
523 |
-
private Section getNodesName(Object obj) throws Exception {
|
524 |
-
Section ss = new Section();
|
525 |
-
if (obj == null) {
|
526 |
-
return ss;
|
527 |
-
}
|
528 |
-
|
529 |
-
Node nd = null;
|
530 |
-
if (obj instanceof NodeList) {
|
531 |
-
NodeList nl = (NodeList) obj;
|
532 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
533 |
-
nd = nl.item(i);
|
534 |
-
if (nd.getNodeType() != Node.ELEMENT_NODE) {
|
535 |
-
continue;
|
536 |
-
}
|
537 |
-
ss.unionSection(nd.getNodeName());
|
538 |
-
}
|
539 |
-
}
|
540 |
-
|
541 |
-
if (obj instanceof NamedNodeMap) {
|
542 |
-
NamedNodeMap nnm = (NamedNodeMap) obj;
|
543 |
-
for (int i = 0; i < nnm.getLength(); i++) {
|
544 |
-
nd = nnm.item(i);
|
545 |
-
ss.unionSection(nd.getNodeName());
|
546 |
-
}
|
547 |
-
}
|
548 |
-
return ss;
|
549 |
-
}
|
550 |
-
|
551 |
-
/**
|
552 |
-
* Locate node among nodes
|
553 |
-
*
|
554 |
-
* @param obj
|
555 |
-
* NodeList or NamedNodeMap
|
556 |
-
* @param nodeName
|
557 |
-
* Node name
|
558 |
-
* @return
|
559 |
-
* @throws Exception
|
560 |
-
*/
|
561 |
-
private Node locateNode(Object obj, String nodeName) throws Exception {
|
562 |
-
int i = 0, j = 0;
|
563 |
-
String sTmp;
|
564 |
-
Node tmpNode = null;
|
565 |
-
NodeList nl;
|
566 |
-
NamedNodeMap nnm;
|
567 |
-
|
568 |
-
if (obj instanceof NodeList) {
|
569 |
-
nl = (NodeList) obj;
|
570 |
-
i = nl.getLength();
|
571 |
-
for (j = 0; j < i; j++) {
|
572 |
-
tmpNode = nl.item(j);
|
573 |
-
sTmp = tmpNode.getNodeName();
|
574 |
-
if (sTmp.equalsIgnoreCase(nodeName)) {
|
575 |
-
break;
|
576 |
-
}
|
577 |
-
}
|
578 |
-
}
|
579 |
-
if (obj instanceof NamedNodeMap) {
|
580 |
-
nnm = (NamedNodeMap) obj;
|
581 |
-
i = nnm.getLength();
|
582 |
-
for (j = 0; j < i; j++) {
|
583 |
-
tmpNode = nnm.item(j);
|
584 |
-
sTmp = tmpNode.getNodeName();
|
585 |
-
if (sTmp.equalsIgnoreCase(nodeName)) {
|
586 |
-
break;
|
587 |
-
}
|
588 |
-
}
|
589 |
-
}
|
590 |
-
if (j == i) {
|
591 |
-
throw new Exception(mm.getMessage("xmlfile.falsenodename", xmlFile,
|
592 |
-
nodeName));
|
593 |
-
}
|
594 |
-
return tmpNode;
|
595 |
-
}
|
596 |
-
|
597 |
-
/**
|
598 |
-
* Get terminal node
|
599 |
-
*
|
600 |
-
* @param path
|
601 |
-
* Node path
|
602 |
-
* @param type
|
603 |
-
* Constants defined in org.w3c.dom.Node
|
604 |
-
* @return
|
605 |
-
* @throws Exception
|
606 |
-
*/
|
607 |
-
private Node getTerminalNode(String path, short type) throws Exception {
|
608 |
-
Node tmpNode = null;
|
609 |
-
String sNode, sLast;
|
610 |
-
int i;
|
611 |
-
if (path == null) {
|
612 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath1", xmlFile));
|
613 |
-
}
|
614 |
-
i = path.lastIndexOf('/');
|
615 |
-
if (i == -1) {
|
616 |
-
if (path.length() == 0) {
|
617 |
-
return xmlDocument;
|
618 |
-
}
|
619 |
-
sNode = path;
|
620 |
-
if (type == Node.ELEMENT_NODE) {
|
621 |
-
tmpNode = locateNode(xmlDocument.getChildNodes(), sNode);
|
622 |
-
}
|
623 |
-
} else {
|
624 |
-
sLast = path.substring(i + 1);
|
625 |
-
path = path.substring(0, i);
|
626 |
-
|
627 |
-
StringTokenizer st = new StringTokenizer(path, "/");
|
628 |
-
NodeList childNodes = xmlDocument.getChildNodes();
|
629 |
-
while (st.hasMoreTokens()) {
|
630 |
-
sNode = st.nextToken();
|
631 |
-
tmpNode = locateNode(childNodes, sNode);
|
632 |
-
if (tmpNode == null) {
|
633 |
-
throw new Exception(mm.getMessage("xmlfile.notexistpath",
|
634 |
-
xmlFile, path));
|
635 |
-
}
|
636 |
-
childNodes = tmpNode.getChildNodes();
|
637 |
-
}
|
638 |
-
if (type == Node.ELEMENT_NODE) {
|
639 |
-
tmpNode = locateNode(tmpNode.getChildNodes(), sLast);
|
640 |
-
} else {
|
641 |
-
tmpNode = locateNode(tmpNode.getAttributes(), sLast);
|
642 |
-
}
|
643 |
-
}
|
644 |
-
if (tmpNode == null) {
|
645 |
-
throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile,
|
646 |
-
path));
|
647 |
-
}
|
648 |
-
return tmpNode;
|
649 |
-
}
|
650 |
-
|
651 |
-
/**
|
652 |
-
* Is the legal XML name
|
653 |
-
*
|
654 |
-
* @param input
|
655 |
-
* Node name
|
656 |
-
* @return
|
657 |
-
*/
|
658 |
-
public static boolean isLegalXmlName(String input) {
|
659 |
-
if (input == null || input.length() == 0) {
|
660 |
-
return false;
|
661 |
-
}
|
662 |
-
return true;
|
663 |
-
}
|
664 |
-
|
665 |
-
/**
|
666 |
-
* ����XML
|
667 |
-
* @param is
|
668 |
-
* @return
|
669 |
-
* @throws Exception
|
670 |
-
*/
|
671 |
-
public static Document parseXml(InputStream is) throws Exception {
|
672 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
673 |
-
.newInstance();
|
674 |
-
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
675 |
-
return docBuilder.parse(is);
|
676 |
-
}
|
677 |
-
|
678 |
-
/**
|
679 |
-
* ������ȡ�ӽڵ�
|
680 |
-
* @param parent
|
681 |
-
* @param childName
|
682 |
-
* @return
|
683 |
-
*/
|
684 |
-
public static Element getChild(Node parent, String childName) {
|
685 |
-
NodeList list = parent.getChildNodes();
|
686 |
-
if (list == null) {
|
687 |
-
return null;
|
688 |
-
}
|
689 |
-
Node node;
|
690 |
-
for (int i = 0; i < list.getLength(); i++) {
|
691 |
-
node = list.item(i);
|
692 |
-
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
|
693 |
-
if (childName.equalsIgnoreCase(node.getNodeName())) {
|
694 |
-
return (Element) node;
|
695 |
-
}
|
696 |
-
}
|
697 |
-
}
|
698 |
-
return null;
|
699 |
-
}
|
700 |
-
|
701 |
-
/**
|
702 |
-
* ������ȡ����ӽڵ�
|
703 |
-
* @param parent
|
704 |
-
* @param childName
|
705 |
-
* @return
|
706 |
-
*/
|
707 |
-
public static List<Element> getChildren(Node parent, String childName) {
|
708 |
-
NodeList list = parent.getChildNodes();
|
709 |
-
if (list == null) {
|
710 |
-
return null;
|
711 |
-
}
|
712 |
-
List<Element> childList = new ArrayList<Element>();
|
713 |
-
Node node;
|
714 |
-
for (int i = 0; i < list.getLength(); i++) {
|
715 |
-
node = list.item(i);
|
716 |
-
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
|
717 |
-
if (childName.equalsIgnoreCase(node.getNodeName())) {
|
718 |
-
childList.add((Element) node);
|
719 |
-
}
|
720 |
-
}
|
721 |
-
}
|
722 |
-
if (childList.isEmpty())
|
723 |
-
return null;
|
724 |
-
return childList;
|
725 |
-
}
|
726 |
-
|
727 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10004.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.ide.common;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.Writer;import java.util.ArrayList;import java.util.List;import java.util.Properties;import java.util.StringTokenizer;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.scudata.app.common.Section;import com.scudata.common.MessageManager;import com.scudata.ide.common.resources.IdeCommonMessage;/** * Used to parse xml files */public class XMLFile { /** * XML file path */ public String xmlFile = null; /** * XML Document */ private Document xmlDocument = null; /** * Common MessageManager */ private MessageManager mm = IdeCommonMessage.get(); /** * Constructor * * @param file * XML file path * @throws Exception */ public XMLFile(String file) throws Exception { this(new File(file), "root"); } /** * Constructor * * @param file * XML file path * @param root * Root node name * @throws Exception */ public XMLFile(File file, String root) throws Exception { if (file != null) { xmlFile = file.getAbsolutePath(); if (file.exists() && file.isFile()) { loadXMLFile(new FileInputStream(file)); } else { XMLFile.newXML(xmlFile, root); } } else { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: xmlDocument = docBuilder.newDocument(); Element eRoot = xmlDocument.createElement(root); eRoot.normalize(); xmlDocument.appendChild(eRoot); } } /** * Constructor * * @param is * File InputStream * @throws Exception */ public XMLFile(InputStream is) throws Exception { loadXMLFile(is); } /** * Load XML file from file input stream * * @param is * @throws Exception */ private void loadXMLFile(InputStream is) throws Exception { xmlDocument = parseXml(is); } /** * Create a new XML file * * @param file * The name of the file to be created. If the file exists, it * will overwrite the original one. * @param root * Root node name * @return Return true if the creation is successful, otherwise false. */ public static XMLFile newXML(String file, String root) throws Exception { if (!isLegalXmlName(root)) { throw new Exception(IdeCommonMessage.get().getMessage( "xmlfile.falseroot", file, root)); } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document sxmlDocument = docBuilder.newDocument(); Element eRoot = sxmlDocument.createElement(root); eRoot.normalize(); sxmlDocument.appendChild(eRoot); writeNodeToFile(sxmlDocument, file); return new XMLFile(file); } /** * List all sub-elements under the path path in the file file, including * elements and attributes. * * @param path * Node path, use / as a separator, for example: "a/b/c" * @return Return the section of the element and attribute under the path * node */ public Section listAll(String path) throws Exception { Section ss = new Section(); Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); ss.unionSection(getNodesName(tmpNode.getChildNodes())); ss.unionSection(getNodesName(tmpNode.getAttributes())); return ss; } /** * List all sub-elements under path in the file * * @param path * Node path * @return Return the section of the elements under the path node */ public Section listElement(String path) throws Exception { Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); return getNodesName(tmpNode.getChildNodes()); } /** * List all attributes under path in file * * @param path * Node path * @return Return the section of the attribute names under the path node */ public Section listAttribute(String path) throws Exception { Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); return getNodesName(tmpNode.getAttributes()); } /** * List the attribute value of the path node in the file * * @param path * Node path * @return The value of the attribute */ public String getAttribute(String path) { try { Node tmpNode = getTerminalNode(path, Node.ATTRIBUTE_NODE); return tmpNode.getNodeValue(); } catch (Exception ex) { return ""; } } /** * Create a new element under the current path * * @param path * Node path * @param element * The name of the element to be created * @return The node path after the new element is successfully created */ public String newElement(String path, String element) throws Exception { Element newElement = null; if (!isLegalXmlName(element)) { throw new Exception(mm.getMessage("xmlfile.falseelement", xmlFile, element)); } Node parent = getTerminalNode(path, Node.ELEMENT_NODE); NodeList nl = parent.getChildNodes(); int i; for (i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equalsIgnoreCase(element)) { break; } } if (i >= nl.getLength()) { newElement = xmlDocument.createElement(element); parent.appendChild(newElement); } return path + "/" + element; } /** * Create a new attribute under the current path * * @param path * Node path * @param attr * The name of the attribute to be created * @return Return 1 on success, -1 on failure (when the attribute with the * same name exists) */ public int newAttribute(String path, String attr) throws Exception { if (!isLegalXmlName(attr)) { throw new Exception(mm.getMessage("xmlfile.falseattr", xmlFile, attr)); } Node parent = getTerminalNode(path, Node.ELEMENT_NODE); NamedNodeMap nl = parent.getAttributes(); int i; for (i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equalsIgnoreCase(attr)) { break; } } if (i >= nl.getLength()) { ((Element) parent).setAttribute(attr, ""); } else { return -1; } return 1; } /** * Delete the node specified by path * * @param path * Node path */ public void delete(String path) throws Exception { deleteAttribute(path); deleteElement(path); } /** * Delete the element node specified by path * * @param path * Node path */ public void deleteElement(String path) throws Exception { Node nd = getTerminalNode(path, Node.ELEMENT_NODE); Node parent = nd.getParentNode(); parent.removeChild(nd); } /** * Whether the node path exists * * @param path * Node path * @return Exists when true, and does not exist when false. */ public boolean isPathExists(String path) { try { getTerminalNode(path, Node.ELEMENT_NODE); } catch (Exception ex) { return false; } return true; } /** * Delete the attribute node specified by path * * @param path * Node path */ public void deleteAttribute(String path) throws Exception { int i = path.lastIndexOf('/'); Node parent; if (i > 0) { String p = path.substring(0, i); parent = getTerminalNode(p, Node.ELEMENT_NODE); } else { return; } ((Element) parent).removeAttribute(path.substring(i + 1)); } /** * Change the name of the attribute node of the path * * @param path * Node path * @param newName * New name * @throws Exception */ public void renameAttribute(String path, String newName) throws Exception { int i; i = path.lastIndexOf('/'); if (i == -1) { throw new Exception(mm.getMessage("xmlfile.falsepath", xmlFile, path)); } String value = getAttribute(path); deleteAttribute(path); setAttribute(path.substring(0, i) + "/" + newName, value); } /** * Change the name of the element node of the path * * @param path * Node path * @param newName * New name * @throws Exception */ public void renameElement(String path, String newName) throws Exception { if (path.lastIndexOf('/') == -1) { throw new Exception(mm.getMessage("xmlfile.renameroot", xmlFile)); } Node nd = getTerminalNode(path, Node.ELEMENT_NODE); Node pp = nd.getParentNode(); NodeList childNodes = pp.getChildNodes(); int i; if (childNodes != null) { for (i = 0; i < childNodes.getLength(); i++) { if (newName.equalsIgnoreCase(childNodes.item(i).getNodeName())) { throw new Exception(mm.getMessage("xmlfile.existnode", xmlFile, newName)); } } } Element newNode = xmlDocument.createElement(newName); childNodes = nd.getChildNodes(); if (childNodes != null) { for (i = 0; i < childNodes.getLength(); i++) { newNode.appendChild(childNodes.item(i)); } } NamedNodeMap childAttr = nd.getAttributes(); Node tmpNode; if (childAttr != null) { for (i = 0; i < childAttr.getLength(); i++) { tmpNode = childAttr.item(i); newNode.setAttribute(tmpNode.getNodeName(), tmpNode.getNodeValue()); } } pp.replaceChild(newNode, nd); } /** * Set the attribute value of the attribute node of the path * * @param path * Node path * @param value * The attribute value to be set, null means delete the * attribute. */ public void setAttribute(String path, String value) throws Exception { if (path == null) { throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile)); } if (path.trim().length() == 0) { throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile)); } if (value == null) { deleteAttribute(path); return; } Node nd; int i = path.lastIndexOf('/'); if (i > 0) { String p = path.substring(0, i); String v = path.substring(i + 1); newAttribute(p, v); } nd = getTerminalNode(path, Node.ATTRIBUTE_NODE); nd.setNodeValue(value); } /** * Save XML file * * @throws Exception */ public void save() throws Exception { save(xmlFile); } /** * Save XML file * * @param file * XML file path * @throws Exception */ public void save(String file) throws Exception { writeNodeToFile(xmlDocument, file); } /** * Get the byte array of the XML file * * @return */ public byte[] getFileBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { outputDocument(xmlDocument, baos); } catch (Exception ex) { } return baos.toByteArray(); } /** * Save XML file * * @param os * File OutputStream * @throws Exception */ public void save(OutputStream os) throws Exception { outputDocument(xmlDocument, os); } /** * Write document to file * * @param node * Document * @param file * XML file path * @throws Exception */ public static void writeNodeToFile(Document node, String file) throws Exception { outputDocument(node, file); } /** * Output document * * @param node * Document * @param out * The object to output to. It can be: * String,OutputStream,Writer. * @throws Exception */ public static void outputDocument(Document node, Object out) throws Exception { StreamResult result; if (out instanceof String) { result = new StreamResult((String) out); } else if (out instanceof OutputStream) { result = new StreamResult((OutputStream) out); } else if (out instanceof Writer) { result = new StreamResult((Writer) out); } else { return; } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); Properties properties = transformer.getOutputProperties(); properties.setProperty(OutputKeys.ENCODING, "UTF-8"); properties.setProperty(OutputKeys.METHOD, "xml"); properties.setProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperties(properties); DOMSource source = new DOMSource(node); transformer.transform(source, result); } /** * Get the name Section of the nodes * * @param obj * @return * @throws Exception */ private Section getNodesName(Object obj) throws Exception { Section ss = new Section(); if (obj == null) { return ss; } Node nd = null; if (obj instanceof NodeList) { NodeList nl = (NodeList) obj; for (int i = 0; i < nl.getLength(); i++) { nd = nl.item(i); if (nd.getNodeType() != Node.ELEMENT_NODE) { continue; } ss.unionSection(nd.getNodeName()); } } if (obj instanceof NamedNodeMap) { NamedNodeMap nnm = (NamedNodeMap) obj; for (int i = 0; i < nnm.getLength(); i++) { nd = nnm.item(i); ss.unionSection(nd.getNodeName()); } } return ss; } /** * Locate node among nodes * * @param obj * NodeList or NamedNodeMap * @param nodeName * Node name * @return * @throws Exception */ private Node locateNode(Object obj, String nodeName) throws Exception { int i = 0, j = 0; String sTmp; Node tmpNode = null; NodeList nl; NamedNodeMap nnm; if (obj instanceof NodeList) { nl = (NodeList) obj; i = nl.getLength(); for (j = 0; j < i; j++) { tmpNode = nl.item(j); sTmp = tmpNode.getNodeName(); if (sTmp.equalsIgnoreCase(nodeName)) { break; } } } if (obj instanceof NamedNodeMap) { nnm = (NamedNodeMap) obj; i = nnm.getLength(); for (j = 0; j < i; j++) { tmpNode = nnm.item(j); sTmp = tmpNode.getNodeName(); if (sTmp.equalsIgnoreCase(nodeName)) { break; } } } if (j == i) { throw new Exception(mm.getMessage("xmlfile.falsenodename", xmlFile, nodeName)); } return tmpNode; } /** * Get terminal node * * @param path * Node path * @param type * Constants defined in org.w3c.dom.Node * @return * @throws Exception */ private Node getTerminalNode(String path, short type) throws Exception { Node tmpNode = null; String sNode, sLast; int i; if (path == null) { throw new Exception(mm.getMessage("xmlfile.nullpath1", xmlFile)); } i = path.lastIndexOf('/'); if (i == -1) { if (path.length() == 0) { return xmlDocument; } sNode = path; if (type == Node.ELEMENT_NODE) { tmpNode = locateNode(xmlDocument.getChildNodes(), sNode); } } else { sLast = path.substring(i + 1); path = path.substring(0, i); StringTokenizer st = new StringTokenizer(path, "/"); NodeList childNodes = xmlDocument.getChildNodes(); while (st.hasMoreTokens()) { sNode = st.nextToken(); tmpNode = locateNode(childNodes, sNode); if (tmpNode == null) { throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile, path)); } childNodes = tmpNode.getChildNodes(); } if (type == Node.ELEMENT_NODE) { tmpNode = locateNode(tmpNode.getChildNodes(), sLast); } else { tmpNode = locateNode(tmpNode.getAttributes(), sLast); } } if (tmpNode == null) { throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile, path)); } return tmpNode; } /** * Is the legal XML name * * @param input * Node name * @return */ public static boolean isLegalXmlName(String input) { if (input == null || input.length() == 0) { return false; } return true; } /** * ����XML * @param is * @return * @throws Exception */ public static Document parseXml(InputStream is) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); return docBuilder.parse(is); } /** * ������ȡ�ӽڵ� * @param parent * @param childName * @return */ public static Element getChild(Node parent, String childName) { NodeList list = parent.getChildNodes(); if (list == null) { return null; } Node node; for (int i = 0; i < list.getLength(); i++) { node = list.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { if (childName.equalsIgnoreCase(node.getNodeName())) { return (Element) node; } } } return null; } /** * ������ȡ����ӽڵ� * @param parent * @param childName * @return */ public static List<Element> getChildren(Node parent, String childName) { NodeList list = parent.getChildNodes(); if (list == null) { return null; } List<Element> childList = new ArrayList<Element>(); Node node; for (int i = 0; i < list.getLength(); i++) { node = list.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { if (childName.equalsIgnoreCase(node.getNodeName())) { childList.add((Element) node); } } } if (childList.isEmpty()) return null; return childList; }}
|
data/java/10005.java
DELETED
@@ -1,727 +0,0 @@
|
|
1 |
-
package com.scudata.ide.common;
|
2 |
-
|
3 |
-
import java.io.ByteArrayOutputStream;
|
4 |
-
import java.io.File;
|
5 |
-
import java.io.FileInputStream;
|
6 |
-
import java.io.InputStream;
|
7 |
-
import java.io.OutputStream;
|
8 |
-
import java.io.Writer;
|
9 |
-
import java.util.ArrayList;
|
10 |
-
import java.util.List;
|
11 |
-
import java.util.Properties;
|
12 |
-
import java.util.StringTokenizer;
|
13 |
-
|
14 |
-
import javax.xml.parsers.DocumentBuilder;
|
15 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
16 |
-
import javax.xml.transform.OutputKeys;
|
17 |
-
import javax.xml.transform.Transformer;
|
18 |
-
import javax.xml.transform.TransformerFactory;
|
19 |
-
import javax.xml.transform.dom.DOMSource;
|
20 |
-
import javax.xml.transform.stream.StreamResult;
|
21 |
-
|
22 |
-
import org.w3c.dom.Document;
|
23 |
-
import org.w3c.dom.Element;
|
24 |
-
import org.w3c.dom.NamedNodeMap;
|
25 |
-
import org.w3c.dom.Node;
|
26 |
-
import org.w3c.dom.NodeList;
|
27 |
-
|
28 |
-
import com.scudata.app.common.Section;
|
29 |
-
import com.scudata.common.MessageManager;
|
30 |
-
import com.scudata.ide.common.resources.IdeCommonMessage;
|
31 |
-
|
32 |
-
/**
|
33 |
-
* Used to parse xml files
|
34 |
-
*/
|
35 |
-
public class XMLFile {
|
36 |
-
|
37 |
-
/**
|
38 |
-
* XML file path
|
39 |
-
*/
|
40 |
-
public String xmlFile = null;
|
41 |
-
|
42 |
-
/**
|
43 |
-
* XML Document
|
44 |
-
*/
|
45 |
-
private Document xmlDocument = null;
|
46 |
-
|
47 |
-
/**
|
48 |
-
* Common MessageManager
|
49 |
-
*/
|
50 |
-
private MessageManager mm = IdeCommonMessage.get();
|
51 |
-
|
52 |
-
/**
|
53 |
-
* Constructor
|
54 |
-
*
|
55 |
-
* @param file
|
56 |
-
* XML file path
|
57 |
-
* @throws Exception
|
58 |
-
*/
|
59 |
-
public XMLFile(String file) throws Exception {
|
60 |
-
this(new File(file), "root");
|
61 |
-
}
|
62 |
-
|
63 |
-
/**
|
64 |
-
* Constructor
|
65 |
-
*
|
66 |
-
* @param file
|
67 |
-
* XML file path
|
68 |
-
* @param root
|
69 |
-
* Root node name
|
70 |
-
* @throws Exception
|
71 |
-
*/
|
72 |
-
public XMLFile(File file, String root) throws Exception {
|
73 |
-
if (file != null) {
|
74 |
-
xmlFile = file.getAbsolutePath();
|
75 |
-
if (file.exists() && file.isFile()) {
|
76 |
-
loadXMLFile(new FileInputStream(file));
|
77 |
-
} else {
|
78 |
-
XMLFile.newXML(xmlFile, root);
|
79 |
-
}
|
80 |
-
} else {
|
81 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
82 |
-
.newInstance();
|
83 |
-
|
84 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
85 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
86 |
-
// FIXED:
|
87 |
-
|
88 |
-
xmlDocument = docBuilder.newDocument();
|
89 |
-
Element eRoot = xmlDocument.createElement(root);
|
90 |
-
eRoot.normalize();
|
91 |
-
xmlDocument.appendChild(eRoot);
|
92 |
-
}
|
93 |
-
}
|
94 |
-
|
95 |
-
/**
|
96 |
-
* Constructor
|
97 |
-
*
|
98 |
-
* @param is
|
99 |
-
* File InputStream
|
100 |
-
* @throws Exception
|
101 |
-
*/
|
102 |
-
public XMLFile(InputStream is) throws Exception {
|
103 |
-
loadXMLFile(is);
|
104 |
-
}
|
105 |
-
|
106 |
-
/**
|
107 |
-
* Load XML file from file input stream
|
108 |
-
*
|
109 |
-
* @param is
|
110 |
-
* @throws Exception
|
111 |
-
*/
|
112 |
-
private void loadXMLFile(InputStream is) throws Exception {
|
113 |
-
xmlDocument = parseXml(is);
|
114 |
-
}
|
115 |
-
|
116 |
-
/**
|
117 |
-
* Create a new XML file
|
118 |
-
*
|
119 |
-
* @param file
|
120 |
-
* The name of the file to be created. If the file exists, it
|
121 |
-
* will overwrite the original one.
|
122 |
-
* @param root
|
123 |
-
* Root node name
|
124 |
-
* @return Return true if the creation is successful, otherwise false.
|
125 |
-
*/
|
126 |
-
public static XMLFile newXML(String file, String root) throws Exception {
|
127 |
-
if (!isLegalXmlName(root)) {
|
128 |
-
throw new Exception(IdeCommonMessage.get().getMessage(
|
129 |
-
"xmlfile.falseroot", file, root));
|
130 |
-
}
|
131 |
-
|
132 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
133 |
-
.newInstance();
|
134 |
-
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
135 |
-
Document sxmlDocument = docBuilder.newDocument();
|
136 |
-
Element eRoot = sxmlDocument.createElement(root);
|
137 |
-
eRoot.normalize();
|
138 |
-
sxmlDocument.appendChild(eRoot);
|
139 |
-
|
140 |
-
writeNodeToFile(sxmlDocument, file);
|
141 |
-
return new XMLFile(file);
|
142 |
-
}
|
143 |
-
|
144 |
-
/**
|
145 |
-
* List all sub-elements under the path path in the file file, including
|
146 |
-
* elements and attributes.
|
147 |
-
*
|
148 |
-
* @param path
|
149 |
-
* Node path, use / as a separator, for example: "a/b/c"
|
150 |
-
* @return Return the section of the element and attribute under the path
|
151 |
-
* node
|
152 |
-
*/
|
153 |
-
public Section listAll(String path) throws Exception {
|
154 |
-
Section ss = new Section();
|
155 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
156 |
-
ss.unionSection(getNodesName(tmpNode.getChildNodes()));
|
157 |
-
ss.unionSection(getNodesName(tmpNode.getAttributes()));
|
158 |
-
return ss;
|
159 |
-
}
|
160 |
-
|
161 |
-
/**
|
162 |
-
* List all sub-elements under path in the file
|
163 |
-
*
|
164 |
-
* @param path
|
165 |
-
* Node path
|
166 |
-
* @return Return the section of the elements under the path node
|
167 |
-
*/
|
168 |
-
public Section listElement(String path) throws Exception {
|
169 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
170 |
-
return getNodesName(tmpNode.getChildNodes());
|
171 |
-
}
|
172 |
-
|
173 |
-
/**
|
174 |
-
* List all attributes under path in file
|
175 |
-
*
|
176 |
-
* @param path
|
177 |
-
* Node path
|
178 |
-
* @return Return the section of the attribute names under the path node
|
179 |
-
*/
|
180 |
-
public Section listAttribute(String path) throws Exception {
|
181 |
-
Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE);
|
182 |
-
return getNodesName(tmpNode.getAttributes());
|
183 |
-
}
|
184 |
-
|
185 |
-
/**
|
186 |
-
* List the attribute value of the path node in the file
|
187 |
-
*
|
188 |
-
* @param path
|
189 |
-
* Node path
|
190 |
-
* @return The value of the attribute
|
191 |
-
*/
|
192 |
-
public String getAttribute(String path) {
|
193 |
-
try {
|
194 |
-
Node tmpNode = getTerminalNode(path, Node.ATTRIBUTE_NODE);
|
195 |
-
return tmpNode.getNodeValue();
|
196 |
-
} catch (Exception ex) {
|
197 |
-
return "";
|
198 |
-
}
|
199 |
-
}
|
200 |
-
|
201 |
-
/**
|
202 |
-
* Create a new element under the current path
|
203 |
-
*
|
204 |
-
* @param path
|
205 |
-
* Node path
|
206 |
-
* @param element
|
207 |
-
* The name of the element to be created
|
208 |
-
* @return The node path after the new element is successfully created
|
209 |
-
*/
|
210 |
-
public String newElement(String path, String element) throws Exception {
|
211 |
-
Element newElement = null;
|
212 |
-
if (!isLegalXmlName(element)) {
|
213 |
-
throw new Exception(mm.getMessage("xmlfile.falseelement", xmlFile,
|
214 |
-
element));
|
215 |
-
}
|
216 |
-
|
217 |
-
Node parent = getTerminalNode(path, Node.ELEMENT_NODE);
|
218 |
-
NodeList nl = parent.getChildNodes();
|
219 |
-
int i;
|
220 |
-
for (i = 0; i < nl.getLength(); i++) {
|
221 |
-
if (nl.item(i).getNodeName().equalsIgnoreCase(element)) {
|
222 |
-
break;
|
223 |
-
}
|
224 |
-
}
|
225 |
-
if (i >= nl.getLength()) {
|
226 |
-
newElement = xmlDocument.createElement(element);
|
227 |
-
parent.appendChild(newElement);
|
228 |
-
}
|
229 |
-
return path + "/" + element;
|
230 |
-
}
|
231 |
-
|
232 |
-
/**
|
233 |
-
* Create a new attribute under the current path
|
234 |
-
*
|
235 |
-
* @param path
|
236 |
-
* Node path
|
237 |
-
* @param attr
|
238 |
-
* The name of the attribute to be created
|
239 |
-
* @return Return 1 on success, -1 on failure (when the attribute with the
|
240 |
-
* same name exists)
|
241 |
-
*/
|
242 |
-
public int newAttribute(String path, String attr) throws Exception {
|
243 |
-
if (!isLegalXmlName(attr)) {
|
244 |
-
throw new Exception(mm.getMessage("xmlfile.falseattr", xmlFile,
|
245 |
-
attr));
|
246 |
-
}
|
247 |
-
|
248 |
-
Node parent = getTerminalNode(path, Node.ELEMENT_NODE);
|
249 |
-
|
250 |
-
NamedNodeMap nl = parent.getAttributes();
|
251 |
-
int i;
|
252 |
-
for (i = 0; i < nl.getLength(); i++) {
|
253 |
-
if (nl.item(i).getNodeName().equalsIgnoreCase(attr)) {
|
254 |
-
break;
|
255 |
-
}
|
256 |
-
}
|
257 |
-
if (i >= nl.getLength()) {
|
258 |
-
((Element) parent).setAttribute(attr, "");
|
259 |
-
} else {
|
260 |
-
return -1;
|
261 |
-
}
|
262 |
-
return 1;
|
263 |
-
}
|
264 |
-
|
265 |
-
/**
|
266 |
-
* Delete the node specified by path
|
267 |
-
*
|
268 |
-
* @param path
|
269 |
-
* Node path
|
270 |
-
*/
|
271 |
-
public void delete(String path) throws Exception {
|
272 |
-
deleteAttribute(path);
|
273 |
-
deleteElement(path);
|
274 |
-
}
|
275 |
-
|
276 |
-
/**
|
277 |
-
* Delete the element node specified by path
|
278 |
-
*
|
279 |
-
* @param path
|
280 |
-
* Node path
|
281 |
-
*/
|
282 |
-
public void deleteElement(String path) throws Exception {
|
283 |
-
Node nd = getTerminalNode(path, Node.ELEMENT_NODE);
|
284 |
-
Node parent = nd.getParentNode();
|
285 |
-
parent.removeChild(nd);
|
286 |
-
}
|
287 |
-
|
288 |
-
/**
|
289 |
-
* Whether the node path exists
|
290 |
-
*
|
291 |
-
* @param path
|
292 |
-
* Node path
|
293 |
-
* @return Exists when true, and does not exist when false.
|
294 |
-
*/
|
295 |
-
public boolean isPathExists(String path) {
|
296 |
-
try {
|
297 |
-
getTerminalNode(path, Node.ELEMENT_NODE);
|
298 |
-
} catch (Exception ex) {
|
299 |
-
return false;
|
300 |
-
}
|
301 |
-
return true;
|
302 |
-
}
|
303 |
-
|
304 |
-
/**
|
305 |
-
* Delete the attribute node specified by path
|
306 |
-
*
|
307 |
-
* @param path
|
308 |
-
* Node path
|
309 |
-
*/
|
310 |
-
public void deleteAttribute(String path) throws Exception {
|
311 |
-
int i = path.lastIndexOf('/');
|
312 |
-
Node parent;
|
313 |
-
if (i > 0) {
|
314 |
-
String p = path.substring(0, i);
|
315 |
-
parent = getTerminalNode(p, Node.ELEMENT_NODE);
|
316 |
-
} else {
|
317 |
-
return;
|
318 |
-
}
|
319 |
-
((Element) parent).removeAttribute(path.substring(i + 1));
|
320 |
-
}
|
321 |
-
|
322 |
-
/**
|
323 |
-
* Change the name of the attribute node of the path
|
324 |
-
*
|
325 |
-
* @param path
|
326 |
-
* Node path
|
327 |
-
* @param newName
|
328 |
-
* New name
|
329 |
-
* @throws Exception
|
330 |
-
*/
|
331 |
-
public void renameAttribute(String path, String newName) throws Exception {
|
332 |
-
int i;
|
333 |
-
i = path.lastIndexOf('/');
|
334 |
-
if (i == -1) {
|
335 |
-
throw new Exception(mm.getMessage("xmlfile.falsepath", xmlFile,
|
336 |
-
path));
|
337 |
-
}
|
338 |
-
|
339 |
-
String value = getAttribute(path);
|
340 |
-
deleteAttribute(path);
|
341 |
-
setAttribute(path.substring(0, i) + "/" + newName, value);
|
342 |
-
}
|
343 |
-
|
344 |
-
/**
|
345 |
-
* Change the name of the element node of the path
|
346 |
-
*
|
347 |
-
* @param path
|
348 |
-
* Node path
|
349 |
-
* @param newName
|
350 |
-
* New name
|
351 |
-
* @throws Exception
|
352 |
-
*/
|
353 |
-
public void renameElement(String path, String newName) throws Exception {
|
354 |
-
if (path.lastIndexOf('/') == -1) {
|
355 |
-
throw new Exception(mm.getMessage("xmlfile.renameroot", xmlFile));
|
356 |
-
}
|
357 |
-
Node nd = getTerminalNode(path, Node.ELEMENT_NODE);
|
358 |
-
Node pp = nd.getParentNode();
|
359 |
-
NodeList childNodes = pp.getChildNodes();
|
360 |
-
int i;
|
361 |
-
if (childNodes != null) {
|
362 |
-
for (i = 0; i < childNodes.getLength(); i++) {
|
363 |
-
if (newName.equalsIgnoreCase(childNodes.item(i).getNodeName())) {
|
364 |
-
throw new Exception(mm.getMessage("xmlfile.existnode",
|
365 |
-
xmlFile, newName));
|
366 |
-
}
|
367 |
-
}
|
368 |
-
}
|
369 |
-
|
370 |
-
Element newNode = xmlDocument.createElement(newName);
|
371 |
-
|
372 |
-
childNodes = nd.getChildNodes();
|
373 |
-
if (childNodes != null) {
|
374 |
-
for (i = 0; i < childNodes.getLength(); i++) {
|
375 |
-
newNode.appendChild(childNodes.item(i));
|
376 |
-
}
|
377 |
-
}
|
378 |
-
NamedNodeMap childAttr = nd.getAttributes();
|
379 |
-
Node tmpNode;
|
380 |
-
if (childAttr != null) {
|
381 |
-
for (i = 0; i < childAttr.getLength(); i++) {
|
382 |
-
tmpNode = childAttr.item(i);
|
383 |
-
newNode.setAttribute(tmpNode.getNodeName(),
|
384 |
-
tmpNode.getNodeValue());
|
385 |
-
}
|
386 |
-
}
|
387 |
-
pp.replaceChild(newNode, nd);
|
388 |
-
}
|
389 |
-
|
390 |
-
/**
|
391 |
-
* Set the attribute value of the attribute node of the path
|
392 |
-
*
|
393 |
-
* @param path
|
394 |
-
* Node path
|
395 |
-
* @param value
|
396 |
-
* The attribute value to be set, null means delete the
|
397 |
-
* attribute.
|
398 |
-
*/
|
399 |
-
public void setAttribute(String path, String value) throws Exception {
|
400 |
-
if (path == null) {
|
401 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile));
|
402 |
-
}
|
403 |
-
if (path.trim().length() == 0) {
|
404 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile));
|
405 |
-
}
|
406 |
-
if (value == null) {
|
407 |
-
deleteAttribute(path);
|
408 |
-
return;
|
409 |
-
}
|
410 |
-
Node nd;
|
411 |
-
int i = path.lastIndexOf('/');
|
412 |
-
if (i > 0) {
|
413 |
-
String p = path.substring(0, i);
|
414 |
-
String v = path.substring(i + 1);
|
415 |
-
newAttribute(p, v);
|
416 |
-
}
|
417 |
-
|
418 |
-
nd = getTerminalNode(path, Node.ATTRIBUTE_NODE);
|
419 |
-
nd.setNodeValue(value);
|
420 |
-
}
|
421 |
-
|
422 |
-
/**
|
423 |
-
* Save XML file
|
424 |
-
*
|
425 |
-
* @throws Exception
|
426 |
-
*/
|
427 |
-
public void save() throws Exception {
|
428 |
-
save(xmlFile);
|
429 |
-
}
|
430 |
-
|
431 |
-
/**
|
432 |
-
* Save XML file
|
433 |
-
*
|
434 |
-
* @param file
|
435 |
-
* XML file path
|
436 |
-
* @throws Exception
|
437 |
-
*/
|
438 |
-
public void save(String file) throws Exception {
|
439 |
-
writeNodeToFile(xmlDocument, file);
|
440 |
-
}
|
441 |
-
|
442 |
-
/**
|
443 |
-
* Get the byte array of the XML file
|
444 |
-
*
|
445 |
-
* @return
|
446 |
-
*/
|
447 |
-
public byte[] getFileBytes() {
|
448 |
-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
449 |
-
try {
|
450 |
-
outputDocument(xmlDocument, baos);
|
451 |
-
} catch (Exception ex) {
|
452 |
-
}
|
453 |
-
return baos.toByteArray();
|
454 |
-
}
|
455 |
-
|
456 |
-
/**
|
457 |
-
* Save XML file
|
458 |
-
*
|
459 |
-
* @param os
|
460 |
-
* File OutputStream
|
461 |
-
* @throws Exception
|
462 |
-
*/
|
463 |
-
public void save(OutputStream os) throws Exception {
|
464 |
-
outputDocument(xmlDocument, os);
|
465 |
-
}
|
466 |
-
|
467 |
-
/**
|
468 |
-
* Write document to file
|
469 |
-
*
|
470 |
-
* @param node
|
471 |
-
* Document
|
472 |
-
* @param file
|
473 |
-
* XML file path
|
474 |
-
* @throws Exception
|
475 |
-
*/
|
476 |
-
public static void writeNodeToFile(Document node, String file)
|
477 |
-
throws Exception {
|
478 |
-
outputDocument(node, file);
|
479 |
-
}
|
480 |
-
|
481 |
-
/**
|
482 |
-
* Output document
|
483 |
-
*
|
484 |
-
* @param node
|
485 |
-
* Document
|
486 |
-
* @param out
|
487 |
-
* The object to output to. It can be:
|
488 |
-
* String,OutputStream,Writer.
|
489 |
-
* @throws Exception
|
490 |
-
*/
|
491 |
-
public static void outputDocument(Document node, Object out)
|
492 |
-
throws Exception {
|
493 |
-
StreamResult result;
|
494 |
-
if (out instanceof String) {
|
495 |
-
result = new StreamResult((String) out);
|
496 |
-
} else if (out instanceof OutputStream) {
|
497 |
-
result = new StreamResult((OutputStream) out);
|
498 |
-
} else if (out instanceof Writer) {
|
499 |
-
result = new StreamResult((Writer) out);
|
500 |
-
} else {
|
501 |
-
return;
|
502 |
-
}
|
503 |
-
TransformerFactory tFactory = TransformerFactory.newInstance();
|
504 |
-
Transformer transformer = tFactory.newTransformer();
|
505 |
-
|
506 |
-
Properties properties = transformer.getOutputProperties();
|
507 |
-
properties.setProperty(OutputKeys.ENCODING, "UTF-8");
|
508 |
-
properties.setProperty(OutputKeys.METHOD, "xml");
|
509 |
-
properties.setProperty(OutputKeys.INDENT, "yes");
|
510 |
-
transformer.setOutputProperties(properties);
|
511 |
-
|
512 |
-
DOMSource source = new DOMSource(node);
|
513 |
-
transformer.transform(source, result);
|
514 |
-
}
|
515 |
-
|
516 |
-
/**
|
517 |
-
* Get the name Section of the nodes
|
518 |
-
*
|
519 |
-
* @param obj
|
520 |
-
* @return
|
521 |
-
* @throws Exception
|
522 |
-
*/
|
523 |
-
private Section getNodesName(Object obj) throws Exception {
|
524 |
-
Section ss = new Section();
|
525 |
-
if (obj == null) {
|
526 |
-
return ss;
|
527 |
-
}
|
528 |
-
|
529 |
-
Node nd = null;
|
530 |
-
if (obj instanceof NodeList) {
|
531 |
-
NodeList nl = (NodeList) obj;
|
532 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
533 |
-
nd = nl.item(i);
|
534 |
-
if (nd.getNodeType() != Node.ELEMENT_NODE) {
|
535 |
-
continue;
|
536 |
-
}
|
537 |
-
ss.unionSection(nd.getNodeName());
|
538 |
-
}
|
539 |
-
}
|
540 |
-
|
541 |
-
if (obj instanceof NamedNodeMap) {
|
542 |
-
NamedNodeMap nnm = (NamedNodeMap) obj;
|
543 |
-
for (int i = 0; i < nnm.getLength(); i++) {
|
544 |
-
nd = nnm.item(i);
|
545 |
-
ss.unionSection(nd.getNodeName());
|
546 |
-
}
|
547 |
-
}
|
548 |
-
return ss;
|
549 |
-
}
|
550 |
-
|
551 |
-
/**
|
552 |
-
* Locate node among nodes
|
553 |
-
*
|
554 |
-
* @param obj
|
555 |
-
* NodeList or NamedNodeMap
|
556 |
-
* @param nodeName
|
557 |
-
* Node name
|
558 |
-
* @return
|
559 |
-
* @throws Exception
|
560 |
-
*/
|
561 |
-
private Node locateNode(Object obj, String nodeName) throws Exception {
|
562 |
-
int i = 0, j = 0;
|
563 |
-
String sTmp;
|
564 |
-
Node tmpNode = null;
|
565 |
-
NodeList nl;
|
566 |
-
NamedNodeMap nnm;
|
567 |
-
|
568 |
-
if (obj instanceof NodeList) {
|
569 |
-
nl = (NodeList) obj;
|
570 |
-
i = nl.getLength();
|
571 |
-
for (j = 0; j < i; j++) {
|
572 |
-
tmpNode = nl.item(j);
|
573 |
-
sTmp = tmpNode.getNodeName();
|
574 |
-
if (sTmp.equalsIgnoreCase(nodeName)) {
|
575 |
-
break;
|
576 |
-
}
|
577 |
-
}
|
578 |
-
}
|
579 |
-
if (obj instanceof NamedNodeMap) {
|
580 |
-
nnm = (NamedNodeMap) obj;
|
581 |
-
i = nnm.getLength();
|
582 |
-
for (j = 0; j < i; j++) {
|
583 |
-
tmpNode = nnm.item(j);
|
584 |
-
sTmp = tmpNode.getNodeName();
|
585 |
-
if (sTmp.equalsIgnoreCase(nodeName)) {
|
586 |
-
break;
|
587 |
-
}
|
588 |
-
}
|
589 |
-
}
|
590 |
-
if (j == i) {
|
591 |
-
throw new Exception(mm.getMessage("xmlfile.falsenodename", xmlFile,
|
592 |
-
nodeName));
|
593 |
-
}
|
594 |
-
return tmpNode;
|
595 |
-
}
|
596 |
-
|
597 |
-
/**
|
598 |
-
* Get terminal node
|
599 |
-
*
|
600 |
-
* @param path
|
601 |
-
* Node path
|
602 |
-
* @param type
|
603 |
-
* Constants defined in org.w3c.dom.Node
|
604 |
-
* @return
|
605 |
-
* @throws Exception
|
606 |
-
*/
|
607 |
-
private Node getTerminalNode(String path, short type) throws Exception {
|
608 |
-
Node tmpNode = null;
|
609 |
-
String sNode, sLast;
|
610 |
-
int i;
|
611 |
-
if (path == null) {
|
612 |
-
throw new Exception(mm.getMessage("xmlfile.nullpath1", xmlFile));
|
613 |
-
}
|
614 |
-
i = path.lastIndexOf('/');
|
615 |
-
if (i == -1) {
|
616 |
-
if (path.length() == 0) {
|
617 |
-
return xmlDocument;
|
618 |
-
}
|
619 |
-
sNode = path;
|
620 |
-
if (type == Node.ELEMENT_NODE) {
|
621 |
-
tmpNode = locateNode(xmlDocument.getChildNodes(), sNode);
|
622 |
-
}
|
623 |
-
} else {
|
624 |
-
sLast = path.substring(i + 1);
|
625 |
-
path = path.substring(0, i);
|
626 |
-
|
627 |
-
StringTokenizer st = new StringTokenizer(path, "/");
|
628 |
-
NodeList childNodes = xmlDocument.getChildNodes();
|
629 |
-
while (st.hasMoreTokens()) {
|
630 |
-
sNode = st.nextToken();
|
631 |
-
tmpNode = locateNode(childNodes, sNode);
|
632 |
-
if (tmpNode == null) {
|
633 |
-
throw new Exception(mm.getMessage("xmlfile.notexistpath",
|
634 |
-
xmlFile, path));
|
635 |
-
}
|
636 |
-
childNodes = tmpNode.getChildNodes();
|
637 |
-
}
|
638 |
-
if (type == Node.ELEMENT_NODE) {
|
639 |
-
tmpNode = locateNode(tmpNode.getChildNodes(), sLast);
|
640 |
-
} else {
|
641 |
-
tmpNode = locateNode(tmpNode.getAttributes(), sLast);
|
642 |
-
}
|
643 |
-
}
|
644 |
-
if (tmpNode == null) {
|
645 |
-
throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile,
|
646 |
-
path));
|
647 |
-
}
|
648 |
-
return tmpNode;
|
649 |
-
}
|
650 |
-
|
651 |
-
/**
|
652 |
-
* Is the legal XML name
|
653 |
-
*
|
654 |
-
* @param input
|
655 |
-
* Node name
|
656 |
-
* @return
|
657 |
-
*/
|
658 |
-
public static boolean isLegalXmlName(String input) {
|
659 |
-
if (input == null || input.length() == 0) {
|
660 |
-
return false;
|
661 |
-
}
|
662 |
-
return true;
|
663 |
-
}
|
664 |
-
|
665 |
-
/**
|
666 |
-
* ����XML
|
667 |
-
* @param is
|
668 |
-
* @return
|
669 |
-
* @throws Exception
|
670 |
-
*/
|
671 |
-
public static Document parseXml(InputStream is) throws Exception {
|
672 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
673 |
-
.newInstance();
|
674 |
-
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
675 |
-
return docBuilder.parse(is);
|
676 |
-
}
|
677 |
-
|
678 |
-
/**
|
679 |
-
* ������ȡ�ӽڵ�
|
680 |
-
* @param parent
|
681 |
-
* @param childName
|
682 |
-
* @return
|
683 |
-
*/
|
684 |
-
public static Element getChild(Node parent, String childName) {
|
685 |
-
NodeList list = parent.getChildNodes();
|
686 |
-
if (list == null) {
|
687 |
-
return null;
|
688 |
-
}
|
689 |
-
Node node;
|
690 |
-
for (int i = 0; i < list.getLength(); i++) {
|
691 |
-
node = list.item(i);
|
692 |
-
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
|
693 |
-
if (childName.equalsIgnoreCase(node.getNodeName())) {
|
694 |
-
return (Element) node;
|
695 |
-
}
|
696 |
-
}
|
697 |
-
}
|
698 |
-
return null;
|
699 |
-
}
|
700 |
-
|
701 |
-
/**
|
702 |
-
* ������ȡ����ӽڵ�
|
703 |
-
* @param parent
|
704 |
-
* @param childName
|
705 |
-
* @return
|
706 |
-
*/
|
707 |
-
public static List<Element> getChildren(Node parent, String childName) {
|
708 |
-
NodeList list = parent.getChildNodes();
|
709 |
-
if (list == null) {
|
710 |
-
return null;
|
711 |
-
}
|
712 |
-
List<Element> childList = new ArrayList<Element>();
|
713 |
-
Node node;
|
714 |
-
for (int i = 0; i < list.getLength(); i++) {
|
715 |
-
node = list.item(i);
|
716 |
-
if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
|
717 |
-
if (childName.equalsIgnoreCase(node.getNodeName())) {
|
718 |
-
childList.add((Element) node);
|
719 |
-
}
|
720 |
-
}
|
721 |
-
}
|
722 |
-
if (childList.isEmpty())
|
723 |
-
return null;
|
724 |
-
return childList;
|
725 |
-
}
|
726 |
-
|
727 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10005.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.ide.common;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import java.io.Writer;import java.util.ArrayList;import java.util.List;import java.util.Properties;import java.util.StringTokenizer;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import com.scudata.app.common.Section;import com.scudata.common.MessageManager;import com.scudata.ide.common.resources.IdeCommonMessage;/** * Used to parse xml files */public class XMLFile { /** * XML file path */ public String xmlFile = null; /** * XML Document */ private Document xmlDocument = null; /** * Common MessageManager */ private MessageManager mm = IdeCommonMessage.get(); /** * Constructor * * @param file * XML file path * @throws Exception */ public XMLFile(String file) throws Exception { this(new File(file), "root"); } /** * Constructor * * @param file * XML file path * @param root * Root node name * @throws Exception */ public XMLFile(File file, String root) throws Exception { if (file != null) { xmlFile = file.getAbsolutePath(); if (file.exists() && file.isFile()) { loadXMLFile(new FileInputStream(file)); } else { XMLFile.newXML(xmlFile, root); } } else { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: xmlDocument = docBuilder.newDocument(); Element eRoot = xmlDocument.createElement(root); eRoot.normalize(); xmlDocument.appendChild(eRoot); } } /** * Constructor * * @param is * File InputStream * @throws Exception */ public XMLFile(InputStream is) throws Exception { loadXMLFile(is); } /** * Load XML file from file input stream * * @param is * @throws Exception */ private void loadXMLFile(InputStream is) throws Exception { xmlDocument = parseXml(is); } /** * Create a new XML file * * @param file * The name of the file to be created. If the file exists, it * will overwrite the original one. * @param root * Root node name * @return Return true if the creation is successful, otherwise false. */ public static XMLFile newXML(String file, String root) throws Exception { if (!isLegalXmlName(root)) { throw new Exception(IdeCommonMessage.get().getMessage( "xmlfile.falseroot", file, root)); } DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document sxmlDocument = docBuilder.newDocument(); Element eRoot = sxmlDocument.createElement(root); eRoot.normalize(); sxmlDocument.appendChild(eRoot); writeNodeToFile(sxmlDocument, file); return new XMLFile(file); } /** * List all sub-elements under the path path in the file file, including * elements and attributes. * * @param path * Node path, use / as a separator, for example: "a/b/c" * @return Return the section of the element and attribute under the path * node */ public Section listAll(String path) throws Exception { Section ss = new Section(); Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); ss.unionSection(getNodesName(tmpNode.getChildNodes())); ss.unionSection(getNodesName(tmpNode.getAttributes())); return ss; } /** * List all sub-elements under path in the file * * @param path * Node path * @return Return the section of the elements under the path node */ public Section listElement(String path) throws Exception { Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); return getNodesName(tmpNode.getChildNodes()); } /** * List all attributes under path in file * * @param path * Node path * @return Return the section of the attribute names under the path node */ public Section listAttribute(String path) throws Exception { Node tmpNode = getTerminalNode(path, Node.ELEMENT_NODE); return getNodesName(tmpNode.getAttributes()); } /** * List the attribute value of the path node in the file * * @param path * Node path * @return The value of the attribute */ public String getAttribute(String path) { try { Node tmpNode = getTerminalNode(path, Node.ATTRIBUTE_NODE); return tmpNode.getNodeValue(); } catch (Exception ex) { return ""; } } /** * Create a new element under the current path * * @param path * Node path * @param element * The name of the element to be created * @return The node path after the new element is successfully created */ public String newElement(String path, String element) throws Exception { Element newElement = null; if (!isLegalXmlName(element)) { throw new Exception(mm.getMessage("xmlfile.falseelement", xmlFile, element)); } Node parent = getTerminalNode(path, Node.ELEMENT_NODE); NodeList nl = parent.getChildNodes(); int i; for (i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equalsIgnoreCase(element)) { break; } } if (i >= nl.getLength()) { newElement = xmlDocument.createElement(element); parent.appendChild(newElement); } return path + "/" + element; } /** * Create a new attribute under the current path * * @param path * Node path * @param attr * The name of the attribute to be created * @return Return 1 on success, -1 on failure (when the attribute with the * same name exists) */ public int newAttribute(String path, String attr) throws Exception { if (!isLegalXmlName(attr)) { throw new Exception(mm.getMessage("xmlfile.falseattr", xmlFile, attr)); } Node parent = getTerminalNode(path, Node.ELEMENT_NODE); NamedNodeMap nl = parent.getAttributes(); int i; for (i = 0; i < nl.getLength(); i++) { if (nl.item(i).getNodeName().equalsIgnoreCase(attr)) { break; } } if (i >= nl.getLength()) { ((Element) parent).setAttribute(attr, ""); } else { return -1; } return 1; } /** * Delete the node specified by path * * @param path * Node path */ public void delete(String path) throws Exception { deleteAttribute(path); deleteElement(path); } /** * Delete the element node specified by path * * @param path * Node path */ public void deleteElement(String path) throws Exception { Node nd = getTerminalNode(path, Node.ELEMENT_NODE); Node parent = nd.getParentNode(); parent.removeChild(nd); } /** * Whether the node path exists * * @param path * Node path * @return Exists when true, and does not exist when false. */ public boolean isPathExists(String path) { try { getTerminalNode(path, Node.ELEMENT_NODE); } catch (Exception ex) { return false; } return true; } /** * Delete the attribute node specified by path * * @param path * Node path */ public void deleteAttribute(String path) throws Exception { int i = path.lastIndexOf('/'); Node parent; if (i > 0) { String p = path.substring(0, i); parent = getTerminalNode(p, Node.ELEMENT_NODE); } else { return; } ((Element) parent).removeAttribute(path.substring(i + 1)); } /** * Change the name of the attribute node of the path * * @param path * Node path * @param newName * New name * @throws Exception */ public void renameAttribute(String path, String newName) throws Exception { int i; i = path.lastIndexOf('/'); if (i == -1) { throw new Exception(mm.getMessage("xmlfile.falsepath", xmlFile, path)); } String value = getAttribute(path); deleteAttribute(path); setAttribute(path.substring(0, i) + "/" + newName, value); } /** * Change the name of the element node of the path * * @param path * Node path * @param newName * New name * @throws Exception */ public void renameElement(String path, String newName) throws Exception { if (path.lastIndexOf('/') == -1) { throw new Exception(mm.getMessage("xmlfile.renameroot", xmlFile)); } Node nd = getTerminalNode(path, Node.ELEMENT_NODE); Node pp = nd.getParentNode(); NodeList childNodes = pp.getChildNodes(); int i; if (childNodes != null) { for (i = 0; i < childNodes.getLength(); i++) { if (newName.equalsIgnoreCase(childNodes.item(i).getNodeName())) { throw new Exception(mm.getMessage("xmlfile.existnode", xmlFile, newName)); } } } Element newNode = xmlDocument.createElement(newName); childNodes = nd.getChildNodes(); if (childNodes != null) { for (i = 0; i < childNodes.getLength(); i++) { newNode.appendChild(childNodes.item(i)); } } NamedNodeMap childAttr = nd.getAttributes(); Node tmpNode; if (childAttr != null) { for (i = 0; i < childAttr.getLength(); i++) { tmpNode = childAttr.item(i); newNode.setAttribute(tmpNode.getNodeName(), tmpNode.getNodeValue()); } } pp.replaceChild(newNode, nd); } /** * Set the attribute value of the attribute node of the path * * @param path * Node path * @param value * The attribute value to be set, null means delete the * attribute. */ public void setAttribute(String path, String value) throws Exception { if (path == null) { throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile)); } if (path.trim().length() == 0) { throw new Exception(mm.getMessage("xmlfile.nullpath", xmlFile)); } if (value == null) { deleteAttribute(path); return; } Node nd; int i = path.lastIndexOf('/'); if (i > 0) { String p = path.substring(0, i); String v = path.substring(i + 1); newAttribute(p, v); } nd = getTerminalNode(path, Node.ATTRIBUTE_NODE); nd.setNodeValue(value); } /** * Save XML file * * @throws Exception */ public void save() throws Exception { save(xmlFile); } /** * Save XML file * * @param file * XML file path * @throws Exception */ public void save(String file) throws Exception { writeNodeToFile(xmlDocument, file); } /** * Get the byte array of the XML file * * @return */ public byte[] getFileBytes() { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { outputDocument(xmlDocument, baos); } catch (Exception ex) { } return baos.toByteArray(); } /** * Save XML file * * @param os * File OutputStream * @throws Exception */ public void save(OutputStream os) throws Exception { outputDocument(xmlDocument, os); } /** * Write document to file * * @param node * Document * @param file * XML file path * @throws Exception */ public static void writeNodeToFile(Document node, String file) throws Exception { outputDocument(node, file); } /** * Output document * * @param node * Document * @param out * The object to output to. It can be: * String,OutputStream,Writer. * @throws Exception */ public static void outputDocument(Document node, Object out) throws Exception { StreamResult result; if (out instanceof String) { result = new StreamResult((String) out); } else if (out instanceof OutputStream) { result = new StreamResult((OutputStream) out); } else if (out instanceof Writer) { result = new StreamResult((Writer) out); } else { return; } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); Properties properties = transformer.getOutputProperties(); properties.setProperty(OutputKeys.ENCODING, "UTF-8"); properties.setProperty(OutputKeys.METHOD, "xml"); properties.setProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperties(properties); DOMSource source = new DOMSource(node); transformer.transform(source, result); } /** * Get the name Section of the nodes * * @param obj * @return * @throws Exception */ private Section getNodesName(Object obj) throws Exception { Section ss = new Section(); if (obj == null) { return ss; } Node nd = null; if (obj instanceof NodeList) { NodeList nl = (NodeList) obj; for (int i = 0; i < nl.getLength(); i++) { nd = nl.item(i); if (nd.getNodeType() != Node.ELEMENT_NODE) { continue; } ss.unionSection(nd.getNodeName()); } } if (obj instanceof NamedNodeMap) { NamedNodeMap nnm = (NamedNodeMap) obj; for (int i = 0; i < nnm.getLength(); i++) { nd = nnm.item(i); ss.unionSection(nd.getNodeName()); } } return ss; } /** * Locate node among nodes * * @param obj * NodeList or NamedNodeMap * @param nodeName * Node name * @return * @throws Exception */ private Node locateNode(Object obj, String nodeName) throws Exception { int i = 0, j = 0; String sTmp; Node tmpNode = null; NodeList nl; NamedNodeMap nnm; if (obj instanceof NodeList) { nl = (NodeList) obj; i = nl.getLength(); for (j = 0; j < i; j++) { tmpNode = nl.item(j); sTmp = tmpNode.getNodeName(); if (sTmp.equalsIgnoreCase(nodeName)) { break; } } } if (obj instanceof NamedNodeMap) { nnm = (NamedNodeMap) obj; i = nnm.getLength(); for (j = 0; j < i; j++) { tmpNode = nnm.item(j); sTmp = tmpNode.getNodeName(); if (sTmp.equalsIgnoreCase(nodeName)) { break; } } } if (j == i) { throw new Exception(mm.getMessage("xmlfile.falsenodename", xmlFile, nodeName)); } return tmpNode; } /** * Get terminal node * * @param path * Node path * @param type * Constants defined in org.w3c.dom.Node * @return * @throws Exception */ private Node getTerminalNode(String path, short type) throws Exception { Node tmpNode = null; String sNode, sLast; int i; if (path == null) { throw new Exception(mm.getMessage("xmlfile.nullpath1", xmlFile)); } i = path.lastIndexOf('/'); if (i == -1) { if (path.length() == 0) { return xmlDocument; } sNode = path; if (type == Node.ELEMENT_NODE) { tmpNode = locateNode(xmlDocument.getChildNodes(), sNode); } } else { sLast = path.substring(i + 1); path = path.substring(0, i); StringTokenizer st = new StringTokenizer(path, "/"); NodeList childNodes = xmlDocument.getChildNodes(); while (st.hasMoreTokens()) { sNode = st.nextToken(); tmpNode = locateNode(childNodes, sNode); if (tmpNode == null) { throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile, path)); } childNodes = tmpNode.getChildNodes(); } if (type == Node.ELEMENT_NODE) { tmpNode = locateNode(tmpNode.getChildNodes(), sLast); } else { tmpNode = locateNode(tmpNode.getAttributes(), sLast); } } if (tmpNode == null) { throw new Exception(mm.getMessage("xmlfile.notexistpath", xmlFile, path)); } return tmpNode; } /** * Is the legal XML name * * @param input * Node name * @return */ public static boolean isLegalXmlName(String input) { if (input == null || input.length() == 0) { return false; } return true; } /** * ����XML * @param is * @return * @throws Exception */ public static Document parseXml(InputStream is) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); return docBuilder.parse(is); } /** * ������ȡ�ӽڵ� * @param parent * @param childName * @return */ public static Element getChild(Node parent, String childName) { NodeList list = parent.getChildNodes(); if (list == null) { return null; } Node node; for (int i = 0; i < list.getLength(); i++) { node = list.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { if (childName.equalsIgnoreCase(node.getNodeName())) { return (Element) node; } } } return null; } /** * ������ȡ����ӽڵ� * @param parent * @param childName * @return */ public static List<Element> getChildren(Node parent, String childName) { NodeList list = parent.getChildNodes(); if (list == null) { return null; } List<Element> childList = new ArrayList<Element>(); Node node; for (int i = 0; i < list.getLength(); i++) { node = list.item(i); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { if (childName.equalsIgnoreCase(node.getNodeName())) { childList.add((Element) node); } } } if (childList.isEmpty()) return null; return childList; }}
|
data/java/10006.java
DELETED
@@ -1,476 +0,0 @@
|
|
1 |
-
package com.scudata.parallel;
|
2 |
-
|
3 |
-
import java.io.ByteArrayInputStream;
|
4 |
-
import java.io.ByteArrayOutputStream;
|
5 |
-
import java.io.InputStream;
|
6 |
-
import java.io.OutputStream;
|
7 |
-
import java.util.ArrayList;
|
8 |
-
import java.util.List;
|
9 |
-
|
10 |
-
import javax.xml.parsers.DocumentBuilder;
|
11 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
12 |
-
import javax.xml.transform.Result;
|
13 |
-
import javax.xml.transform.stream.StreamResult;
|
14 |
-
|
15 |
-
import org.w3c.dom.Document;
|
16 |
-
import org.w3c.dom.Node;
|
17 |
-
import org.w3c.dom.NodeList;
|
18 |
-
import org.xml.sax.SAXException;
|
19 |
-
|
20 |
-
import com.scudata.app.config.ConfigConsts;
|
21 |
-
import com.scudata.app.config.ConfigWriter;
|
22 |
-
import com.scudata.common.Logger;
|
23 |
-
import com.scudata.common.MessageManager;
|
24 |
-
import com.scudata.common.StringUtils;
|
25 |
-
import com.scudata.parallel.XmlUtil;
|
26 |
-
import com.scudata.resources.ParallelMessage;
|
27 |
-
|
28 |
-
/**
|
29 |
-
* �ֻ�������
|
30 |
-
* @author Joancy
|
31 |
-
*
|
32 |
-
*/
|
33 |
-
public class UnitConfig extends ConfigWriter {
|
34 |
-
// version 3
|
35 |
-
private int tempTimeOut = 12; // ��ʱ�ļ����ʱ�䣬��Ϊ��λ��0Ϊ��������λ����Сʱ��
|
36 |
-
private int proxyTimeOut = 12; // �ļ��Լ��α����Ĺ���ʱ�䣬��Ϊ��λ��0Ϊ��������λ����Сʱ��
|
37 |
-
private int interval = 30 * 60; // �����������ʱ�ļ����ڵ�ʱ������0Ϊ�������ڡ���λ��
|
38 |
-
private int backlog = 10; // ������������ӣ�����ϵͳȱʡ���Ϊ50������Χ1��50
|
39 |
-
boolean autoStart=false;
|
40 |
-
private List<Host> hosts = null;
|
41 |
-
|
42 |
-
// �ͻ��˰�����
|
43 |
-
private boolean checkClient = false;
|
44 |
-
private List<String> enabledClientsStart = null;
|
45 |
-
private List<String> enabledClientsEnd = null;
|
46 |
-
|
47 |
-
MessageManager mm = ParallelMessage.get();
|
48 |
-
|
49 |
-
/**
|
50 |
-
* �������ļ�������������Ϣ
|
51 |
-
* @param is �������
|
52 |
-
* @throws Exception ���س���ʱ�׳��쳣
|
53 |
-
*/
|
54 |
-
public void load(InputStream is) throws Exception {
|
55 |
-
load(is, true);
|
56 |
-
}
|
57 |
-
|
58 |
-
/**
|
59 |
-
* �������ļ����ֽ����ݼ���������Ϣ
|
60 |
-
* @param buf �����ļ��ֽ�����
|
61 |
-
* @throws Exception ���س����׳��쳣
|
62 |
-
*/
|
63 |
-
public void load(byte[] buf) throws Exception {
|
64 |
-
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
|
65 |
-
load(bais, true);
|
66 |
-
bais.close();
|
67 |
-
}
|
68 |
-
|
69 |
-
/**
|
70 |
-
* ����ip��port����Host������Host��������hosts����
|
71 |
-
* @param hosts hosts����
|
72 |
-
* @param ip IP��ַ
|
73 |
-
* @param port �˿ں�
|
74 |
-
* @return ��ip��port����Host����
|
75 |
-
*/
|
76 |
-
public static Host getHost(List<Host> hosts, String ip, int port) {
|
77 |
-
Host h = null;
|
78 |
-
for (int i = 0, size = hosts.size(); i < size; i++) {
|
79 |
-
h = hosts.get(i);
|
80 |
-
if (h.getIp().equals(ip) && h.getPort()==port) {
|
81 |
-
return h;
|
82 |
-
}
|
83 |
-
}
|
84 |
-
h = new Host(ip,port);
|
85 |
-
hosts.add(h);
|
86 |
-
return h;
|
87 |
-
}
|
88 |
-
|
89 |
-
/**
|
90 |
-
* ���������������
|
91 |
-
* @param is �������
|
92 |
-
* @param showDebug �Ƿ����������õĵ�����Ϣ
|
93 |
-
* @throws Exception �ļ���ʽ�������׳��쳣
|
94 |
-
*/
|
95 |
-
public void load(InputStream is, boolean showDebug) throws Exception {
|
96 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
97 |
-
.newInstance();
|
98 |
-
|
99 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
100 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
101 |
-
// FIXED:
|
102 |
-
|
103 |
-
Document xmlDocument = docBuilder.parse(is);
|
104 |
-
NodeList nl = xmlDocument.getChildNodes();
|
105 |
-
Node root = null;
|
106 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
107 |
-
Node n = nl.item(i);
|
108 |
-
if (n.getNodeName().equalsIgnoreCase("Server")) {
|
109 |
-
root = n;
|
110 |
-
}
|
111 |
-
}
|
112 |
-
if (root == null) {
|
113 |
-
throw new Exception(mm.getMessage("UnitConfig.errorxml"));
|
114 |
-
}
|
115 |
-
String ver = XmlUtil.getAttribute(root, "Version");
|
116 |
-
if (ver==null || Integer.parseInt( ver )<3) {
|
117 |
-
throw new RuntimeException(mm.getMessage("UnitConfig.updateversion",UnitContext.UNIT_XML));
|
118 |
-
}
|
119 |
-
|
120 |
-
// version 3
|
121 |
-
// Server ����
|
122 |
-
Node subNode = XmlUtil.findSonNode(root, "tempTimeout");
|
123 |
-
String buf = XmlUtil.getNodeValue(subNode);
|
124 |
-
if (StringUtils.isValidString(buf)) {
|
125 |
-
tempTimeOut = Integer.parseInt(buf);
|
126 |
-
if (tempTimeOut > 0) {
|
127 |
-
if (showDebug)
|
128 |
-
Logger.debug("Using TempTimeOut=" + tempTimeOut
|
129 |
-
+ " hour(s).");
|
130 |
-
}
|
131 |
-
}
|
132 |
-
|
133 |
-
subNode = XmlUtil.findSonNode(root, "interval");
|
134 |
-
buf = XmlUtil.getNodeValue(subNode);
|
135 |
-
if (StringUtils.isValidString(buf)) {
|
136 |
-
int t = Integer.parseInt(buf);
|
137 |
-
if (t > 0)
|
138 |
-
interval = t;// ���ò���ȷʱ��ʹ��ȱʡ�����
|
139 |
-
}
|
140 |
-
|
141 |
-
subNode = XmlUtil.findSonNode(root, "backlog");
|
142 |
-
buf = XmlUtil.getNodeValue(subNode);
|
143 |
-
if (StringUtils.isValidString(buf)) {
|
144 |
-
int t = Integer.parseInt(buf);
|
145 |
-
if (t > 0)
|
146 |
-
backlog = t;
|
147 |
-
}
|
148 |
-
|
149 |
-
subNode = XmlUtil.findSonNode(root, "autostart");
|
150 |
-
buf = XmlUtil.getNodeValue(subNode);
|
151 |
-
if (StringUtils.isValidString(buf)) {
|
152 |
-
autoStart = new Boolean(buf);
|
153 |
-
}
|
154 |
-
|
155 |
-
subNode = XmlUtil.findSonNode(root, "proxyTimeout");
|
156 |
-
buf = XmlUtil.getNodeValue(subNode);
|
157 |
-
if (StringUtils.isValidString(buf)) {
|
158 |
-
proxyTimeOut = Integer.parseInt(buf);
|
159 |
-
if (proxyTimeOut > 0) {
|
160 |
-
if (showDebug)
|
161 |
-
Logger.debug("Using ProxyTimeOut=" + proxyTimeOut
|
162 |
-
+ " hour(s).");
|
163 |
-
}
|
164 |
-
}
|
165 |
-
|
166 |
-
Node nodeHosts = XmlUtil.findSonNode(root, "Hosts");
|
167 |
-
NodeList hostsList = nodeHosts.getChildNodes();
|
168 |
-
hosts = new ArrayList<Host>();
|
169 |
-
|
170 |
-
for (int i = 0; i < hostsList.getLength(); i++) {
|
171 |
-
Node xmlNode = hostsList.item(i);
|
172 |
-
if (!xmlNode.getNodeName().equalsIgnoreCase("Host")) {
|
173 |
-
continue;
|
174 |
-
}
|
175 |
-
buf = XmlUtil.getAttribute(xmlNode, "ip");
|
176 |
-
String sPort = XmlUtil.getAttribute(xmlNode, "port");
|
177 |
-
Host host = new Host(buf,Integer.parseInt(sPort));
|
178 |
-
|
179 |
-
buf = XmlUtil.getAttribute(xmlNode, "maxTaskNum");
|
180 |
-
if(StringUtils.isValidString(buf)){
|
181 |
-
host.setMaxTaskNum(Integer.parseInt(buf));
|
182 |
-
}
|
183 |
-
|
184 |
-
buf = XmlUtil.getAttribute(xmlNode, "preferredTaskNum");
|
185 |
-
if(StringUtils.isValidString(buf)){
|
186 |
-
host.setPreferredTaskNum(Integer.parseInt(buf));
|
187 |
-
}
|
188 |
-
|
189 |
-
hosts.add(host);
|
190 |
-
}// hosts
|
191 |
-
|
192 |
-
Node nodeECs = XmlUtil.findSonNode(root, "EnabledClients");
|
193 |
-
buf = XmlUtil.getAttribute(nodeECs, "check");
|
194 |
-
if (StringUtils.isValidString(buf)){
|
195 |
-
checkClient = new Boolean(buf);
|
196 |
-
}
|
197 |
-
|
198 |
-
NodeList ecList = nodeECs.getChildNodes();
|
199 |
-
enabledClientsStart = new ArrayList<String>();
|
200 |
-
enabledClientsEnd = new ArrayList<String>();
|
201 |
-
|
202 |
-
for (int i = 0; i < ecList.getLength(); i++) {
|
203 |
-
Node xmlNode = ecList.item(i);
|
204 |
-
if (!xmlNode.getNodeName().equalsIgnoreCase("Host"))
|
205 |
-
continue;
|
206 |
-
buf = XmlUtil.getAttribute(xmlNode, "start");
|
207 |
-
if (!StringUtils.isValidString(buf))
|
208 |
-
continue;
|
209 |
-
enabledClientsStart.add(buf);
|
210 |
-
buf = XmlUtil.getAttribute(xmlNode, "end");
|
211 |
-
enabledClientsEnd.add(buf);
|
212 |
-
}
|
213 |
-
}
|
214 |
-
|
215 |
-
/**
|
216 |
-
* �������ļ�ת��Ϊ�ֽ�����
|
217 |
-
* @return �ֽ�����
|
218 |
-
* @throws Exception ת������ʱ�׳��쳣
|
219 |
-
*/
|
220 |
-
public byte[] toFileBytes() throws Exception{
|
221 |
-
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
222 |
-
save(baos);
|
223 |
-
return baos.toByteArray();
|
224 |
-
}
|
225 |
-
|
226 |
-
/**
|
227 |
-
* �������ļ���Ϣ���浽�����out
|
228 |
-
* @param out �����
|
229 |
-
* @throws SAXException д����ʱ�׳��쳣
|
230 |
-
*/
|
231 |
-
public void save(OutputStream out) throws SAXException {
|
232 |
-
Result resultxml = new StreamResult(out);
|
233 |
-
handler.setResult(resultxml);
|
234 |
-
level = 0;
|
235 |
-
handler.startDocument();
|
236 |
-
// ���ø��ڵ�Ͱ汾
|
237 |
-
handler.startElement("", "", "SERVER", getAttributesImpl(new String[] {
|
238 |
-
ConfigConsts.VERSION, "3" }));
|
239 |
-
level = 1;
|
240 |
-
writeAttribute("TempTimeOut", tempTimeOut + "");
|
241 |
-
writeAttribute("Interval", interval + "");
|
242 |
-
writeAttribute("Backlog", backlog + "");
|
243 |
-
writeAttribute("AutoStart", autoStart + "");
|
244 |
-
writeAttribute("ProxyTimeOut", proxyTimeOut + "");
|
245 |
-
|
246 |
-
startElement("Hosts", null);
|
247 |
-
if (hosts != null) {
|
248 |
-
for (int i = 0, size = hosts.size(); i < size; i++) {
|
249 |
-
level = 2;
|
250 |
-
Host h = hosts.get(i);
|
251 |
-
startElement("Host", getAttributesImpl(new String[] { "ip",
|
252 |
-
h.ip,"port",h.port+"",
|
253 |
-
"maxTaskNum",h.maxTaskNum+"","preferredTaskNum",h.preferredTaskNum+""}));
|
254 |
-
endElement("Host");
|
255 |
-
}
|
256 |
-
level = 1;
|
257 |
-
endElement("Hosts");
|
258 |
-
} else {
|
259 |
-
endEmptyElement("Hosts");
|
260 |
-
}
|
261 |
-
|
262 |
-
level = 1;
|
263 |
-
startElement("EnabledClients", getAttributesImpl(new String[] { "check",
|
264 |
-
checkClient+"" }));
|
265 |
-
if (enabledClientsStart != null) {
|
266 |
-
level = 2;
|
267 |
-
for (int i = 0, size = enabledClientsStart.size(); i < size; i++) {
|
268 |
-
String start = enabledClientsStart.get(i);
|
269 |
-
String end = enabledClientsEnd.get(i);
|
270 |
-
startElement("Host", getAttributesImpl(new String[] {
|
271 |
-
"start",start,"end",end }));
|
272 |
-
endElement("Host");
|
273 |
-
}
|
274 |
-
level = 1;
|
275 |
-
endElement("EnabledClients");
|
276 |
-
} else {
|
277 |
-
endEmptyElement("EnabledClients");
|
278 |
-
}
|
279 |
-
|
280 |
-
handler.endElement("", "", "SERVER");
|
281 |
-
// �ĵ�����,ͬ��������
|
282 |
-
handler.endDocument();
|
283 |
-
}
|
284 |
-
|
285 |
-
/**
|
286 |
-
* ��ȡ��ʱ�ļ���ʱʱ�䣬��λͳһΪСʱ
|
287 |
-
* ����ͬgetTempTimeOutHour���������ڼ���
|
288 |
-
* @return ��ʱʱ��
|
289 |
-
*/
|
290 |
-
public int getTempTimeOut() {
|
291 |
-
return tempTimeOut;
|
292 |
-
}
|
293 |
-
|
294 |
-
/**
|
295 |
-
* ��ȡ��ʱ�ļ���ʱʱ�䣬��λСʱ
|
296 |
-
* @return ��ʱʱ��
|
297 |
-
*/
|
298 |
-
public int getTempTimeOutHour() {
|
299 |
-
return tempTimeOut;
|
300 |
-
}
|
301 |
-
|
302 |
-
/**
|
303 |
-
* ������ʱ�ļ���ʱʱ��
|
304 |
-
* @param tempTimeOut ʱ��
|
305 |
-
*/
|
306 |
-
public void setTempTimeOut(int tempTimeOut) {
|
307 |
-
this.tempTimeOut = tempTimeOut;
|
308 |
-
}
|
309 |
-
|
310 |
-
/**
|
311 |
-
* ��Сʱ���ó�ʱʱ�䣬����ͬsetTempTimeOut
|
312 |
-
* �������ڴ������
|
313 |
-
* @param tempTimeOutHour ʱ��
|
314 |
-
*/
|
315 |
-
public void setTempTimeOutHour(int tempTimeOutHour) {
|
316 |
-
this.tempTimeOut = tempTimeOutHour;
|
317 |
-
}
|
318 |
-
|
319 |
-
public int getProxyTimeOut() {
|
320 |
-
return proxyTimeOut;
|
321 |
-
}
|
322 |
-
|
323 |
-
public boolean isAutoStart(){
|
324 |
-
return autoStart;
|
325 |
-
}
|
326 |
-
public void setAutoStart(boolean as){
|
327 |
-
autoStart = as;
|
328 |
-
}
|
329 |
-
/**
|
330 |
-
* ȡ�����������ʱ�䣨��λΪСʱ��
|
331 |
-
* @return ����ʱʱ��
|
332 |
-
*/
|
333 |
-
public int getProxyTimeOutHour() {
|
334 |
-
return proxyTimeOut;
|
335 |
-
}
|
336 |
-
|
337 |
-
/**
|
338 |
-
* ���ô���ʱʱ��
|
339 |
-
* @param proxyTimeOut ��ʱʱ��
|
340 |
-
*/
|
341 |
-
public void setProxyTimeOut(int proxyTimeOut) {
|
342 |
-
this.proxyTimeOut = proxyTimeOut;
|
343 |
-
}
|
344 |
-
|
345 |
-
/**
|
346 |
-
* ����ͬsetProxyTimeOut
|
347 |
-
* @param proxyTimeOutHour
|
348 |
-
*/
|
349 |
-
public void setProxyTimeOutHour(int proxyTimeOutHour) {
|
350 |
-
this.proxyTimeOut = proxyTimeOutHour;// * 3600;
|
351 |
-
}
|
352 |
-
|
353 |
-
/**
|
354 |
-
* ����Ƿ�ʱ��ʱ����(��λΪ��)
|
355 |
-
* @return ʱ����
|
356 |
-
*/
|
357 |
-
public int getInterval() {
|
358 |
-
return interval;
|
359 |
-
}
|
360 |
-
|
361 |
-
/**
|
362 |
-
* ���ü�鳬ʱ��ʱ����
|
363 |
-
* @param interval ʱ����
|
364 |
-
*/
|
365 |
-
public void setInterval(int interval) {
|
366 |
-
this.interval = interval;
|
367 |
-
}
|
368 |
-
|
369 |
-
/**
|
370 |
-
* ��ȡ����˵IJ���������
|
371 |
-
* @return ������
|
372 |
-
*/
|
373 |
-
public int getBacklog() {
|
374 |
-
return backlog;
|
375 |
-
}
|
376 |
-
|
377 |
-
/**
|
378 |
-
* ���÷���������������
|
379 |
-
* @param backlog ����������
|
380 |
-
*/
|
381 |
-
public void setBacklog(int backlog) {
|
382 |
-
this.backlog = backlog;
|
383 |
-
}
|
384 |
-
|
385 |
-
/**
|
386 |
-
* �г���ǰ�ֻ��µ����н��̵�ַ
|
387 |
-
* @return ���������б�
|
388 |
-
*/
|
389 |
-
public List<Host> getHosts() {
|
390 |
-
return hosts;
|
391 |
-
}
|
392 |
-
|
393 |
-
/**
|
394 |
-
* ���ý��������б�
|
395 |
-
* @param hosts ���������б�
|
396 |
-
*/
|
397 |
-
public void setHosts(List<Host> hosts) {
|
398 |
-
this.hosts = hosts;
|
399 |
-
}
|
400 |
-
|
401 |
-
/**
|
402 |
-
* �Ƿ�У��ͻ���
|
403 |
-
* @return
|
404 |
-
*/
|
405 |
-
public boolean isCheckClients() {
|
406 |
-
return checkClient;
|
407 |
-
}
|
408 |
-
|
409 |
-
public void setCheckClients(boolean b) {
|
410 |
-
this.checkClient = b;
|
411 |
-
}
|
412 |
-
|
413 |
-
public List<String> getEnabledClientsStart() {
|
414 |
-
return enabledClientsStart;
|
415 |
-
}
|
416 |
-
|
417 |
-
public void setEnabledClientsStart(List<String> enHosts) {
|
418 |
-
this.enabledClientsStart = enHosts;
|
419 |
-
}
|
420 |
-
|
421 |
-
public List<String> getEnabledClientsEnd() {
|
422 |
-
return enabledClientsEnd;
|
423 |
-
}
|
424 |
-
|
425 |
-
public void setEnabledClientsEnd(List<String> enHosts) {
|
426 |
-
this.enabledClientsEnd = enHosts;
|
427 |
-
}
|
428 |
-
|
429 |
-
|
430 |
-
public static class Host {
|
431 |
-
// �ʺ���ҵ��ȱʡΪCPU����,���ܱ�����
|
432 |
-
int preferredTaskNum = Runtime.getRuntime().availableProcessors();
|
433 |
-
|
434 |
-
int maxTaskNum = preferredTaskNum*2;
|
435 |
-
String ip;
|
436 |
-
int port;
|
437 |
-
|
438 |
-
public Host(String ip, int port) {
|
439 |
-
this.ip = ip;
|
440 |
-
this.port = port;
|
441 |
-
}
|
442 |
-
|
443 |
-
public String getIp() {
|
444 |
-
return ip;
|
445 |
-
}
|
446 |
-
|
447 |
-
public int getPort(){
|
448 |
-
return port;
|
449 |
-
}
|
450 |
-
|
451 |
-
public int getMaxTaskNum(){
|
452 |
-
return maxTaskNum;
|
453 |
-
}
|
454 |
-
public void setMaxTaskNum(int max){
|
455 |
-
maxTaskNum = max;
|
456 |
-
}
|
457 |
-
|
458 |
-
public int getPreferredTaskNum(){
|
459 |
-
return preferredTaskNum;
|
460 |
-
}
|
461 |
-
public void setPreferredTaskNum(int num){
|
462 |
-
preferredTaskNum = num;
|
463 |
-
}
|
464 |
-
|
465 |
-
public String toString() {
|
466 |
-
StringBuffer sb = new StringBuffer();
|
467 |
-
sb.append(ip);
|
468 |
-
sb.append(":[");
|
469 |
-
sb.append(port);
|
470 |
-
sb.append("]");
|
471 |
-
return sb.toString();
|
472 |
-
}
|
473 |
-
|
474 |
-
}
|
475 |
-
|
476 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10006.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.parallel;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Result;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import com.scudata.app.config.ConfigConsts;import com.scudata.app.config.ConfigWriter;import com.scudata.common.Logger;import com.scudata.common.MessageManager;import com.scudata.common.StringUtils;import com.scudata.parallel.XmlUtil;import com.scudata.resources.ParallelMessage;/** * �ֻ������� * @author Joancy * */public class UnitConfig extends ConfigWriter { // version 3 private int tempTimeOut = 12; // ��ʱ�ļ����ʱ�䣬��Ϊ��λ��0Ϊ��������λ����Сʱ�� private int proxyTimeOut = 12; // �ļ��Լ��α����Ĺ���ʱ�䣬��Ϊ��λ��0Ϊ��������λ����Сʱ�� private int interval = 30 * 60; // �����������ʱ�ļ����ڵ�ʱ������0Ϊ�������ڡ���λ�� private int backlog = 10; // ������������ӣ�����ϵͳȱʡ���Ϊ50������Χ1��50 boolean autoStart=false; private List<Host> hosts = null; // �ͻ��˰����� private boolean checkClient = false; private List<String> enabledClientsStart = null; private List<String> enabledClientsEnd = null; MessageManager mm = ParallelMessage.get(); /** * �������ļ�������������Ϣ * @param is �����ļ��� * @throws Exception ���س���ʱ�׳��쳣 */ public void load(InputStream is) throws Exception { load(is, true); } /** * �������ļ����ֽ����ݼ���������Ϣ * @param buf �����ļ��ֽ����� * @throws Exception ���س����׳��쳣 */ public void load(byte[] buf) throws Exception { ByteArrayInputStream bais = new ByteArrayInputStream(buf); load(bais, true); bais.close(); } /** * ����ip��port����Host������Host����ά����hosts���� * @param hosts hosts���� * @param ip IP��ַ * @param port �˿ں� * @return ��ip��port����Host���� */ public static Host getHost(List<Host> hosts, String ip, int port) { Host h = null; for (int i = 0, size = hosts.size(); i < size; i++) { h = hosts.get(i); if (h.getIp().equals(ip) && h.getPort()==port) { return h; } } h = new Host(ip,port); hosts.add(h); return h; } /** * ���������ļ������� * @param is �����ļ��� * @param showDebug �Ƿ����������õĵ�����Ϣ * @throws Exception �ļ���ʽ�������׳��쳣 */ public void load(InputStream is, boolean showDebug) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: Document xmlDocument = docBuilder.parse(is); NodeList nl = xmlDocument.getChildNodes(); Node root = null; for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeName().equalsIgnoreCase("Server")) { root = n; } } if (root == null) { throw new Exception(mm.getMessage("UnitConfig.errorxml")); } String ver = XmlUtil.getAttribute(root, "Version"); if (ver==null || Integer.parseInt( ver )<3) { throw new RuntimeException(mm.getMessage("UnitConfig.updateversion",UnitContext.UNIT_XML)); } // version 3 // Server ���� Node subNode = XmlUtil.findSonNode(root, "tempTimeout"); String buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { tempTimeOut = Integer.parseInt(buf); if (tempTimeOut > 0) { if (showDebug) Logger.debug("Using TempTimeOut=" + tempTimeOut + " hour(s)."); } } subNode = XmlUtil.findSonNode(root, "interval"); buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { int t = Integer.parseInt(buf); if (t > 0) interval = t;// ���ò���ȷʱ��ʹ��ȱʡ����� } subNode = XmlUtil.findSonNode(root, "backlog"); buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { int t = Integer.parseInt(buf); if (t > 0) backlog = t; } subNode = XmlUtil.findSonNode(root, "autostart"); buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { autoStart = new Boolean(buf); } subNode = XmlUtil.findSonNode(root, "proxyTimeout"); buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { proxyTimeOut = Integer.parseInt(buf); if (proxyTimeOut > 0) { if (showDebug) Logger.debug("Using ProxyTimeOut=" + proxyTimeOut + " hour(s)."); } } Node nodeHosts = XmlUtil.findSonNode(root, "Hosts"); NodeList hostsList = nodeHosts.getChildNodes(); hosts = new ArrayList<Host>(); for (int i = 0; i < hostsList.getLength(); i++) { Node xmlNode = hostsList.item(i); if (!xmlNode.getNodeName().equalsIgnoreCase("Host")) { continue; } buf = XmlUtil.getAttribute(xmlNode, "ip"); String sPort = XmlUtil.getAttribute(xmlNode, "port"); Host host = new Host(buf,Integer.parseInt(sPort)); buf = XmlUtil.getAttribute(xmlNode, "maxTaskNum"); if(StringUtils.isValidString(buf)){ host.setMaxTaskNum(Integer.parseInt(buf)); } buf = XmlUtil.getAttribute(xmlNode, "preferredTaskNum"); if(StringUtils.isValidString(buf)){ host.setPreferredTaskNum(Integer.parseInt(buf)); } hosts.add(host); }// hosts Node nodeECs = XmlUtil.findSonNode(root, "EnabledClients"); buf = XmlUtil.getAttribute(nodeECs, "check"); if (StringUtils.isValidString(buf)){ checkClient = new Boolean(buf); } NodeList ecList = nodeECs.getChildNodes(); enabledClientsStart = new ArrayList<String>(); enabledClientsEnd = new ArrayList<String>(); for (int i = 0; i < ecList.getLength(); i++) { Node xmlNode = ecList.item(i); if (!xmlNode.getNodeName().equalsIgnoreCase("Host")) continue; buf = XmlUtil.getAttribute(xmlNode, "start"); if (!StringUtils.isValidString(buf)) continue; enabledClientsStart.add(buf); buf = XmlUtil.getAttribute(xmlNode, "end"); enabledClientsEnd.add(buf); } } /** * �������ļ�ת��Ϊ�ֽ����� * @return �ֽ����� * @throws Exception ת������ʱ�׳��쳣 */ public byte[] toFileBytes() throws Exception{ ByteArrayOutputStream baos = new ByteArrayOutputStream(); save(baos); return baos.toByteArray(); } /** * �������ļ���Ϣ���浽�����out * @param out ����� * @throws SAXException д����ʱ�׳��쳣 */ public void save(OutputStream out) throws SAXException { Result resultxml = new StreamResult(out); handler.setResult(resultxml); level = 0; handler.startDocument(); // ���ø��ڵ�Ͱ汾 handler.startElement("", "", "SERVER", getAttributesImpl(new String[] { ConfigConsts.VERSION, "3" })); level = 1; writeAttribute("TempTimeOut", tempTimeOut + ""); writeAttribute("Interval", interval + ""); writeAttribute("Backlog", backlog + ""); writeAttribute("AutoStart", autoStart + ""); writeAttribute("ProxyTimeOut", proxyTimeOut + ""); startElement("Hosts", null); if (hosts != null) { for (int i = 0, size = hosts.size(); i < size; i++) { level = 2; Host h = hosts.get(i); startElement("Host", getAttributesImpl(new String[] { "ip", h.ip,"port",h.port+"", "maxTaskNum",h.maxTaskNum+"","preferredTaskNum",h.preferredTaskNum+""})); endElement("Host"); } level = 1; endElement("Hosts"); } else { endEmptyElement("Hosts"); } level = 1; startElement("EnabledClients", getAttributesImpl(new String[] { "check", checkClient+"" })); if (enabledClientsStart != null) { level = 2; for (int i = 0, size = enabledClientsStart.size(); i < size; i++) { String start = enabledClientsStart.get(i); String end = enabledClientsEnd.get(i); startElement("Host", getAttributesImpl(new String[] { "start",start,"end",end })); endElement("Host"); } level = 1; endElement("EnabledClients"); } else { endEmptyElement("EnabledClients"); } handler.endElement("", "", "SERVER"); // �ĵ�����,ͬ�������� handler.endDocument(); } /** * ��ȡ��ʱ�ļ���ʱʱ�䣬��λͳһΪСʱ * ����ͬgetTempTimeOutHour���������ڼ��� * @return ��ʱʱ�� */ public int getTempTimeOut() { return tempTimeOut; } /** * ��ȡ��ʱ�ļ���ʱʱ�䣬��λСʱ * @return ��ʱʱ�� */ public int getTempTimeOutHour() { return tempTimeOut; } /** * ������ʱ�ļ���ʱʱ�� * @param tempTimeOut ʱ�� */ public void setTempTimeOut(int tempTimeOut) { this.tempTimeOut = tempTimeOut; } /** * ��Сʱ���ó�ʱʱ�䣬����ͬsetTempTimeOut * �������ڴ������ * @param tempTimeOutHour ʱ�� */ public void setTempTimeOutHour(int tempTimeOutHour) { this.tempTimeOut = tempTimeOutHour; } public int getProxyTimeOut() { return proxyTimeOut; } public boolean isAutoStart(){ return autoStart; } public void setAutoStart(boolean as){ autoStart = as; } /** * ȡ�����������ʱ�䣨��λΪСʱ�� * @return ����ʱʱ�� */ public int getProxyTimeOutHour() { return proxyTimeOut; } /** * ���ô���ʱʱ�� * @param proxyTimeOut ��ʱʱ�� */ public void setProxyTimeOut(int proxyTimeOut) { this.proxyTimeOut = proxyTimeOut; } /** * ����ͬsetProxyTimeOut * @param proxyTimeOutHour */ public void setProxyTimeOutHour(int proxyTimeOutHour) { this.proxyTimeOut = proxyTimeOutHour;// * 3600; } /** * ����Ƿ�ʱ��ʱ����(��λΪ��) * @return ʱ���� */ public int getInterval() { return interval; } /** * ���ü�鳬ʱ��ʱ���� * @param interval ʱ���� */ public void setInterval(int interval) { this.interval = interval; } /** * ��ȡ����˵IJ��������� * @return ������ */ public int getBacklog() { return backlog; } /** * ���÷��������������� * @param backlog ���������� */ public void setBacklog(int backlog) { this.backlog = backlog; } /** * �г���ǰ�ֻ��µ����н��̵�ַ * @return ���������б� */ public List<Host> getHosts() { return hosts; } /** * ���ý��������б� * @param hosts ���������б� */ public void setHosts(List<Host> hosts) { this.hosts = hosts; } /** * �Ƿ�У��ͻ��� * @return */ public boolean isCheckClients() { return checkClient; } public void setCheckClients(boolean b) { this.checkClient = b; } public List<String> getEnabledClientsStart() { return enabledClientsStart; } public void setEnabledClientsStart(List<String> enHosts) { this.enabledClientsStart = enHosts; } public List<String> getEnabledClientsEnd() { return enabledClientsEnd; } public void setEnabledClientsEnd(List<String> enHosts) { this.enabledClientsEnd = enHosts; } public static class Host {// �ʺ���ҵ��ȱʡΪCPU����,���ܱ����� int preferredTaskNum = Runtime.getRuntime().availableProcessors(); int maxTaskNum = preferredTaskNum*2; String ip; int port; public Host(String ip, int port) { this.ip = ip; this.port = port; } public String getIp() { return ip; } public int getPort(){ return port; } public int getMaxTaskNum(){ return maxTaskNum; } public void setMaxTaskNum(int max){ maxTaskNum = max; } public int getPreferredTaskNum(){ return preferredTaskNum; } public void setPreferredTaskNum(int num){ preferredTaskNum = num; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(ip); sb.append(":["); sb.append(port); sb.append("]"); return sb.toString(); } }}
|
data/java/10007.java
DELETED
@@ -1,258 +0,0 @@
|
|
1 |
-
package com.scudata.server.http;
|
2 |
-
|
3 |
-
import java.io.File;
|
4 |
-
import java.io.InputStream;
|
5 |
-
import java.io.OutputStream;
|
6 |
-
import java.util.ArrayList;
|
7 |
-
|
8 |
-
import javax.xml.parsers.DocumentBuilder;
|
9 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
10 |
-
import javax.xml.transform.Result;
|
11 |
-
import javax.xml.transform.stream.StreamResult;
|
12 |
-
|
13 |
-
import org.w3c.dom.Document;
|
14 |
-
import org.w3c.dom.Node;
|
15 |
-
import org.w3c.dom.NodeList;
|
16 |
-
import org.xml.sax.SAXException;
|
17 |
-
|
18 |
-
import com.scudata.app.config.ConfigConsts;
|
19 |
-
import com.scudata.app.config.ConfigWriter;
|
20 |
-
import com.scudata.common.ArgumentTokenizer;
|
21 |
-
import com.scudata.common.Logger;
|
22 |
-
import com.scudata.common.MessageManager;
|
23 |
-
import com.scudata.common.StringUtils;
|
24 |
-
import com.scudata.common.Logger.FileHandler;
|
25 |
-
import com.scudata.dm.Env;
|
26 |
-
import com.scudata.parallel.UnitClient;
|
27 |
-
import com.scudata.parallel.UnitContext;
|
28 |
-
import com.scudata.parallel.XmlUtil;
|
29 |
-
import com.scudata.resources.ParallelMessage;
|
30 |
-
import com.scudata.server.unit.UnitServer;
|
31 |
-
|
32 |
-
import sun.net.util.IPAddressUtil;
|
33 |
-
|
34 |
-
/**
|
35 |
-
* Http�������Ļ������ò�����
|
36 |
-
*
|
37 |
-
* @author Joancy
|
38 |
-
*
|
39 |
-
*/
|
40 |
-
public class HttpContext extends ConfigWriter {
|
41 |
-
public static final String HTTP_CONFIG_FILE = "HttpServer.xml";
|
42 |
-
public static String dfxHome;
|
43 |
-
|
44 |
-
private String host = UnitContext.getDefaultHost();// "127.0.0.1";
|
45 |
-
private int port = 8508;
|
46 |
-
private int maxLinks = 50;
|
47 |
-
private boolean autoStart=false;
|
48 |
-
|
49 |
-
private ArrayList<String> sapPath = new ArrayList<String>();
|
50 |
-
|
51 |
-
static MessageManager mm = ParallelMessage.get();
|
52 |
-
|
53 |
-
/**
|
54 |
-
* ���캯��
|
55 |
-
* @param showException �Ƿ����쳣��ӡ������̨���������
|
56 |
-
*/
|
57 |
-
public HttpContext(boolean showException) {
|
58 |
-
try {
|
59 |
-
InputStream inputStream = UnitContext
|
60 |
-
.getUnitInputStream(HTTP_CONFIG_FILE);
|
61 |
-
if (inputStream != null) {
|
62 |
-
load(inputStream);
|
63 |
-
}
|
64 |
-
} catch (Exception x) {
|
65 |
-
if (showException) {
|
66 |
-
x.printStackTrace();
|
67 |
-
}
|
68 |
-
}
|
69 |
-
}
|
70 |
-
|
71 |
-
/**
|
72 |
-
* ��ȡȱʡ�ķ���url��ַ
|
73 |
-
* @return url��ַ
|
74 |
-
*/
|
75 |
-
public String getDefaultUrl() {
|
76 |
-
String tmp = host;
|
77 |
-
if (IPAddressUtil.isIPv6LiteralAddress(host)) {
|
78 |
-
int percentIndex = host.indexOf('%');
|
79 |
-
if (percentIndex > 0) {
|
80 |
-
tmp = tmp.substring(0, percentIndex);
|
81 |
-
}
|
82 |
-
tmp = "[" + tmp + "]";
|
83 |
-
}
|
84 |
-
|
85 |
-
return "http://" + tmp + ":" + port;
|
86 |
-
}
|
87 |
-
|
88 |
-
/**
|
89 |
-
* �������ļ������������ػ�������
|
90 |
-
* @param is �����������
|
91 |
-
* @throws Exception ��ʽ����ʱ�׳��쳣
|
92 |
-
*/
|
93 |
-
public void load(InputStream is) throws Exception {
|
94 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
95 |
-
.newInstance();
|
96 |
-
|
97 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
98 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
99 |
-
// FIXED:
|
100 |
-
|
101 |
-
Document xmlDocument = docBuilder.parse(is);
|
102 |
-
NodeList nl = xmlDocument.getChildNodes();
|
103 |
-
Node root = null;
|
104 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
105 |
-
Node n = nl.item(i);
|
106 |
-
if (n.getNodeName().equalsIgnoreCase("Server")) {
|
107 |
-
root = n;
|
108 |
-
}
|
109 |
-
}
|
110 |
-
if (root == null) {
|
111 |
-
throw new Exception(mm.getMessage("UnitConfig.errorxml"));
|
112 |
-
}
|
113 |
-
|
114 |
-
// Server ����
|
115 |
-
String buf = XmlUtil.getAttribute(root, "host");
|
116 |
-
if (StringUtils.isValidString(buf)) {
|
117 |
-
host = buf;
|
118 |
-
}
|
119 |
-
|
120 |
-
buf = XmlUtil.getAttribute(root, "port");
|
121 |
-
if (StringUtils.isValidString(buf)) {
|
122 |
-
port = Integer.parseInt(buf);
|
123 |
-
}
|
124 |
-
|
125 |
-
buf = XmlUtil.getAttribute(root, "autostart");
|
126 |
-
if (StringUtils.isValidString(buf)) {
|
127 |
-
autoStart = Boolean.parseBoolean(buf);
|
128 |
-
}
|
129 |
-
|
130 |
-
// �̶������־������̨�� �� start.home/nodes/[ip_port]/log Ŀ¼��
|
131 |
-
String home = UnitServer.getHome();
|
132 |
-
String file = "http/" + UnitClient.getHostPath(host) + "_" + port + "/log/log.txt";
|
133 |
-
File f = new File(home, file);
|
134 |
-
File fp = f.getParentFile();
|
135 |
-
if (!fp.exists()) {
|
136 |
-
fp.mkdirs();
|
137 |
-
}
|
138 |
-
String logFile = f.getAbsolutePath();
|
139 |
-
FileHandler lfh = Logger.newFileHandler(logFile);
|
140 |
-
Logger.addFileHandler(lfh);
|
141 |
-
|
142 |
-
buf = XmlUtil.getAttribute(root, "parallelNum");
|
143 |
-
if (StringUtils.isValidString(buf)) {
|
144 |
-
}
|
145 |
-
|
146 |
-
buf = XmlUtil.getAttribute(root, "maxlinks");
|
147 |
-
if (StringUtils.isValidString(buf)) {
|
148 |
-
maxLinks = Integer.parseInt(buf);
|
149 |
-
}
|
150 |
-
|
151 |
-
String mp = Env.getMainPath();
|
152 |
-
if(!StringUtils.isValidString( mp )) {
|
153 |
-
Logger.info("Main path is empty.");
|
154 |
-
}else {
|
155 |
-
File main = new File( mp );
|
156 |
-
if( main.exists() ) {
|
157 |
-
String mainPath = main.getAbsolutePath();
|
158 |
-
addSubdir2Sappath( main, mainPath );
|
159 |
-
}
|
160 |
-
}
|
161 |
-
/*buf = XmlUtil.getAttribute(root, "sapPath");
|
162 |
-
if (StringUtils.isValidString(buf)) {
|
163 |
-
ArgumentTokenizer at = new ArgumentTokenizer(buf, ',');
|
164 |
-
while (at.hasMoreTokens()) {
|
165 |
-
sapPath.add(at.nextToken().trim());
|
166 |
-
}
|
167 |
-
}*/
|
168 |
-
}
|
169 |
-
|
170 |
-
private void addSubdir2Sappath( File main, String mainPath ) {
|
171 |
-
File[] fs = main.listFiles();
|
172 |
-
if(fs==null) {
|
173 |
-
return;
|
174 |
-
}
|
175 |
-
for( int i = 0; i < fs.length; i++ ) {
|
176 |
-
if( !fs[i].isDirectory() ) continue;
|
177 |
-
String path = fs[i].getAbsolutePath();
|
178 |
-
path = path.substring( mainPath.length() );
|
179 |
-
path = StringUtils.replace( path, "\\", "/" );
|
180 |
-
sapPath.add( path );
|
181 |
-
addSubdir2Sappath( fs[i], mainPath );
|
182 |
-
}
|
183 |
-
}
|
184 |
-
|
185 |
-
public void save(OutputStream out) throws SAXException {
|
186 |
-
Result resultxml = new StreamResult(out);
|
187 |
-
handler.setResult(resultxml);
|
188 |
-
level = 0;
|
189 |
-
handler.startDocument();
|
190 |
-
// ���ø��ڵ�Ͱ汾
|
191 |
-
String paths = "";
|
192 |
-
for (int i = 0; i < sapPath.size(); i++) {
|
193 |
-
if (paths.length() > 0)
|
194 |
-
paths += ",";
|
195 |
-
paths += sapPath.get(i);
|
196 |
-
}
|
197 |
-
handler.startElement("", "", "Server", getAttributesImpl(new String[] {
|
198 |
-
ConfigConsts.VERSION, "1", "host", host, "port", port + "", "autostart", autoStart + "",
|
199 |
-
"maxlinks", maxLinks + "", //parallelNum + "",
|
200 |
-
"sapPath", paths }));
|
201 |
-
|
202 |
-
handler.endElement("", "", "Server");
|
203 |
-
// �ĵ�����,ͬ��������
|
204 |
-
handler.endDocument();
|
205 |
-
}
|
206 |
-
|
207 |
-
public String getHost() {
|
208 |
-
return host;
|
209 |
-
}
|
210 |
-
|
211 |
-
public int getPort() {
|
212 |
-
return port;
|
213 |
-
}
|
214 |
-
|
215 |
-
public boolean isAutoStart() {
|
216 |
-
return autoStart;
|
217 |
-
}
|
218 |
-
|
219 |
-
public void setHost(String host) {
|
220 |
-
this.host = host;
|
221 |
-
}
|
222 |
-
|
223 |
-
public void setPort(int port) {
|
224 |
-
this.port = port;
|
225 |
-
}
|
226 |
-
|
227 |
-
public void setAutoStart(boolean as) {
|
228 |
-
this.autoStart = as;
|
229 |
-
}
|
230 |
-
|
231 |
-
// public int getParallelNum() {
|
232 |
-
// return parallelNum;
|
233 |
-
// }
|
234 |
-
//
|
235 |
-
// public void setParallelNum(int num) {
|
236 |
-
// this.parallelNum = num;
|
237 |
-
// }
|
238 |
-
|
239 |
-
public int getMaxLinks() {
|
240 |
-
return maxLinks;
|
241 |
-
}
|
242 |
-
|
243 |
-
public void setMaxLinks(int m) {
|
244 |
-
this.maxLinks = m;
|
245 |
-
}
|
246 |
-
|
247 |
-
public ArrayList<String> getSapPath() {
|
248 |
-
return sapPath;
|
249 |
-
}
|
250 |
-
|
251 |
-
public void setSapPath(ArrayList<String> paths) {
|
252 |
-
sapPath = paths;
|
253 |
-
}
|
254 |
-
|
255 |
-
public String toString() {
|
256 |
-
return host + ":" + port;
|
257 |
-
}
|
258 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10007.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.server.http;import java.io.File;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Result;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import com.scudata.app.config.ConfigConsts;import com.scudata.app.config.ConfigWriter;import com.scudata.common.ArgumentTokenizer;import com.scudata.common.Logger;import com.scudata.common.MessageManager;import com.scudata.common.StringUtils;import com.scudata.common.Logger.FileHandler;import com.scudata.dm.Env;import com.scudata.parallel.UnitClient;import com.scudata.parallel.UnitContext;import com.scudata.parallel.XmlUtil;import com.scudata.resources.ParallelMessage;import com.scudata.server.unit.UnitServer;import sun.net.util.IPAddressUtil;/** * Http�������Ļ������ò����� * * @author Joancy * */public class HttpContext extends ConfigWriter { public static final String HTTP_CONFIG_FILE = "HttpServer.xml"; public static String dfxHome; private String host = UnitContext.getDefaultHost();// "127.0.0.1"; private int port = 8508; private int maxLinks = 50; private boolean autoStart=false; private ArrayList<String> sapPath = new ArrayList<String>(); static MessageManager mm = ParallelMessage.get(); /** * ���캯�� * @param showException �Ƿ����쳣��ӡ������̨��������� */ public HttpContext(boolean showException) { try { InputStream inputStream = UnitContext .getUnitInputStream(HTTP_CONFIG_FILE); if (inputStream != null) { load(inputStream); } } catch (Exception x) { if (showException) { x.printStackTrace(); } } } /** * ��ȡȱʡ�ķ���url��ַ * @return url��ַ */ public String getDefaultUrl() { String tmp = host; if (IPAddressUtil.isIPv6LiteralAddress(host)) { int percentIndex = host.indexOf('%'); if (percentIndex > 0) { tmp = tmp.substring(0, percentIndex); } tmp = "[" + tmp + "]"; } return "http://" + tmp + ":" + port; } /** * �������ļ������������ػ������� * @param is �����ļ������� * @throws Exception ��ʽ����ʱ�׳��쳣 */ public void load(InputStream is) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: Document xmlDocument = docBuilder.parse(is); NodeList nl = xmlDocument.getChildNodes(); Node root = null; for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeName().equalsIgnoreCase("Server")) { root = n; } } if (root == null) { throw new Exception(mm.getMessage("UnitConfig.errorxml")); } // Server ���� String buf = XmlUtil.getAttribute(root, "host"); if (StringUtils.isValidString(buf)) { host = buf; } buf = XmlUtil.getAttribute(root, "port"); if (StringUtils.isValidString(buf)) { port = Integer.parseInt(buf); } buf = XmlUtil.getAttribute(root, "autostart"); if (StringUtils.isValidString(buf)) { autoStart = Boolean.parseBoolean(buf); } // �̶������־������̨�� �� start.home/nodes/[ip_port]/log Ŀ¼�� String home = UnitServer.getHome(); String file = "http/" + UnitClient.getHostPath(host) + "_" + port + "/log/log.txt"; File f = new File(home, file); File fp = f.getParentFile(); if (!fp.exists()) { fp.mkdirs(); } String logFile = f.getAbsolutePath(); FileHandler lfh = Logger.newFileHandler(logFile); Logger.addFileHandler(lfh); buf = XmlUtil.getAttribute(root, "parallelNum"); if (StringUtils.isValidString(buf)) { } buf = XmlUtil.getAttribute(root, "maxlinks"); if (StringUtils.isValidString(buf)) { maxLinks = Integer.parseInt(buf); } String mp = Env.getMainPath(); if(!StringUtils.isValidString( mp )) { Logger.info("Main path is empty."); }else { File main = new File( mp ); if( main.exists() ) { String mainPath = main.getAbsolutePath(); addSubdir2Sappath( main, mainPath ); } } /*buf = XmlUtil.getAttribute(root, "sapPath"); if (StringUtils.isValidString(buf)) { ArgumentTokenizer at = new ArgumentTokenizer(buf, ','); while (at.hasMoreTokens()) { sapPath.add(at.nextToken().trim()); } }*/ } private void addSubdir2Sappath( File main, String mainPath ) { File[] fs = main.listFiles(); if(fs==null) { return; } for( int i = 0; i < fs.length; i++ ) { if( !fs[i].isDirectory() ) continue; String path = fs[i].getAbsolutePath(); path = path.substring( mainPath.length() ); path = StringUtils.replace( path, "\\", "/" ); sapPath.add( path ); addSubdir2Sappath( fs[i], mainPath ); } } public void save(OutputStream out) throws SAXException { Result resultxml = new StreamResult(out); handler.setResult(resultxml); level = 0; handler.startDocument(); // ���ø��ڵ�Ͱ汾 String paths = ""; for (int i = 0; i < sapPath.size(); i++) { if (paths.length() > 0) paths += ","; paths += sapPath.get(i); } handler.startElement("", "", "Server", getAttributesImpl(new String[] { ConfigConsts.VERSION, "1", "host", host, "port", port + "", "autostart", autoStart + "", "maxlinks", maxLinks + "", //parallelNum + "", "sapPath", paths })); handler.endElement("", "", "Server"); // �ĵ�����,ͬ�������� handler.endDocument(); } public String getHost() { return host; } public int getPort() { return port; } public boolean isAutoStart() { return autoStart; } public void setHost(String host) { this.host = host; } public void setPort(int port) { this.port = port; } public void setAutoStart(boolean as) { this.autoStart = as; }// public int getParallelNum() {// return parallelNum;// }//// public void setParallelNum(int num) {// this.parallelNum = num;// } public int getMaxLinks() { return maxLinks; } public void setMaxLinks(int m) { this.maxLinks = m; } public ArrayList<String> getSapPath() { return sapPath; } public void setSapPath(ArrayList<String> paths) { sapPath = paths; } public String toString() { return host + ":" + port; }}
|
data/java/10008.java
DELETED
@@ -1,422 +0,0 @@
|
|
1 |
-
package com.scudata.server.odbc;
|
2 |
-
|
3 |
-
import java.io.File;
|
4 |
-
import java.io.InputStream;
|
5 |
-
import java.io.OutputStream;
|
6 |
-
import java.util.ArrayList;
|
7 |
-
import java.util.List;
|
8 |
-
|
9 |
-
import javax.xml.parsers.DocumentBuilder;
|
10 |
-
import javax.xml.parsers.DocumentBuilderFactory;
|
11 |
-
import javax.xml.transform.Result;
|
12 |
-
import javax.xml.transform.stream.StreamResult;
|
13 |
-
|
14 |
-
import org.w3c.dom.Document;
|
15 |
-
import org.w3c.dom.Node;
|
16 |
-
import org.w3c.dom.NodeList;
|
17 |
-
import org.xml.sax.SAXException;
|
18 |
-
|
19 |
-
import com.scudata.app.config.ConfigConsts;
|
20 |
-
import com.scudata.app.config.ConfigWriter;
|
21 |
-
import com.scudata.common.Logger;
|
22 |
-
import com.scudata.common.StringUtils;
|
23 |
-
import com.scudata.common.Logger.FileHandler;
|
24 |
-
import com.scudata.parallel.UnitClient;
|
25 |
-
import com.scudata.parallel.UnitContext;
|
26 |
-
import com.scudata.parallel.XmlUtil;
|
27 |
-
import com.scudata.resources.ParallelMessage;
|
28 |
-
import com.scudata.server.ConnectionProxyManager;
|
29 |
-
import com.scudata.server.unit.UnitServer;
|
30 |
-
|
31 |
-
/**
|
32 |
-
* ODBC������������
|
33 |
-
*/
|
34 |
-
public class OdbcContext extends ConfigWriter {
|
35 |
-
public static final String ODBC_CONFIG_FILE = "OdbcServer.xml";
|
36 |
-
|
37 |
-
private String host = UnitContext.getDefaultHost();//"127.0.0.1";
|
38 |
-
private int port = 8501, timeOut = 2; // ��ʱ�ļ����ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ
|
39 |
-
|
40 |
-
// Connection
|
41 |
-
private int conMax = 10;
|
42 |
-
private int conTimeOut = 2;// ���Ӵ��ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ
|
43 |
-
private int conPeriod = 5; // �����������ʱ�ļ����ڵ�ʱ������0Ϊ�������ڡ��ļ��Լ��α����Ĺ���ʱ��,��λ��
|
44 |
-
private boolean autoStart=false;
|
45 |
-
|
46 |
-
private List<User> users = null;
|
47 |
-
|
48 |
-
/**
|
49 |
-
* ����odbc������������
|
50 |
-
*/
|
51 |
-
public OdbcContext(){
|
52 |
-
try {
|
53 |
-
InputStream inputStream = UnitContext.getUnitInputStream(ODBC_CONFIG_FILE);
|
54 |
-
if (inputStream != null) {
|
55 |
-
load(inputStream);
|
56 |
-
}
|
57 |
-
}catch (Exception x) {
|
58 |
-
x.printStackTrace();
|
59 |
-
}
|
60 |
-
}
|
61 |
-
|
62 |
-
/**
|
63 |
-
* ��������
|
64 |
-
* @param is �����������
|
65 |
-
* @throws Exception
|
66 |
-
*/
|
67 |
-
public void load(InputStream is) throws Exception {
|
68 |
-
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
|
69 |
-
.newInstance();
|
70 |
-
|
71 |
-
// BUG: CWE-611: Improper Restriction of XML External Entity Reference
|
72 |
-
// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
|
73 |
-
// FIXED:
|
74 |
-
|
75 |
-
Document xmlDocument = docBuilder.parse(is);
|
76 |
-
NodeList nl = xmlDocument.getChildNodes();
|
77 |
-
Node root = null;
|
78 |
-
for (int i = 0; i < nl.getLength(); i++) {
|
79 |
-
Node n = nl.item(i);
|
80 |
-
if (n.getNodeName().equalsIgnoreCase("Server")) {
|
81 |
-
root = n;
|
82 |
-
}
|
83 |
-
}
|
84 |
-
if (root == null) {
|
85 |
-
throw new Exception(ParallelMessage.get().getMessage("UnitConfig.errorxml"));
|
86 |
-
}
|
87 |
-
|
88 |
-
// Server ����
|
89 |
-
String buf = XmlUtil.getAttribute(root, "host");
|
90 |
-
if (StringUtils.isValidString(buf)) {
|
91 |
-
host = buf;
|
92 |
-
}
|
93 |
-
|
94 |
-
buf = XmlUtil.getAttribute(root, "port");
|
95 |
-
if (StringUtils.isValidString(buf)) {
|
96 |
-
port = Integer.parseInt(buf);
|
97 |
-
}
|
98 |
-
|
99 |
-
buf = XmlUtil.getAttribute(root, "autostart");
|
100 |
-
if (StringUtils.isValidString(buf)) {
|
101 |
-
autoStart = Boolean.parseBoolean(buf);
|
102 |
-
}
|
103 |
-
|
104 |
-
// �̶������־������̨�� �� start.home/nodes/[ip_port]/log Ŀ¼��
|
105 |
-
String home = UnitServer.getHome();
|
106 |
-
String file = "odbc/" + UnitClient.getHostPath(host) + "_" + port + "/log/log.txt";
|
107 |
-
File f = new File(home, file);
|
108 |
-
File fp = f.getParentFile();
|
109 |
-
if (!fp.exists()) {
|
110 |
-
fp.mkdirs();
|
111 |
-
}
|
112 |
-
String logFile = f.getAbsolutePath();
|
113 |
-
FileHandler lfh = Logger.newFileHandler(logFile);
|
114 |
-
Logger.addFileHandler(lfh);
|
115 |
-
|
116 |
-
buf = XmlUtil.getAttribute(root, "timeout");
|
117 |
-
if (StringUtils.isValidString(buf)) {
|
118 |
-
timeOut = Integer.parseInt(buf);
|
119 |
-
}
|
120 |
-
|
121 |
-
Node conNode = XmlUtil.findSonNode(root, "Connection");
|
122 |
-
Node subNode = XmlUtil.findSonNode(conNode, "Max");
|
123 |
-
buf = XmlUtil.getNodeValue(subNode);
|
124 |
-
if (StringUtils.isValidString(buf)) {
|
125 |
-
int t = Integer.parseInt(buf);
|
126 |
-
if (t > 0)
|
127 |
-
conMax = t;
|
128 |
-
}
|
129 |
-
|
130 |
-
subNode = XmlUtil.findSonNode(conNode, "Timeout");
|
131 |
-
buf = XmlUtil.getNodeValue(subNode);
|
132 |
-
if (StringUtils.isValidString(buf)) {
|
133 |
-
int t = Integer.parseInt(buf);
|
134 |
-
if (t > 0)
|
135 |
-
conTimeOut = t;
|
136 |
-
}
|
137 |
-
|
138 |
-
subNode = XmlUtil.findSonNode(conNode, "Period");
|
139 |
-
buf = XmlUtil.getNodeValue(subNode);
|
140 |
-
if (StringUtils.isValidString(buf)) {
|
141 |
-
int t = Integer.parseInt(buf);
|
142 |
-
if (t > 0)
|
143 |
-
conPeriod = t;
|
144 |
-
}
|
145 |
-
|
146 |
-
Node usersNode = XmlUtil.findSonNode(root, "Users");
|
147 |
-
NodeList userList = usersNode.getChildNodes();
|
148 |
-
|
149 |
-
users = new ArrayList<User>();
|
150 |
-
for (int i = 0, size = userList.getLength(); i < size; i++) {
|
151 |
-
Node xmlNode = userList.item(i);
|
152 |
-
if (!(xmlNode.getNodeName().equalsIgnoreCase("User")))
|
153 |
-
continue;
|
154 |
-
User user = new User();
|
155 |
-
buf = XmlUtil.getAttribute(xmlNode, "name");
|
156 |
-
user.name = buf;
|
157 |
-
|
158 |
-
buf = XmlUtil.getAttribute(xmlNode, "password");
|
159 |
-
user.password = buf;
|
160 |
-
|
161 |
-
buf = XmlUtil.getAttribute(xmlNode, "admin");
|
162 |
-
if (StringUtils.isValidString(buf)) {
|
163 |
-
user.admin = Boolean.parseBoolean(buf);
|
164 |
-
}
|
165 |
-
|
166 |
-
users.add(user);
|
167 |
-
}
|
168 |
-
|
169 |
-
}
|
170 |
-
|
171 |
-
/**
|
172 |
-
* �������õ������
|
173 |
-
* @param out �����
|
174 |
-
* @throws SAXException
|
175 |
-
*/
|
176 |
-
public void save(OutputStream out) throws SAXException {
|
177 |
-
Result resultxml = new StreamResult(out);
|
178 |
-
handler.setResult(resultxml);
|
179 |
-
level = 0;
|
180 |
-
handler.startDocument();
|
181 |
-
// ���ø��ڵ�Ͱ汾
|
182 |
-
handler.startElement("", "", "Server", getAttributesImpl(new String[] {
|
183 |
-
ConfigConsts.VERSION, "1", "host", host, "port", port + "","autostart", autoStart + "",
|
184 |
-
"timeout", timeOut + ""}));
|
185 |
-
|
186 |
-
level = 1;
|
187 |
-
startElement("Connection", null);
|
188 |
-
level = 2;
|
189 |
-
writeAttribute("Max", conMax + "");
|
190 |
-
writeAttribute("Timeout", conTimeOut + "");
|
191 |
-
writeAttribute("Period", conPeriod + "");
|
192 |
-
level = 1;
|
193 |
-
endElement("Connection");
|
194 |
-
|
195 |
-
startElement("Users", null);
|
196 |
-
if (users != null) {
|
197 |
-
for (int i = 0, size = users.size(); i < size; i++) {
|
198 |
-
level = 2;
|
199 |
-
User u = users.get(i);
|
200 |
-
startElement(
|
201 |
-
"User",
|
202 |
-
getAttributesImpl(new String[] { "name", u.name,
|
203 |
-
"password", u.password, "admin", u.admin + "" }));
|
204 |
-
endElement("User");
|
205 |
-
}
|
206 |
-
level = 1;
|
207 |
-
endElement("Users");
|
208 |
-
} else {
|
209 |
-
endEmptyElement("Users");
|
210 |
-
}
|
211 |
-
|
212 |
-
handler.endElement("", "", "Server");
|
213 |
-
// �ĵ�����,ͬ��������
|
214 |
-
handler.endDocument();
|
215 |
-
}
|
216 |
-
|
217 |
-
/**
|
218 |
-
* ��ȡ������IP
|
219 |
-
* @return IP��ַ
|
220 |
-
*/
|
221 |
-
public String getHost() {
|
222 |
-
return host;
|
223 |
-
}
|
224 |
-
|
225 |
-
/**
|
226 |
-
* ��ȡ�˿ں�
|
227 |
-
* @return �˿ں�
|
228 |
-
*/
|
229 |
-
public int getPort() {
|
230 |
-
return port;
|
231 |
-
}
|
232 |
-
|
233 |
-
public void setHost(String host) {
|
234 |
-
this.host = host;
|
235 |
-
}
|
236 |
-
|
237 |
-
/**
|
238 |
-
* ���ö˿ں�
|
239 |
-
* @param port �˿�
|
240 |
-
*/
|
241 |
-
public void setPort(int port) {
|
242 |
-
this.port = port;
|
243 |
-
}
|
244 |
-
|
245 |
-
/**
|
246 |
-
* �����Ƿ��Զ�����
|
247 |
-
* @param as �Ƿ��Զ�����
|
248 |
-
*/
|
249 |
-
public void setAutoStart(boolean as) {
|
250 |
-
this.autoStart = as;
|
251 |
-
}
|
252 |
-
|
253 |
-
/**
|
254 |
-
* ��ȡ�������Ƿ��Զ�������
|
255 |
-
* @return �Ƿ�������
|
256 |
-
*/
|
257 |
-
public boolean isAutoStart() {
|
258 |
-
return autoStart;
|
259 |
-
}
|
260 |
-
|
261 |
-
/**
|
262 |
-
* ��ȡ���ӳ�ʱ��ʱ��
|
263 |
-
* @return ��ʱʱ��
|
264 |
-
*/
|
265 |
-
public int getTimeOut() {
|
266 |
-
return timeOut;
|
267 |
-
}
|
268 |
-
|
269 |
-
/**
|
270 |
-
* ������ʱ�ļ����ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ
|
271 |
-
* @param timeout ��ʱʱ��
|
272 |
-
*/
|
273 |
-
public void setTimeOut(int timeout) {
|
274 |
-
this.timeOut = timeout;
|
275 |
-
}
|
276 |
-
|
277 |
-
/**
|
278 |
-
* ��ȡ���������Ŀ
|
279 |
-
* @return ���������
|
280 |
-
*/
|
281 |
-
public int getConMax() {
|
282 |
-
return conMax;
|
283 |
-
}
|
284 |
-
|
285 |
-
/**
|
286 |
-
* �������������
|
287 |
-
* @param max ���������
|
288 |
-
*/
|
289 |
-
public void setConMax(int max) {
|
290 |
-
this.conMax = max;
|
291 |
-
}
|
292 |
-
|
293 |
-
/**
|
294 |
-
* ��ȡ���ӳ�ʱ��ʱ��
|
295 |
-
* @return ���ӳ�ʱ��ʱ��
|
296 |
-
*/
|
297 |
-
public int getConTimeOut() {
|
298 |
-
return conTimeOut;
|
299 |
-
}
|
300 |
-
/**
|
301 |
-
* �������Ӵ��ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ
|
302 |
-
* @param cto ʱ��
|
303 |
-
*/
|
304 |
-
public void setConTimeOut(int cto) {
|
305 |
-
this.conTimeOut = cto;
|
306 |
-
}
|
307 |
-
|
308 |
-
/**
|
309 |
-
* ��ȡ��鳬ʱ���
|
310 |
-
* @return ��ʱ�����
|
311 |
-
*/
|
312 |
-
public int getConPeriod() {
|
313 |
-
return this.conPeriod;
|
314 |
-
}
|
315 |
-
|
316 |
-
/**
|
317 |
-
* ���ü����������ʱ�ļ����ڵ�ʱ������0Ϊ�������ڡ�
|
318 |
-
* �ļ��Լ��α����Ĺ���ʱ��,��λ��
|
319 |
-
*/
|
320 |
-
public void setConPeriod(int period) {
|
321 |
-
this.conPeriod = period;
|
322 |
-
}
|
323 |
-
|
324 |
-
/**
|
325 |
-
* ��ȡ�û��б�
|
326 |
-
* @return �û��б�
|
327 |
-
*/
|
328 |
-
public List<User> getUserList() {
|
329 |
-
return users;
|
330 |
-
}
|
331 |
-
|
332 |
-
/**
|
333 |
-
* �����û��б�
|
334 |
-
* @param users �û��б�
|
335 |
-
*/
|
336 |
-
public void setUserList(List<User> users) {
|
337 |
-
this.users = users;
|
338 |
-
}
|
339 |
-
|
340 |
-
/**
|
341 |
-
* ʵ��toString�ӿ�
|
342 |
-
*/
|
343 |
-
public String toString() {
|
344 |
-
return host + ":" + port;
|
345 |
-
}
|
346 |
-
|
347 |
-
/**
|
348 |
-
* ����û��Ƿ����
|
349 |
-
* @param user �û���
|
350 |
-
* @return ����ʱ����true������false
|
351 |
-
*/
|
352 |
-
public boolean isUserExist(String user) {
|
353 |
-
if (users == null) {
|
354 |
-
return true;
|
355 |
-
}
|
356 |
-
for (User u : users) {
|
357 |
-
if (u.getName().equalsIgnoreCase(user))
|
358 |
-
return true;
|
359 |
-
}
|
360 |
-
return false;
|
361 |
-
}
|
362 |
-
|
363 |
-
/**
|
364 |
-
* У���û��Ϸ���
|
365 |
-
* @param user �û���
|
366 |
-
* @param password ����
|
367 |
-
* @return У��ͨ������true������false
|
368 |
-
* @throws Exception
|
369 |
-
*/
|
370 |
-
public boolean checkUser(String user, String password) throws Exception{
|
371 |
-
ConnectionProxyManager cpm = ConnectionProxyManager.getInstance();
|
372 |
-
if(cpm.size()>=conMax){
|
373 |
-
throw new Exception("Exceed server's max connections, login user:"+user);
|
374 |
-
}
|
375 |
-
int size = users.size();
|
376 |
-
for (int i = 0; i < size; i++) {
|
377 |
-
User u = users.get(i);
|
378 |
-
if (u.getName().equalsIgnoreCase(user)) {
|
379 |
-
if (u.getPassword().equals(password)) {
|
380 |
-
return true;
|
381 |
-
} else {
|
382 |
-
throw new Exception("Invalid password.");
|
383 |
-
}
|
384 |
-
}
|
385 |
-
}
|
386 |
-
throw new Exception("Invalid user name.");
|
387 |
-
}
|
388 |
-
|
389 |
-
// ����1��ʾ��ȷ����������
|
390 |
-
public static class User {
|
391 |
-
private String name = null;
|
392 |
-
private String password = null;
|
393 |
-
private boolean admin = false;
|
394 |
-
|
395 |
-
public User() {
|
396 |
-
}
|
397 |
-
|
398 |
-
public String getName() {
|
399 |
-
return name;
|
400 |
-
}
|
401 |
-
|
402 |
-
public void setName(String name) {
|
403 |
-
this.name = name;
|
404 |
-
}
|
405 |
-
|
406 |
-
public String getPassword() {
|
407 |
-
return password;
|
408 |
-
}
|
409 |
-
|
410 |
-
public void setPassword(String password) {
|
411 |
-
this.password = password;
|
412 |
-
}
|
413 |
-
|
414 |
-
public boolean isAdmin() {
|
415 |
-
return admin;
|
416 |
-
}
|
417 |
-
|
418 |
-
public void setAdmin(boolean admin) {
|
419 |
-
this.admin = admin;
|
420 |
-
}
|
421 |
-
}
|
422 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10008.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.scudata.server.odbc;import java.io.File;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.Result;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;import com.scudata.app.config.ConfigConsts;import com.scudata.app.config.ConfigWriter;import com.scudata.common.Logger;import com.scudata.common.StringUtils;import com.scudata.common.Logger.FileHandler;import com.scudata.parallel.UnitClient;import com.scudata.parallel.UnitContext;import com.scudata.parallel.XmlUtil;import com.scudata.resources.ParallelMessage;import com.scudata.server.ConnectionProxyManager;import com.scudata.server.unit.UnitServer;/** * ODBC������������ */public class OdbcContext extends ConfigWriter { public static final String ODBC_CONFIG_FILE = "OdbcServer.xml"; private String host = UnitContext.getDefaultHost();//"127.0.0.1"; private int port = 8501, timeOut = 2; // ��ʱ�ļ����ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ // Connection private int conMax = 10; private int conTimeOut = 2;// ���Ӵ��ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ private int conPeriod = 5; // �����������ʱ�ļ����ڵ�ʱ������0Ϊ�������ڡ��ļ��Լ��α����Ĺ���ʱ��,��λ�� private boolean autoStart=false; private List<User> users = null; /** * ����odbc������������ */ public OdbcContext(){ try { InputStream inputStream = UnitContext.getUnitInputStream(ODBC_CONFIG_FILE); if (inputStream != null) { load(inputStream); } }catch (Exception x) { x.printStackTrace(); } } /** * �������� * @param is �����ļ������� * @throws Exception */ public void load(InputStream is) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();// FIXED: Document xmlDocument = docBuilder.parse(is); NodeList nl = xmlDocument.getChildNodes(); Node root = null; for (int i = 0; i < nl.getLength(); i++) { Node n = nl.item(i); if (n.getNodeName().equalsIgnoreCase("Server")) { root = n; } } if (root == null) { throw new Exception(ParallelMessage.get().getMessage("UnitConfig.errorxml")); } // Server ���� String buf = XmlUtil.getAttribute(root, "host"); if (StringUtils.isValidString(buf)) { host = buf; } buf = XmlUtil.getAttribute(root, "port"); if (StringUtils.isValidString(buf)) { port = Integer.parseInt(buf); } buf = XmlUtil.getAttribute(root, "autostart"); if (StringUtils.isValidString(buf)) { autoStart = Boolean.parseBoolean(buf); } // �̶������־������̨�� �� start.home/nodes/[ip_port]/log Ŀ¼�� String home = UnitServer.getHome(); String file = "odbc/" + UnitClient.getHostPath(host) + "_" + port + "/log/log.txt"; File f = new File(home, file); File fp = f.getParentFile(); if (!fp.exists()) { fp.mkdirs(); } String logFile = f.getAbsolutePath(); FileHandler lfh = Logger.newFileHandler(logFile); Logger.addFileHandler(lfh); buf = XmlUtil.getAttribute(root, "timeout"); if (StringUtils.isValidString(buf)) { timeOut = Integer.parseInt(buf); } Node conNode = XmlUtil.findSonNode(root, "Connection"); Node subNode = XmlUtil.findSonNode(conNode, "Max"); buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { int t = Integer.parseInt(buf); if (t > 0) conMax = t; } subNode = XmlUtil.findSonNode(conNode, "Timeout"); buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { int t = Integer.parseInt(buf); if (t > 0) conTimeOut = t; } subNode = XmlUtil.findSonNode(conNode, "Period"); buf = XmlUtil.getNodeValue(subNode); if (StringUtils.isValidString(buf)) { int t = Integer.parseInt(buf); if (t > 0) conPeriod = t; } Node usersNode = XmlUtil.findSonNode(root, "Users"); NodeList userList = usersNode.getChildNodes(); users = new ArrayList<User>(); for (int i = 0, size = userList.getLength(); i < size; i++) { Node xmlNode = userList.item(i); if (!(xmlNode.getNodeName().equalsIgnoreCase("User"))) continue; User user = new User(); buf = XmlUtil.getAttribute(xmlNode, "name"); user.name = buf; buf = XmlUtil.getAttribute(xmlNode, "password"); user.password = buf; buf = XmlUtil.getAttribute(xmlNode, "admin"); if (StringUtils.isValidString(buf)) { user.admin = Boolean.parseBoolean(buf); } users.add(user); } } /** * �������õ������ * @param out ����� * @throws SAXException */ public void save(OutputStream out) throws SAXException { Result resultxml = new StreamResult(out); handler.setResult(resultxml); level = 0; handler.startDocument(); // ���ø��ڵ�Ͱ汾 handler.startElement("", "", "Server", getAttributesImpl(new String[] { ConfigConsts.VERSION, "1", "host", host, "port", port + "","autostart", autoStart + "", "timeout", timeOut + ""})); level = 1; startElement("Connection", null); level = 2; writeAttribute("Max", conMax + ""); writeAttribute("Timeout", conTimeOut + ""); writeAttribute("Period", conPeriod + ""); level = 1; endElement("Connection"); startElement("Users", null); if (users != null) { for (int i = 0, size = users.size(); i < size; i++) { level = 2; User u = users.get(i); startElement( "User", getAttributesImpl(new String[] { "name", u.name, "password", u.password, "admin", u.admin + "" })); endElement("User"); } level = 1; endElement("Users"); } else { endEmptyElement("Users"); } handler.endElement("", "", "Server"); // �ĵ�����,ͬ�������� handler.endDocument(); } /** * ��ȡ������IP * @return IP��ַ */ public String getHost() { return host; } /** * ��ȡ�˿ں� * @return �˿ں� */ public int getPort() { return port; } public void setHost(String host) { this.host = host; } /** * ���ö˿ں� * @param port �˿� */ public void setPort(int port) { this.port = port; } /** * �����Ƿ��Զ����� * @param as �Ƿ��Զ����� */ public void setAutoStart(boolean as) { this.autoStart = as; } /** * ��ȡ�������Ƿ��Զ������� * @return �Ƿ������� */ public boolean isAutoStart() { return autoStart; } /** * ��ȡ���ӳ�ʱ��ʱ�� * @return ��ʱʱ�� */ public int getTimeOut() { return timeOut; } /** * ������ʱ�ļ����ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ * @param timeout ��ʱʱ�� */ public void setTimeOut(int timeout) { this.timeOut = timeout; } /** * ��ȡ���������Ŀ * @return ��������� */ public int getConMax() { return conMax; } /** * ������������� * @param max ��������� */ public void setConMax(int max) { this.conMax = max; } /** * ��ȡ���ӳ�ʱ��ʱ�� * @return ���ӳ�ʱ��ʱ�� */ public int getConTimeOut() { return conTimeOut; } /** * �������Ӵ��ʱ�䣬СʱΪ��λ��0Ϊ����鳬ʱ * @param cto ʱ�� */ public void setConTimeOut(int cto) { this.conTimeOut = cto; } /** * ��ȡ��鳬ʱ��� * @return ��ʱ����� */ public int getConPeriod() { return this.conPeriod; } /** * ���ü����������ʱ�ļ����ڵ�ʱ������0Ϊ�������ڡ� * �ļ��Լ��α����Ĺ���ʱ��,��λ�� */ public void setConPeriod(int period) { this.conPeriod = period; } /** * ��ȡ�û��б� * @return �û��б� */ public List<User> getUserList() { return users; } /** * �����û��б� * @param users �û��б� */ public void setUserList(List<User> users) { this.users = users; } /** * ʵ��toString�ӿ� */ public String toString() { return host + ":" + port; } /** * ����û��Ƿ���� * @param user �û��� * @return ����ʱ����true������false */ public boolean isUserExist(String user) { if (users == null) { return true; } for (User u : users) { if (u.getName().equalsIgnoreCase(user)) return true; } return false; } /** * У���û��Ϸ��� * @param user �û��� * @param password ���� * @return У��ͨ������true������false * @throws Exception */ public boolean checkUser(String user, String password) throws Exception{ ConnectionProxyManager cpm = ConnectionProxyManager.getInstance(); if(cpm.size()>=conMax){ throw new Exception("Exceed server's max connections, login user:"+user); } int size = users.size(); for (int i = 0; i < size; i++) { User u = users.get(i); if (u.getName().equalsIgnoreCase(user)) { if (u.getPassword().equals(password)) { return true; } else { throw new Exception("Invalid password."); } } } throw new Exception("Invalid user name."); } // ����1��ʾ��ȷ���������� public static class User { private String name = null; private String password = null; private boolean admin = false; public User() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isAdmin() { return admin; } public void setAdmin(boolean admin) { this.admin = admin; } }}
|
data/java/10009.java
DELETED
@@ -1,618 +0,0 @@
|
|
1 |
-
/**
|
2 |
-
* Copyright 2015 Huawei Technologies Co., Ltd. All rights reserved.
|
3 |
-
* eSDK is licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
* you may not use this file except in compliance with the License.
|
5 |
-
* You may obtain a copy of the License at
|
6 |
-
*
|
7 |
-
* http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
*
|
9 |
-
* Unless required by applicable law or agreed to in writing, software
|
10 |
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
* See the License for the specific language governing permissions and
|
13 |
-
* limitations under the License.
|
14 |
-
*/
|
15 |
-
package com.huawei.esdk.fusioncompute.local.impl.restlet;
|
16 |
-
|
17 |
-
import java.io.IOException;
|
18 |
-
import java.io.InputStream;
|
19 |
-
import java.security.KeyManagementException;
|
20 |
-
import java.security.KeyStore;
|
21 |
-
import java.security.KeyStoreException;
|
22 |
-
import java.security.NoSuchAlgorithmException;
|
23 |
-
import java.security.NoSuchProviderException;
|
24 |
-
import java.security.SecureRandom;
|
25 |
-
import java.security.cert.CertificateException;
|
26 |
-
import java.security.cert.X509Certificate;
|
27 |
-
import java.util.ArrayList;
|
28 |
-
import java.util.List;
|
29 |
-
|
30 |
-
import javax.net.ssl.HostnameVerifier;
|
31 |
-
import javax.net.ssl.SSLContext;
|
32 |
-
import javax.net.ssl.SSLSession;
|
33 |
-
import javax.net.ssl.TrustManager;
|
34 |
-
import javax.net.ssl.TrustManagerFactory;
|
35 |
-
import javax.net.ssl.X509TrustManager;
|
36 |
-
|
37 |
-
import org.apache.log4j.Logger;
|
38 |
-
import org.restlet.Client;
|
39 |
-
import org.restlet.Context;
|
40 |
-
import org.restlet.Request;
|
41 |
-
import org.restlet.Response;
|
42 |
-
import org.restlet.data.ClientInfo;
|
43 |
-
import org.restlet.data.Header;
|
44 |
-
import org.restlet.data.Language;
|
45 |
-
import org.restlet.data.MediaType;
|
46 |
-
import org.restlet.data.Method;
|
47 |
-
import org.restlet.data.Parameter;
|
48 |
-
import org.restlet.data.Preference;
|
49 |
-
import org.restlet.data.Protocol;
|
50 |
-
import org.restlet.engine.header.HeaderConstants;
|
51 |
-
import org.restlet.engine.ssl.SslContextFactory;
|
52 |
-
import org.restlet.representation.Representation;
|
53 |
-
import org.restlet.util.Series;
|
54 |
-
|
55 |
-
import com.google.gson.Gson;
|
56 |
-
import com.huawei.esdk.fusioncompute.local.impl.SDKClient;
|
57 |
-
import com.huawei.esdk.fusioncompute.local.impl.constant.ESDKURL;
|
58 |
-
import com.huawei.esdk.fusioncompute.local.impl.constant.NativeConstant;
|
59 |
-
import com.huawei.esdk.fusioncompute.local.impl.constant.SSLParameter;
|
60 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.AuthenticateCacheBean;
|
61 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.EsdkVRMException;
|
62 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.FCCacheHolder;
|
63 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.LogConfig;
|
64 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.LogUtil;
|
65 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.SHA256Utils;
|
66 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.StringUtils;
|
67 |
-
import com.huawei.esdk.fusioncompute.local.impl.utils.URLUtils;
|
68 |
-
import com.huawei.esdk.fusioncompute.local.model.ClientProviderBean;
|
69 |
-
import com.huawei.esdk.fusioncompute.local.model.SDKCommonResp;
|
70 |
-
|
71 |
-
public class RestletClient implements SDKClient
|
72 |
-
{
|
73 |
-
private static final Logger LOGGER = Logger.getLogger(RestletClient.class);
|
74 |
-
|
75 |
-
private ClientProviderBean bean;
|
76 |
-
|
77 |
-
private static final int HTTP_STATUS_CODE_OK = 200;
|
78 |
-
|
79 |
-
private static final int HTTP_STATUS_CODE_NOT_FOUND = 404;
|
80 |
-
|
81 |
-
private static final int HTTP_STATUS_CODE_UNAUTHORIZED = 401;
|
82 |
-
|
83 |
-
private static final int HTTP_STATUS_CODE_FORBIDDEN = 403;
|
84 |
-
|
85 |
-
private static final int CONNECTOR_ERROR_COMMUNICATION = 1001;
|
86 |
-
|
87 |
-
private static final int CONNECTOR_ERROR_CONNECTION = 1000;
|
88 |
-
|
89 |
-
private static final String PROTOCOL_HTTPS = "https";
|
90 |
-
|
91 |
-
private static final String X_AUTH_USER = "X-Auth-User";
|
92 |
-
|
93 |
-
private static final String X_AUTH_KEY = "X-Auth-Key";
|
94 |
-
|
95 |
-
private static final String X_AUTH_TOKEN = "X-Auth-Token";
|
96 |
-
|
97 |
-
private String version;
|
98 |
-
|
99 |
-
private int flag = 0;
|
100 |
-
|
101 |
-
private Gson gson = new Gson();
|
102 |
-
|
103 |
-
private ESDKURL esdkUrl = new ESDKURL();
|
104 |
-
|
105 |
-
public RestletClient(ClientProviderBean bean)
|
106 |
-
{
|
107 |
-
this.flag = bean.getTimes();
|
108 |
-
this.bean = bean;
|
109 |
-
this.version = StringUtils.convertString(bean.getVersion());
|
110 |
-
}
|
111 |
-
|
112 |
-
@Override
|
113 |
-
public String get(String url, String methodName) throws Exception
|
114 |
-
{
|
115 |
-
return invoke(Method.GET, url, null, methodName);
|
116 |
-
}
|
117 |
-
|
118 |
-
@Override
|
119 |
-
public String post(String url, Object msg, String methodName) throws Exception
|
120 |
-
{
|
121 |
-
return invoke(Method.POST, url, msg, methodName);
|
122 |
-
|
123 |
-
}
|
124 |
-
|
125 |
-
@Override
|
126 |
-
public String put(String url, Object msg, String methodName) throws Exception
|
127 |
-
{
|
128 |
-
return invoke(Method.PUT, url, msg, methodName);
|
129 |
-
}
|
130 |
-
|
131 |
-
@Override
|
132 |
-
public String delete(String url, String methodName) throws Exception
|
133 |
-
{
|
134 |
-
return invoke(Method.DELETE, url, null, methodName);
|
135 |
-
}
|
136 |
-
|
137 |
-
// 带密码打印日志
|
138 |
-
public String invokeNoLog(Method method, String url, Object msg, String methodName) throws Exception
|
139 |
-
{
|
140 |
-
return invokeRun(method, url, msg, methodName);
|
141 |
-
}
|
142 |
-
|
143 |
-
// 普通处理 不带密码打印日志
|
144 |
-
private String invoke(Method method, String url, Object msg, String methodName) throws Exception
|
145 |
-
{
|
146 |
-
String resp = null;
|
147 |
-
//LOGGER.info("request body:" + gson.toJson(msg));
|
148 |
-
|
149 |
-
resp = invokeRun(method, url, msg, methodName);
|
150 |
-
|
151 |
-
//LOGGER.info("response:" + resp);
|
152 |
-
|
153 |
-
return resp;
|
154 |
-
}
|
155 |
-
|
156 |
-
private String invokeRun(Method method, String url, Object msg, String methodName) throws Exception
|
157 |
-
{
|
158 |
-
Client client = null;
|
159 |
-
if (PROTOCOL_HTTPS.equalsIgnoreCase(bean.getProtocol()))
|
160 |
-
{
|
161 |
-
client = configSSL(bean.getKeyStoreName(), bean.getKeyStorePassword(), bean.getValidateCertificate());
|
162 |
-
}
|
163 |
-
else
|
164 |
-
{
|
165 |
-
//初始客户端对象
|
166 |
-
client = new Client(new Context(), Protocol.HTTP);
|
167 |
-
}
|
168 |
-
Request request = new Request(method, url);
|
169 |
-
String requestStr = null;
|
170 |
-
if (null != msg)
|
171 |
-
{
|
172 |
-
requestStr = gson.toJson(msg);
|
173 |
-
}
|
174 |
-
|
175 |
-
String req_log = requestStr;
|
176 |
-
if (requestStr != null)
|
177 |
-
{
|
178 |
-
if (LogConfig.checkUrl(url))
|
179 |
-
{
|
180 |
-
req_log = LogConfig.replaceWord(requestStr);
|
181 |
-
}
|
182 |
-
}
|
183 |
-
|
184 |
-
//设置标准http header
|
185 |
-
if (null != url && url.endsWith("/service/versions"))
|
186 |
-
{
|
187 |
-
setDefaultHttpHeader(request, null);
|
188 |
-
}
|
189 |
-
else
|
190 |
-
{
|
191 |
-
// 2016.06.22 版本自适应
|
192 |
-
setDefaultHttpHeader(request, "version=" + version + ";");
|
193 |
-
}
|
194 |
-
|
195 |
-
//自定义消息头
|
196 |
-
Series<Header> extraHeaders = new Series<Header>(Header.class);
|
197 |
-
|
198 |
-
if (null != FCCacheHolder.getAuthenticateCache(bean))
|
199 |
-
{
|
200 |
-
extraHeaders.add(X_AUTH_TOKEN, FCCacheHolder.getAuthenticateCache(bean).getToken());
|
201 |
-
}
|
202 |
-
|
203 |
-
request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, extraHeaders);
|
204 |
-
if (!StringUtils.isEmpty(requestStr))
|
205 |
-
{
|
206 |
-
request.setEntity(requestStr, MediaType.APPLICATION_JSON);
|
207 |
-
}
|
208 |
-
//LOGGER.info("request url:" + request);
|
209 |
-
|
210 |
-
client.getContext().getParameters().add("socketConnectTimeoutMs", String.valueOf(20000));
|
211 |
-
client.getContext().getParameters().add("readTimeout", String.valueOf(20000));
|
212 |
-
|
213 |
-
// 消息发送时间
|
214 |
-
String reqTime = LogUtil.getSysTime();
|
215 |
-
|
216 |
-
Response response = client.handle(request);
|
217 |
-
|
218 |
-
// 消息接受时间
|
219 |
-
String respTime = LogUtil.getSysTime();
|
220 |
-
|
221 |
-
//LOGGER.info("http status code:" + response.getStatus().getCode());
|
222 |
-
|
223 |
-
Representation output = response.getEntity();
|
224 |
-
if (null == output)
|
225 |
-
{
|
226 |
-
SDKCommonResp error = new SDKCommonResp();
|
227 |
-
|
228 |
-
error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION);
|
229 |
-
error.setErrorDes("Not Found");
|
230 |
-
EsdkVRMException exception = new EsdkVRMException("Not Found");
|
231 |
-
exception.setErrInfo(error);
|
232 |
-
bean.setTimes(flag);
|
233 |
-
|
234 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime,
|
235 |
-
url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode()));
|
236 |
-
|
237 |
-
throw exception;
|
238 |
-
}
|
239 |
-
String resp = output.getText();
|
240 |
-
|
241 |
-
if (HTTP_STATUS_CODE_NOT_FOUND == response.getStatus().getCode())
|
242 |
-
{
|
243 |
-
SDKCommonResp error = new SDKCommonResp();
|
244 |
-
|
245 |
-
error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION);
|
246 |
-
error.setErrorDes(response.getStatus().getDescription());
|
247 |
-
EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription());
|
248 |
-
exception.setErrInfo(error);
|
249 |
-
bean.setTimes(flag);
|
250 |
-
|
251 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime,
|
252 |
-
url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode()));
|
253 |
-
|
254 |
-
throw exception;
|
255 |
-
}
|
256 |
-
else if (HTTP_STATUS_CODE_UNAUTHORIZED == response.getStatus().getCode())
|
257 |
-
{
|
258 |
-
if (bean.getTimes() >= 1 && !StringUtils.isEmpty(FCCacheHolder.getLoginUser(bean)))
|
259 |
-
{
|
260 |
-
this.login(URLUtils.makeUrl(bean, esdkUrl.getAuthenticateUrl(), null), FCCacheHolder.getAuthenticateCache(bean)
|
261 |
-
.getUserName(), FCCacheHolder.getAuthenticateCache(bean).getPassword(), "Login");
|
262 |
-
bean.setTimes(bean.getTimes() - 1);
|
263 |
-
// 2015-11-09 修改二次请求消息格式错误问题。
|
264 |
-
return this.invokeRun(method, url, msg, methodName);
|
265 |
-
}
|
266 |
-
SDKCommonResp error = new SDKCommonResp();
|
267 |
-
|
268 |
-
error.setErrorCode(NativeConstant.UNAUTHORIZED_EXCEPTION);
|
269 |
-
error.setErrorDes(response.getStatus().getDescription());
|
270 |
-
EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription());
|
271 |
-
exception.setErrInfo(error);
|
272 |
-
bean.setTimes(flag);
|
273 |
-
|
274 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime,
|
275 |
-
url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode()));
|
276 |
-
|
277 |
-
throw exception;
|
278 |
-
}
|
279 |
-
else if (HTTP_STATUS_CODE_FORBIDDEN == response.getStatus().getCode())
|
280 |
-
{
|
281 |
-
SDKCommonResp error = new SDKCommonResp();
|
282 |
-
|
283 |
-
error.setErrorCode(NativeConstant.FORBIDDEN_EXCEPTION);
|
284 |
-
error.setErrorDes(response.getStatus().getDescription());
|
285 |
-
EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription());
|
286 |
-
exception.setErrInfo(error);
|
287 |
-
bean.setTimes(flag);
|
288 |
-
|
289 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime,
|
290 |
-
url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode()));
|
291 |
-
|
292 |
-
throw exception;
|
293 |
-
}
|
294 |
-
else if (CONNECTOR_ERROR_COMMUNICATION == response.getStatus().getCode())
|
295 |
-
{
|
296 |
-
SDKCommonResp error = new SDKCommonResp();
|
297 |
-
|
298 |
-
error.setErrorCode(NativeConstant.COMMUNICATION_EXCEPTION);
|
299 |
-
error.setErrorDes(response.getStatus().getDescription());
|
300 |
-
EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription());
|
301 |
-
exception.setErrInfo(error);
|
302 |
-
bean.setTimes(flag);
|
303 |
-
|
304 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime,
|
305 |
-
url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode()));
|
306 |
-
|
307 |
-
throw exception;
|
308 |
-
}
|
309 |
-
else if (HTTP_STATUS_CODE_OK != response.getStatus().getCode())
|
310 |
-
{
|
311 |
-
SDKCommonResp error = gson.fromJson(resp, SDKCommonResp.class);
|
312 |
-
|
313 |
-
EsdkVRMException exception = null;
|
314 |
-
if (null == error)
|
315 |
-
{
|
316 |
-
error = new SDKCommonResp();
|
317 |
-
error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION);
|
318 |
-
error.setErrorDes("Not Found");
|
319 |
-
exception = new EsdkVRMException("Not Found");
|
320 |
-
exception.setErrInfo(error);
|
321 |
-
}
|
322 |
-
else
|
323 |
-
{
|
324 |
-
exception = new EsdkVRMException(error.getErrorDes());
|
325 |
-
exception.setErrInfo(error);
|
326 |
-
}
|
327 |
-
|
328 |
-
bean.setTimes(flag);
|
329 |
-
|
330 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime,
|
331 |
-
url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode()));
|
332 |
-
|
333 |
-
throw exception;
|
334 |
-
}
|
335 |
-
|
336 |
-
bean.setTimes(flag);
|
337 |
-
|
338 |
-
// 2014.11.11 By y00206201 整改日志 添加
|
339 |
-
String resp_log = resp;
|
340 |
-
if (resp != null)
|
341 |
-
{
|
342 |
-
if (LogConfig.checkUrl(url))
|
343 |
-
{
|
344 |
-
resp_log = LogConfig.replaceWord(resp);
|
345 |
-
}
|
346 |
-
}
|
347 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.infoLogType, LogConfig.product, reqTime, respTime, url,
|
348 |
-
method.getName(), req_log, response.getStatus().getCode(), resp_log));
|
349 |
-
|
350 |
-
return resp;
|
351 |
-
}
|
352 |
-
|
353 |
-
@Override
|
354 |
-
public String login(String url, String userName, String password, String methodName) throws Exception
|
355 |
-
{
|
356 |
-
Client client = null;
|
357 |
-
if (PROTOCOL_HTTPS.equalsIgnoreCase(bean.getProtocol()))
|
358 |
-
{
|
359 |
-
client = configSSL(bean.getKeyStoreName(), bean.getKeyStorePassword(), bean.getValidateCertificate());
|
360 |
-
}
|
361 |
-
else
|
362 |
-
{
|
363 |
-
//初始客户端对象
|
364 |
-
client = new Client(new Context(), Protocol.HTTP);
|
365 |
-
}
|
366 |
-
Request request = new Request(Method.POST, url);
|
367 |
-
|
368 |
-
//设置自定义header
|
369 |
-
Series<Header> extraHeaders = new Series<Header>(Header.class);
|
370 |
-
extraHeaders.add(X_AUTH_USER, userName);
|
371 |
-
extraHeaders.add(X_AUTH_KEY, SHA256Utils.encrypt(password));
|
372 |
-
request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, extraHeaders);
|
373 |
-
//设置标准http header 2016.06.22 适配版本
|
374 |
-
setDefaultHttpHeader(request, "version=" + version + ";");
|
375 |
-
|
376 |
-
//LOGGER.info("request url:" + request);
|
377 |
-
//LOGGER.info("request header:" + extraHeaders);
|
378 |
-
|
379 |
-
//设置连接超时时间
|
380 |
-
client.getContext().getParameters().add("socketConnectTimeoutMs", String.valueOf(20000));
|
381 |
-
client.getContext().getParameters().add("readTimeout", String.valueOf(20000));
|
382 |
-
|
383 |
-
// 2014.11.11 By y00206201 整改日志 添加
|
384 |
-
// 日志类型
|
385 |
-
// 业务
|
386 |
-
// 南北向接口类型 默认
|
387 |
-
// 协议类型 默认
|
388 |
-
// 方法名 对于Rest接口而言就是url + method
|
389 |
-
// 源Ip
|
390 |
-
// 目的Ip 从Url解析
|
391 |
-
// 事务标识 默认
|
392 |
-
// 发送消息给产品时间
|
393 |
-
// 从产品接受消息时间
|
394 |
-
// 消息体
|
395 |
-
String method = LogUtil.POST;
|
396 |
-
String body = "";
|
397 |
-
// 消息请求时间
|
398 |
-
String reqTime = LogUtil.getSysTime();
|
399 |
-
|
400 |
-
//发送请求
|
401 |
-
Response response = client.handle(request);
|
402 |
-
|
403 |
-
// 消息响应时间
|
404 |
-
String respTime = LogUtil.getSysTime();
|
405 |
-
|
406 |
-
//LOGGER.info("http status code:" + response.getStatus().getCode());
|
407 |
-
if (CONNECTOR_ERROR_COMMUNICATION == response.getStatus().getCode() || CONNECTOR_ERROR_CONNECTION == response.getStatus().getCode())
|
408 |
-
{
|
409 |
-
SDKCommonResp error = new SDKCommonResp();
|
410 |
-
|
411 |
-
error.setErrorCode(NativeConstant.COMMUNICATION_EXCEPTION);
|
412 |
-
error.setErrorDes(response.getStatus().getDescription());
|
413 |
-
EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription());
|
414 |
-
exception.setErrInfo(error);
|
415 |
-
|
416 |
-
LOGGER.error(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime,
|
417 |
-
respTime, url, method, body, response.getStatus().getCode(), error.getErrorCode()));
|
418 |
-
|
419 |
-
throw exception;
|
420 |
-
}
|
421 |
-
|
422 |
-
if (HTTP_STATUS_CODE_NOT_FOUND == response.getStatus().getCode())
|
423 |
-
{
|
424 |
-
SDKCommonResp error = new SDKCommonResp();
|
425 |
-
|
426 |
-
error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION);
|
427 |
-
error.setErrorDes(response.getStatus().getDescription());
|
428 |
-
EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription());
|
429 |
-
exception.setErrInfo(error);
|
430 |
-
|
431 |
-
LOGGER.error(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime,
|
432 |
-
respTime, url, method, body, response.getStatus().getCode(), error.getErrorCode()));
|
433 |
-
|
434 |
-
throw exception;
|
435 |
-
}
|
436 |
-
Representation output = response.getEntity();
|
437 |
-
String resp = output.getText();
|
438 |
-
|
439 |
-
if (HTTP_STATUS_CODE_OK != response.getStatus().getCode())
|
440 |
-
{
|
441 |
-
SDKCommonResp error = gson.fromJson(resp, SDKCommonResp.class);
|
442 |
-
|
443 |
-
EsdkVRMException exception = new EsdkVRMException(error.getErrorDes());
|
444 |
-
exception.setErrInfo(error);
|
445 |
-
|
446 |
-
LOGGER.error(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime,
|
447 |
-
respTime, url, method, body, response.getStatus().getCode(), resp));
|
448 |
-
|
449 |
-
throw exception;
|
450 |
-
}
|
451 |
-
|
452 |
-
//获取responseHeader
|
453 |
-
@SuppressWarnings("unchecked")
|
454 |
-
Series<Header> respHeader = (Series<Header>) response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS);
|
455 |
-
String token = respHeader.getValues(X_AUTH_TOKEN);
|
456 |
-
|
457 |
-
if (null != token)
|
458 |
-
{
|
459 |
-
AuthenticateCacheBean authenticateCacheBean = new AuthenticateCacheBean();
|
460 |
-
authenticateCacheBean.setToken(token);
|
461 |
-
authenticateCacheBean.setUserName(userName);
|
462 |
-
authenticateCacheBean.setPassword(password);
|
463 |
-
//保存token
|
464 |
-
FCCacheHolder.saveAuthenticateCache(bean, authenticateCacheBean);
|
465 |
-
}
|
466 |
-
|
467 |
-
// 2014.11.11 By y00206201 整改日志 添加
|
468 |
-
LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.infoLogType, LogConfig.product, reqTime, respTime, url,
|
469 |
-
method, body, response.getStatus().getCode(), resp));
|
470 |
-
|
471 |
-
return resp;
|
472 |
-
}
|
473 |
-
|
474 |
-
private static Client configSSL(String keyStoreName, String keyStorePassword, Boolean validateCertificate) throws KeyStoreException,
|
475 |
-
NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException
|
476 |
-
{
|
477 |
-
|
478 |
-
// BUG: CWE-326: Inadequate Encryption Strength
|
479 |
-
// final SSLContext sslContext = SSLContext.getInstance("TLS");
|
480 |
-
// FIXED:
|
481 |
-
|
482 |
-
if (!validateCertificate)
|
483 |
-
{
|
484 |
-
//信任所有证书
|
485 |
-
sslContext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom());
|
486 |
-
}
|
487 |
-
else
|
488 |
-
{
|
489 |
-
if (null == keyStoreName || null == keyStorePassword)
|
490 |
-
{
|
491 |
-
return new Client(new Context(), Protocol.HTTPS);
|
492 |
-
}
|
493 |
-
KeyStore keyStore = KeyStore.getInstance(SSLParameter.KEYSTORE_TYPE, SSLParameter.KEYSTORE_PROVIDER);
|
494 |
-
InputStream is = (InputStream) ClassLoader.getSystemClassLoader().getResourceAsStream(keyStoreName);
|
495 |
-
if (null == is)
|
496 |
-
{
|
497 |
-
is = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreName);
|
498 |
-
}
|
499 |
-
keyStore.load(is, keyStorePassword.toCharArray());
|
500 |
-
|
501 |
-
try
|
502 |
-
{
|
503 |
-
is.close();
|
504 |
-
}
|
505 |
-
catch (NullPointerException e)
|
506 |
-
{
|
507 |
-
LOGGER.error(LogUtil.runLog(LogUtil.errorLogType, "RestletClient.configSSL", "InputStream is null,and e = " + e));
|
508 |
-
}
|
509 |
-
catch (IOException e)
|
510 |
-
{
|
511 |
-
LOGGER.error(LogUtil.runLog(LogUtil.errorLogType, "RestletClient.configSSL", "RestletClient.configSSL IOException,and e = "
|
512 |
-
+ e));
|
513 |
-
}
|
514 |
-
finally
|
515 |
-
{
|
516 |
-
if (null != is)
|
517 |
-
{
|
518 |
-
try
|
519 |
-
{
|
520 |
-
is.close();
|
521 |
-
}
|
522 |
-
catch (IOException e)
|
523 |
-
{
|
524 |
-
LOGGER.error(LogUtil.runLog(LogUtil.errorLogType, "RestletClient.configSSL",
|
525 |
-
"Exception happened in RestletClient.configSSL,and e = " + e));
|
526 |
-
}
|
527 |
-
}
|
528 |
-
}
|
529 |
-
|
530 |
-
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
531 |
-
trustFactory.init(keyStore);
|
532 |
-
TrustManager[] trustManagers = trustFactory.getTrustManagers();
|
533 |
-
|
534 |
-
//信任证书
|
535 |
-
sslContext.init(null, trustManagers, new SecureRandom());
|
536 |
-
}
|
537 |
-
|
538 |
-
Context context = new Context();
|
539 |
-
|
540 |
-
context.getAttributes().put("hostnameVerifier", new HostnameVerifier() {
|
541 |
-
@Override
|
542 |
-
public boolean verify(String s, SSLSession sslsession)
|
543 |
-
{
|
544 |
-
return true;
|
545 |
-
}
|
546 |
-
});
|
547 |
-
|
548 |
-
context.getAttributes().put("sslContextFactory", new SslContextFactory() {
|
549 |
-
@Override
|
550 |
-
public void init(Series<Parameter> parameter)
|
551 |
-
{
|
552 |
-
}
|
553 |
-
|
554 |
-
@Override
|
555 |
-
public SSLContext createSslContext() throws Exception
|
556 |
-
{
|
557 |
-
return sslContext;
|
558 |
-
}
|
559 |
-
});
|
560 |
-
|
561 |
-
Client client = new Client(context, Protocol.HTTPS);
|
562 |
-
return client;
|
563 |
-
}
|
564 |
-
|
565 |
-
/**
|
566 |
-
* 设置标准http header
|
567 |
-
*
|
568 |
-
* @param request {@code void}
|
569 |
-
* @since eSDK Cloud V100R003C50
|
570 |
-
*/
|
571 |
-
private void setDefaultHttpHeader(Request request, String version)
|
572 |
-
{
|
573 |
-
ClientInfo clientInfo = new ClientInfo();
|
574 |
-
|
575 |
-
List<Preference<MediaType>> acceptedMediaTypes = new ArrayList<Preference<MediaType>>();
|
576 |
-
Preference<MediaType> preferenceMediaType = new Preference<MediaType>();
|
577 |
-
|
578 |
-
String acceptStr = "application/json;";
|
579 |
-
if (null == version)
|
580 |
-
{
|
581 |
-
acceptStr += "charset=UTF-8;";
|
582 |
-
}
|
583 |
-
else
|
584 |
-
{
|
585 |
-
acceptStr += version + "charset=UTF-8;";
|
586 |
-
}
|
587 |
-
MediaType mediaType = MediaType.register(acceptStr, "");
|
588 |
-
preferenceMediaType.setMetadata(mediaType);
|
589 |
-
acceptedMediaTypes.add(preferenceMediaType);
|
590 |
-
clientInfo.setAcceptedMediaTypes(acceptedMediaTypes);
|
591 |
-
|
592 |
-
List<Preference<Language>> acceptedLanguages = new ArrayList<Preference<Language>>();
|
593 |
-
|
594 |
-
Preference<Language> preferenceLanguage = new Preference<Language>();
|
595 |
-
Language language = new Language("zh_CN", "");
|
596 |
-
preferenceLanguage.setMetadata(language);
|
597 |
-
acceptedLanguages.add(preferenceLanguage);
|
598 |
-
|
599 |
-
clientInfo.setAcceptedLanguages(acceptedLanguages);
|
600 |
-
request.setClientInfo(clientInfo);
|
601 |
-
}
|
602 |
-
|
603 |
-
private static class TrustAnyTrustManager implements X509TrustManager
|
604 |
-
{
|
605 |
-
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
|
606 |
-
{
|
607 |
-
}
|
608 |
-
|
609 |
-
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
|
610 |
-
{
|
611 |
-
}
|
612 |
-
|
613 |
-
public X509Certificate[] getAcceptedIssuers()
|
614 |
-
{
|
615 |
-
return new X509Certificate[] {};
|
616 |
-
}
|
617 |
-
}
|
618 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10009.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/** * Copyright 2015 Huawei Technologies Co., Ltd. All rights reserved. * eSDK is licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.huawei.esdk.fusioncompute.local.impl.restlet;import java.io.IOException;import java.io.InputStream;import java.security.KeyManagementException;import java.security.KeyStore;import java.security.KeyStoreException;import java.security.NoSuchAlgorithmException;import java.security.NoSuchProviderException;import java.security.SecureRandom;import java.security.cert.CertificateException;import java.security.cert.X509Certificate;import java.util.ArrayList;import java.util.List;import javax.net.ssl.HostnameVerifier;import javax.net.ssl.SSLContext;import javax.net.ssl.SSLSession;import javax.net.ssl.TrustManager;import javax.net.ssl.TrustManagerFactory;import javax.net.ssl.X509TrustManager;import org.apache.log4j.Logger;import org.restlet.Client;import org.restlet.Context;import org.restlet.Request;import org.restlet.Response;import org.restlet.data.ClientInfo;import org.restlet.data.Header;import org.restlet.data.Language;import org.restlet.data.MediaType;import org.restlet.data.Method;import org.restlet.data.Parameter;import org.restlet.data.Preference;import org.restlet.data.Protocol;import org.restlet.engine.header.HeaderConstants;import org.restlet.engine.ssl.SslContextFactory;import org.restlet.representation.Representation;import org.restlet.util.Series;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.local.impl.SDKClient;import com.huawei.esdk.fusioncompute.local.impl.constant.ESDKURL;import com.huawei.esdk.fusioncompute.local.impl.constant.NativeConstant;import com.huawei.esdk.fusioncompute.local.impl.constant.SSLParameter;import com.huawei.esdk.fusioncompute.local.impl.utils.AuthenticateCacheBean;import com.huawei.esdk.fusioncompute.local.impl.utils.EsdkVRMException;import com.huawei.esdk.fusioncompute.local.impl.utils.FCCacheHolder;import com.huawei.esdk.fusioncompute.local.impl.utils.LogConfig;import com.huawei.esdk.fusioncompute.local.impl.utils.LogUtil;import com.huawei.esdk.fusioncompute.local.impl.utils.SHA256Utils;import com.huawei.esdk.fusioncompute.local.impl.utils.StringUtils;import com.huawei.esdk.fusioncompute.local.impl.utils.URLUtils;import com.huawei.esdk.fusioncompute.local.model.ClientProviderBean;import com.huawei.esdk.fusioncompute.local.model.SDKCommonResp;public class RestletClient implements SDKClient{ private static final Logger LOGGER = Logger.getLogger(RestletClient.class); private ClientProviderBean bean; private static final int HTTP_STATUS_CODE_OK = 200; private static final int HTTP_STATUS_CODE_NOT_FOUND = 404; private static final int HTTP_STATUS_CODE_UNAUTHORIZED = 401; private static final int HTTP_STATUS_CODE_FORBIDDEN = 403; private static final int CONNECTOR_ERROR_COMMUNICATION = 1001; private static final int CONNECTOR_ERROR_CONNECTION = 1000; private static final String PROTOCOL_HTTPS = "https"; private static final String X_AUTH_USER = "X-Auth-User"; private static final String X_AUTH_KEY = "X-Auth-Key"; private static final String X_AUTH_TOKEN = "X-Auth-Token"; private String version; private int flag = 0; private Gson gson = new Gson(); private ESDKURL esdkUrl = new ESDKURL(); public RestletClient(ClientProviderBean bean) { this.flag = bean.getTimes(); this.bean = bean; this.version = StringUtils.convertString(bean.getVersion()); } @Override public String get(String url, String methodName) throws Exception { return invoke(Method.GET, url, null, methodName); } @Override public String post(String url, Object msg, String methodName) throws Exception { return invoke(Method.POST, url, msg, methodName); } @Override public String put(String url, Object msg, String methodName) throws Exception { return invoke(Method.PUT, url, msg, methodName); } @Override public String delete(String url, String methodName) throws Exception { return invoke(Method.DELETE, url, null, methodName); } // 带密码打印日志 public String invokeNoLog(Method method, String url, Object msg, String methodName) throws Exception { return invokeRun(method, url, msg, methodName); } // 普通处理 不带密码打印日志 private String invoke(Method method, String url, Object msg, String methodName) throws Exception { String resp = null; //LOGGER.info("request body:" + gson.toJson(msg)); resp = invokeRun(method, url, msg, methodName); //LOGGER.info("response:" + resp); return resp; } private String invokeRun(Method method, String url, Object msg, String methodName) throws Exception { Client client = null; if (PROTOCOL_HTTPS.equalsIgnoreCase(bean.getProtocol())) { client = configSSL(bean.getKeyStoreName(), bean.getKeyStorePassword(), bean.getValidateCertificate()); } else { //初始客户端对象 client = new Client(new Context(), Protocol.HTTP); } Request request = new Request(method, url); String requestStr = null; if (null != msg) { requestStr = gson.toJson(msg); } String req_log = requestStr; if (requestStr != null) { if (LogConfig.checkUrl(url)) { req_log = LogConfig.replaceWord(requestStr); } } //设置标准http header if (null != url && url.endsWith("/service/versions")) { setDefaultHttpHeader(request, null); } else { // 2016.06.22 版本自适应 setDefaultHttpHeader(request, "version=" + version + ";"); } //自定义消息头 Series<Header> extraHeaders = new Series<Header>(Header.class); if (null != FCCacheHolder.getAuthenticateCache(bean)) { extraHeaders.add(X_AUTH_TOKEN, FCCacheHolder.getAuthenticateCache(bean).getToken()); } request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, extraHeaders); if (!StringUtils.isEmpty(requestStr)) { request.setEntity(requestStr, MediaType.APPLICATION_JSON); } //LOGGER.info("request url:" + request); client.getContext().getParameters().add("socketConnectTimeoutMs", String.valueOf(20000)); client.getContext().getParameters().add("readTimeout", String.valueOf(20000)); // 消息发送时间 String reqTime = LogUtil.getSysTime(); Response response = client.handle(request); // 消息接受时间 String respTime = LogUtil.getSysTime(); //LOGGER.info("http status code:" + response.getStatus().getCode()); Representation output = response.getEntity(); if (null == output) { SDKCommonResp error = new SDKCommonResp(); error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION); error.setErrorDes("Not Found"); EsdkVRMException exception = new EsdkVRMException("Not Found"); exception.setErrInfo(error); bean.setTimes(flag); LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode())); throw exception; } String resp = output.getText(); if (HTTP_STATUS_CODE_NOT_FOUND == response.getStatus().getCode()) { SDKCommonResp error = new SDKCommonResp(); error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION); error.setErrorDes(response.getStatus().getDescription()); EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription()); exception.setErrInfo(error); bean.setTimes(flag); LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode())); throw exception; } else if (HTTP_STATUS_CODE_UNAUTHORIZED == response.getStatus().getCode()) { if (bean.getTimes() >= 1 && !StringUtils.isEmpty(FCCacheHolder.getLoginUser(bean))) { this.login(URLUtils.makeUrl(bean, esdkUrl.getAuthenticateUrl(), null), FCCacheHolder.getAuthenticateCache(bean) .getUserName(), FCCacheHolder.getAuthenticateCache(bean).getPassword(), "Login"); bean.setTimes(bean.getTimes() - 1); // 2015-11-09 修改二次请求消息格式错误问题。 return this.invokeRun(method, url, msg, methodName); } SDKCommonResp error = new SDKCommonResp(); error.setErrorCode(NativeConstant.UNAUTHORIZED_EXCEPTION); error.setErrorDes(response.getStatus().getDescription()); EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription()); exception.setErrInfo(error); bean.setTimes(flag); LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode())); throw exception; } else if (HTTP_STATUS_CODE_FORBIDDEN == response.getStatus().getCode()) { SDKCommonResp error = new SDKCommonResp(); error.setErrorCode(NativeConstant.FORBIDDEN_EXCEPTION); error.setErrorDes(response.getStatus().getDescription()); EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription()); exception.setErrInfo(error); bean.setTimes(flag); LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode())); throw exception; } else if (CONNECTOR_ERROR_COMMUNICATION == response.getStatus().getCode()) { SDKCommonResp error = new SDKCommonResp(); error.setErrorCode(NativeConstant.COMMUNICATION_EXCEPTION); error.setErrorDes(response.getStatus().getDescription()); EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription()); exception.setErrInfo(error); bean.setTimes(flag); LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode())); throw exception; } else if (HTTP_STATUS_CODE_OK != response.getStatus().getCode()) { SDKCommonResp error = gson.fromJson(resp, SDKCommonResp.class); EsdkVRMException exception = null; if (null == error) { error = new SDKCommonResp(); error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION); error.setErrorDes("Not Found"); exception = new EsdkVRMException("Not Found"); exception.setErrInfo(error); } else { exception = new EsdkVRMException(error.getErrorDes()); exception.setErrInfo(error); } bean.setTimes(flag); LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method.getName(), req_log, response.getStatus().getCode(), error.getErrorCode())); throw exception; } bean.setTimes(flag); // 2014.11.11 By y00206201 整改日志 添加 String resp_log = resp; if (resp != null) { if (LogConfig.checkUrl(url)) { resp_log = LogConfig.replaceWord(resp); } } LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.infoLogType, LogConfig.product, reqTime, respTime, url, method.getName(), req_log, response.getStatus().getCode(), resp_log)); return resp; } @Override public String login(String url, String userName, String password, String methodName) throws Exception { Client client = null; if (PROTOCOL_HTTPS.equalsIgnoreCase(bean.getProtocol())) { client = configSSL(bean.getKeyStoreName(), bean.getKeyStorePassword(), bean.getValidateCertificate()); } else { //初始客户端对象 client = new Client(new Context(), Protocol.HTTP); } Request request = new Request(Method.POST, url); //设置自定义header Series<Header> extraHeaders = new Series<Header>(Header.class); extraHeaders.add(X_AUTH_USER, userName); extraHeaders.add(X_AUTH_KEY, SHA256Utils.encrypt(password)); request.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, extraHeaders); //设置标准http header 2016.06.22 适配版本 setDefaultHttpHeader(request, "version=" + version + ";"); //LOGGER.info("request url:" + request); //LOGGER.info("request header:" + extraHeaders); //设置连接超时时间 client.getContext().getParameters().add("socketConnectTimeoutMs", String.valueOf(20000)); client.getContext().getParameters().add("readTimeout", String.valueOf(20000)); // 2014.11.11 By y00206201 整改日志 添加 // 日志类型 // 业务 // 南北向接口类型 默认 // 协议类型 默认 // 方法名 对于Rest接口而言就是url + method // 源Ip // 目的Ip 从Url解析 // 事务标识 默认 // 发送消息给产品时间 // 从产品接受消息时间 // 消息体 String method = LogUtil.POST; String body = ""; // 消息请求时间 String reqTime = LogUtil.getSysTime(); //发送请求 Response response = client.handle(request); // 消息响应时间 String respTime = LogUtil.getSysTime(); //LOGGER.info("http status code:" + response.getStatus().getCode()); if (CONNECTOR_ERROR_COMMUNICATION == response.getStatus().getCode() || CONNECTOR_ERROR_CONNECTION == response.getStatus().getCode()) { SDKCommonResp error = new SDKCommonResp(); error.setErrorCode(NativeConstant.COMMUNICATION_EXCEPTION); error.setErrorDes(response.getStatus().getDescription()); EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription()); exception.setErrInfo(error); LOGGER.error(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method, body, response.getStatus().getCode(), error.getErrorCode())); throw exception; } if (HTTP_STATUS_CODE_NOT_FOUND == response.getStatus().getCode()) { SDKCommonResp error = new SDKCommonResp(); error.setErrorCode(NativeConstant.NOT_FOUND_EXCEPTION); error.setErrorDes(response.getStatus().getDescription()); EsdkVRMException exception = new EsdkVRMException(response.getStatus().getDescription()); exception.setErrInfo(error); LOGGER.error(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method, body, response.getStatus().getCode(), error.getErrorCode())); throw exception; } Representation output = response.getEntity(); String resp = output.getText(); if (HTTP_STATUS_CODE_OK != response.getStatus().getCode()) { SDKCommonResp error = gson.fromJson(resp, SDKCommonResp.class); EsdkVRMException exception = new EsdkVRMException(error.getErrorDes()); exception.setErrInfo(error); LOGGER.error(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.errorLogType, LogConfig.product, reqTime, respTime, url, method, body, response.getStatus().getCode(), resp)); throw exception; } //获取responseHeader @SuppressWarnings("unchecked") Series<Header> respHeader = (Series<Header>) response.getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); String token = respHeader.getValues(X_AUTH_TOKEN); if (null != token) { AuthenticateCacheBean authenticateCacheBean = new AuthenticateCacheBean(); authenticateCacheBean.setToken(token); authenticateCacheBean.setUserName(userName); authenticateCacheBean.setPassword(password); //保存token FCCacheHolder.saveAuthenticateCache(bean, authenticateCacheBean); } // 2014.11.11 By y00206201 整改日志 添加 LOGGER.info(LogUtil.infLogForRest(LogUtil.getSysTime(), methodName, LogUtil.infoLogType, LogConfig.product, reqTime, respTime, url, method, body, response.getStatus().getCode(), resp)); return resp; } private static Client configSSL(String keyStoreName, String keyStorePassword, Boolean validateCertificate) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException { // BUG: CWE-326: Inadequate Encryption Strength// final SSLContext sslContext = SSLContext.getInstance("TLS");// FIXED: if (!validateCertificate) { //信任所有证书 sslContext.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new SecureRandom()); } else { if (null == keyStoreName || null == keyStorePassword) { return new Client(new Context(), Protocol.HTTPS); } KeyStore keyStore = KeyStore.getInstance(SSLParameter.KEYSTORE_TYPE, SSLParameter.KEYSTORE_PROVIDER); InputStream is = (InputStream) ClassLoader.getSystemClassLoader().getResourceAsStream(keyStoreName); if (null == is) { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreName); } keyStore.load(is, keyStorePassword.toCharArray()); try { is.close(); } catch (NullPointerException e) { LOGGER.error(LogUtil.runLog(LogUtil.errorLogType, "RestletClient.configSSL", "InputStream is null,and e = " + e)); } catch (IOException e) { LOGGER.error(LogUtil.runLog(LogUtil.errorLogType, "RestletClient.configSSL", "RestletClient.configSSL IOException,and e = " + e)); } finally { if (null != is) { try { is.close(); } catch (IOException e) { LOGGER.error(LogUtil.runLog(LogUtil.errorLogType, "RestletClient.configSSL", "Exception happened in RestletClient.configSSL,and e = " + e)); } } } TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustFactory.init(keyStore); TrustManager[] trustManagers = trustFactory.getTrustManagers(); //信任证书 sslContext.init(null, trustManagers, new SecureRandom()); } Context context = new Context(); context.getAttributes().put("hostnameVerifier", new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslsession) { return true; } }); context.getAttributes().put("sslContextFactory", new SslContextFactory() { @Override public void init(Series<Parameter> parameter) { } @Override public SSLContext createSslContext() throws Exception { return sslContext; } }); Client client = new Client(context, Protocol.HTTPS); return client; } /** * 设置标准http header * * @param request {@code void} * @since eSDK Cloud V100R003C50 */ private void setDefaultHttpHeader(Request request, String version) { ClientInfo clientInfo = new ClientInfo(); List<Preference<MediaType>> acceptedMediaTypes = new ArrayList<Preference<MediaType>>(); Preference<MediaType> preferenceMediaType = new Preference<MediaType>(); String acceptStr = "application/json;"; if (null == version) { acceptStr += "charset=UTF-8;"; } else { acceptStr += version + "charset=UTF-8;"; } MediaType mediaType = MediaType.register(acceptStr, ""); preferenceMediaType.setMetadata(mediaType); acceptedMediaTypes.add(preferenceMediaType); clientInfo.setAcceptedMediaTypes(acceptedMediaTypes); List<Preference<Language>> acceptedLanguages = new ArrayList<Preference<Language>>(); Preference<Language> preferenceLanguage = new Preference<Language>(); Language language = new Language("zh_CN", ""); preferenceLanguage.setMetadata(language); acceptedLanguages.add(preferenceLanguage); clientInfo.setAcceptedLanguages(acceptedLanguages); request.setClientInfo(clientInfo); } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } }}
|
data/java/10010.java
DELETED
@@ -1,410 +0,0 @@
|
|
1 |
-
/**
|
2 |
-
* Copyright 2015 Huawei Technologies Co., Ltd. All rights reserved.
|
3 |
-
* eSDK is licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
* you may not use this file except in compliance with the License.
|
5 |
-
* You may obtain a copy of the License at
|
6 |
-
*
|
7 |
-
* http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
*
|
9 |
-
* Unless required by applicable law or agreed to in writing, software
|
10 |
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
* See the License for the specific language governing permissions and
|
13 |
-
* limitations under the License.
|
14 |
-
*/
|
15 |
-
package com.huawei.esdk.fusioncompute.local.impl.utils;
|
16 |
-
|
17 |
-
import java.io.File;
|
18 |
-
import java.io.IOException;
|
19 |
-
import java.io.UnsupportedEncodingException;
|
20 |
-
import java.nio.charset.Charset;
|
21 |
-
import java.security.KeyManagementException;
|
22 |
-
import java.security.NoSuchAlgorithmException;
|
23 |
-
import java.util.Random;
|
24 |
-
import java.util.concurrent.TimeUnit;
|
25 |
-
|
26 |
-
import javax.net.ssl.SSLContext;
|
27 |
-
import javax.net.ssl.TrustManager;
|
28 |
-
import javax.net.ssl.X509TrustManager;
|
29 |
-
|
30 |
-
import org.apache.commons.io.FileUtils;
|
31 |
-
import org.apache.http.HttpEntity;
|
32 |
-
import org.apache.http.HttpResponse;
|
33 |
-
import org.apache.http.client.ClientProtocolException;
|
34 |
-
import org.apache.http.client.HttpClient;
|
35 |
-
import org.apache.http.client.methods.HttpPost;
|
36 |
-
import org.apache.http.conn.scheme.Scheme;
|
37 |
-
import org.apache.http.conn.scheme.SchemeRegistry;
|
38 |
-
import org.apache.http.conn.ssl.SSLSocketFactory;
|
39 |
-
import org.apache.http.entity.mime.HttpMultipartMode;
|
40 |
-
import org.apache.http.entity.mime.MultipartEntity;
|
41 |
-
import org.apache.http.entity.mime.content.FileBody;
|
42 |
-
import org.apache.http.entity.mime.content.StringBody;
|
43 |
-
import org.apache.http.impl.client.DefaultHttpClient;
|
44 |
-
import org.apache.http.util.EntityUtils;
|
45 |
-
import org.apache.log4j.Level;
|
46 |
-
import org.apache.log4j.LogManager;
|
47 |
-
import org.apache.log4j.Logger;
|
48 |
-
import org.apache.log4j.RollingFileAppender;
|
49 |
-
|
50 |
-
public class LogFileUploaderTask implements Runnable
|
51 |
-
{
|
52 |
-
// private static final Logger LOGGER = Logger.getLogger(LogFileUploaderTask.class);
|
53 |
-
|
54 |
-
private long getSleepTime()
|
55 |
-
{
|
56 |
-
Random generator = new Random();
|
57 |
-
double num = generator.nextDouble() / 2;
|
58 |
-
|
59 |
-
// long result =
|
60 |
-
// (long)(60L * NumberUtils.parseIntValue(ConfigManager.getInstance()
|
61 |
-
// .getValue("platform.upload.log.file.interval", "60")) * num);
|
62 |
-
long result = (long)(60L * num);
|
63 |
-
|
64 |
-
return result;
|
65 |
-
}
|
66 |
-
|
67 |
-
@Override
|
68 |
-
public void run()
|
69 |
-
{
|
70 |
-
try
|
71 |
-
{
|
72 |
-
long sleepTime;
|
73 |
-
while (true)
|
74 |
-
{
|
75 |
-
sleepTime = getSleepTime();
|
76 |
-
LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "sleepTime=" + sleepTime);
|
77 |
-
//LOGGER.debug("sleepTime=" + sleepTime);
|
78 |
-
|
79 |
-
TimeUnit.SECONDS.sleep(sleepTime);
|
80 |
-
|
81 |
-
try
|
82 |
-
{
|
83 |
-
//upload Logs
|
84 |
-
uploadLogFiles();
|
85 |
-
}
|
86 |
-
catch (Exception e)
|
87 |
-
{
|
88 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e=" + e);
|
89 |
-
}
|
90 |
-
}
|
91 |
-
}
|
92 |
-
catch (InterruptedException e)
|
93 |
-
//catch (Exception e)
|
94 |
-
{
|
95 |
-
//InterruptedException Exception happened
|
96 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e=" + e);
|
97 |
-
//LOGGER.error("", e);
|
98 |
-
}
|
99 |
-
}
|
100 |
-
|
101 |
-
public void uploadLogFiles()
|
102 |
-
{
|
103 |
-
|
104 |
-
LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "uploadLogFiles begin");
|
105 |
-
//LOGGER.debug("uploadLogFiles begin");
|
106 |
-
HttpClient httpClient = new DefaultHttpClient();
|
107 |
-
prepareFo4Https(httpClient);
|
108 |
-
//httpClient = configSSL(httpClient);
|
109 |
-
|
110 |
-
//String[] logTypes = new String[]{"run", "interface", "operation"};
|
111 |
-
String[] logTypes = new String[] {"interface"};
|
112 |
-
String logFile;
|
113 |
-
File file;
|
114 |
-
boolean currentWritingLogFileFlag = false;
|
115 |
-
for (String logType : logTypes)
|
116 |
-
{
|
117 |
-
//Reset variables
|
118 |
-
currentWritingLogFileFlag = false;
|
119 |
-
|
120 |
-
//Loop all log files for specified log type
|
121 |
-
while (true)
|
122 |
-
{
|
123 |
-
logFile = LogFileUploaderHelper.getOldestLogFile(logType);
|
124 |
-
//LOGGER.debug("logFile=" + logFile);
|
125 |
-
LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "logFile=" + logFile);
|
126 |
-
if (StringUtils.isEmpty(logFile)
|
127 |
-
|| (currentWritingLogFileFlag && !LogFileUploaderHelper.isBackLogFile(logFile)))
|
128 |
-
{
|
129 |
-
break;
|
130 |
-
}
|
131 |
-
else
|
132 |
-
{
|
133 |
-
if (!LogFileUploaderHelper.isBackLogFile(logFile))
|
134 |
-
{
|
135 |
-
currentWritingLogFileFlag = true;
|
136 |
-
}
|
137 |
-
file = new File(logFile);
|
138 |
-
if (0 == file.length())
|
139 |
-
{
|
140 |
-
continue;
|
141 |
-
}
|
142 |
-
|
143 |
-
if (!LogFileUploaderHelper.isBackLogFile(logFile))
|
144 |
-
{
|
145 |
-
logFile = processCurrentLogFile(logType, logFile);
|
146 |
-
}
|
147 |
-
if (StringUtils.isEmpty(logFile))
|
148 |
-
{
|
149 |
-
continue;
|
150 |
-
}
|
151 |
-
logFile = moveFile(logFile);
|
152 |
-
|
153 |
-
if (doLogFileUpload(httpClient, logFile, "eSDK-Server"))
|
154 |
-
{
|
155 |
-
LogFileUploaderHelper.deleteLogFile(logFile);
|
156 |
-
}
|
157 |
-
}
|
158 |
-
}
|
159 |
-
}
|
160 |
-
|
161 |
-
LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "uploadLogFiles end");
|
162 |
-
//LOGGER.debug("uploadLogFiles end");
|
163 |
-
}
|
164 |
-
|
165 |
-
private static void prepareFo4Https(HttpClient httpClient)
|
166 |
-
{
|
167 |
-
String serverUrl = LogUtil.getInstance().getLogUrl();
|
168 |
-
if (!serverUrl.startsWith("https"))
|
169 |
-
{
|
170 |
-
return;
|
171 |
-
}
|
172 |
-
try
|
173 |
-
{
|
174 |
-
// SSLContext ctx = SSLContext.getInstance(ESDKConstant.SSL_SECURE_SOCKET_PROTOCOL);
|
175 |
-
|
176 |
-
// BUG: CWE-326: Inadequate Encryption Strength
|
177 |
-
// SSLContext ctx = SSLContext.getInstance("TLS");//TLS SSL
|
178 |
-
// FIXED:
|
179 |
-
|
180 |
-
X509TrustManager tm = new X509TrustManager()
|
181 |
-
{
|
182 |
-
public java.security.cert.X509Certificate[] getAcceptedIssuers()
|
183 |
-
{
|
184 |
-
return new java.security.cert.X509Certificate[] {};
|
185 |
-
}
|
186 |
-
|
187 |
-
@Override
|
188 |
-
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
|
189 |
-
throws java.security.cert.CertificateException
|
190 |
-
{
|
191 |
-
}
|
192 |
-
|
193 |
-
@Override
|
194 |
-
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
|
195 |
-
throws java.security.cert.CertificateException
|
196 |
-
{
|
197 |
-
}
|
198 |
-
|
199 |
-
};
|
200 |
-
ctx.init(null, new TrustManager[] {tm}, null);
|
201 |
-
//ctx.init(null, new TrustManager[] {tm}, new SecureRandom());
|
202 |
-
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
|
203 |
-
SchemeRegistry registry = httpClient.getConnectionManager().getSchemeRegistry();
|
204 |
-
// registry.register(new Scheme(ESDKConstant.PROTOCOL_ADAPTER_TYPE_HTTPS,
|
205 |
-
registry.register(new Scheme("https", Integer.parseInt(serverUrl.substring(serverUrl.lastIndexOf(":") + 1,
|
206 |
-
serverUrl.indexOf("/", 8))), ssf));
|
207 |
-
|
208 |
-
//ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry);
|
209 |
-
//httpClient = new DefaultHttpClient(mgr, httpClient.getParams());
|
210 |
-
|
211 |
-
}
|
212 |
-
catch (KeyManagementException e)
|
213 |
-
{
|
214 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "https error and e = " + e);
|
215 |
-
//LOGGER.error("https error", e);
|
216 |
-
}
|
217 |
-
catch (NoSuchAlgorithmException e)
|
218 |
-
{
|
219 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "https error and e = " + e);
|
220 |
-
//LOGGER.error("https error", e);
|
221 |
-
}
|
222 |
-
}
|
223 |
-
|
224 |
-
private String moveFile(String logFile)
|
225 |
-
{
|
226 |
-
if (StringUtils.isEmpty(logFile))
|
227 |
-
{
|
228 |
-
return logFile;
|
229 |
-
}
|
230 |
-
|
231 |
-
File file = new File(logFile);
|
232 |
-
//Move the file to temp folder for uploading
|
233 |
-
File destFile = new File(file.getParent() + File.separator + "temp" + File.separator + file.getName());
|
234 |
-
try
|
235 |
-
{
|
236 |
-
if (destFile.exists())
|
237 |
-
{
|
238 |
-
destFile.delete();
|
239 |
-
}
|
240 |
-
FileUtils.moveFile(file, destFile);
|
241 |
-
file = destFile;
|
242 |
-
}
|
243 |
-
catch (IOException e)
|
244 |
-
{
|
245 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "https error and e = " + e);
|
246 |
-
//LOGGER.error("", e);
|
247 |
-
}
|
248 |
-
|
249 |
-
return file.getPath();
|
250 |
-
}
|
251 |
-
|
252 |
-
private String processCurrentLogFile(String logType, String logFile)
|
253 |
-
{
|
254 |
-
File file = new File(logFile);
|
255 |
-
//Different appenders for different file types
|
256 |
-
RollingFileAppender appender = null;
|
257 |
-
if ("interface".equalsIgnoreCase(logType))
|
258 |
-
{
|
259 |
-
|
260 |
-
// appender = (RollingFileAppender) Logger.getLogger("com.huawei.esdk.platform.log.InterfaceLog").getAppender("FILE1");
|
261 |
-
|
262 |
-
try
|
263 |
-
{
|
264 |
-
File destDir = new File(file.getParent() + File.separator + "temp" + File.separator + file.getName());
|
265 |
-
FileUtils.moveFile(file, destDir);
|
266 |
-
FileUtils.moveFile(destDir, file);
|
267 |
-
return logFile;
|
268 |
-
}
|
269 |
-
catch (IOException e)
|
270 |
-
{
|
271 |
-
return "";
|
272 |
-
}
|
273 |
-
}
|
274 |
-
else if ("operation".equalsIgnoreCase(logType))
|
275 |
-
{
|
276 |
-
try
|
277 |
-
{
|
278 |
-
File destDir = new File(file.getParent() + File.separator + "temp" + File.separator + file.getName());
|
279 |
-
FileUtils.moveFile(file, destDir);
|
280 |
-
FileUtils.moveFile(destDir, file);
|
281 |
-
return logFile;
|
282 |
-
}
|
283 |
-
catch (IOException e)
|
284 |
-
{
|
285 |
-
return "";
|
286 |
-
}
|
287 |
-
}
|
288 |
-
else
|
289 |
-
{
|
290 |
-
appender = (RollingFileAppender)Logger.getRootLogger().getAppender("fileLogger");
|
291 |
-
}
|
292 |
-
|
293 |
-
if (null == appender)
|
294 |
-
{
|
295 |
-
return "";
|
296 |
-
}
|
297 |
-
long origSize = appender.getMaximumFileSize();
|
298 |
-
appender.setMaximumFileSize(file.length());
|
299 |
-
if ("interface".equalsIgnoreCase(logType))
|
300 |
-
{
|
301 |
-
LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "Rolling the interface log file");
|
302 |
-
//LOGGER.debug("Rolling the interface log file");
|
303 |
-
//Call the rooOver method in order to backup the current log file for uploading
|
304 |
-
appender.rollOver();
|
305 |
-
}
|
306 |
-
else
|
307 |
-
{
|
308 |
-
//Call the rooOver method in order to backup the current log file for uploading
|
309 |
-
appender.rollOver();
|
310 |
-
LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "Log File size reset");
|
311 |
-
//LOGGER.debug("Log File size reset");
|
312 |
-
}
|
313 |
-
LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "origSize=" + origSize + ", logType=" + logType);
|
314 |
-
//LOGGER.debug("origSize=" + origSize + ", logType=" + logType);
|
315 |
-
appender.setMaximumFileSize(origSize);
|
316 |
-
String result = logFile + ".1";
|
317 |
-
file = new File(result);
|
318 |
-
if (file.exists())
|
319 |
-
{
|
320 |
-
return result;
|
321 |
-
}
|
322 |
-
else
|
323 |
-
{
|
324 |
-
return "";
|
325 |
-
}
|
326 |
-
}
|
327 |
-
|
328 |
-
private boolean doLogFileUpload(HttpClient httpClient, String fileNameWithPath, String product)
|
329 |
-
{
|
330 |
-
if (StringUtils.isEmpty(fileNameWithPath))
|
331 |
-
{
|
332 |
-
return true;
|
333 |
-
}
|
334 |
-
//当前日志文件正在写的场景
|
335 |
-
//xx.log.1被xx.log覆盖-xx.log.2被xx.log.1覆盖,删除上传都会有问题如何处理
|
336 |
-
HttpPost httpPost = buildHttpPost(fileNameWithPath, product);
|
337 |
-
HttpResponse httpResponse;
|
338 |
-
try
|
339 |
-
{
|
340 |
-
String packageName = "org.apache.http.wire";
|
341 |
-
Logger logger = LogManager.getLogger(packageName);
|
342 |
-
String backupLevel;
|
343 |
-
if (null != logger && null != logger.getLevel())
|
344 |
-
{
|
345 |
-
backupLevel = logger.getLevel().toString();
|
346 |
-
}
|
347 |
-
else
|
348 |
-
{
|
349 |
-
logger = LogManager.getRootLogger();
|
350 |
-
Level level = logger.getLevel();
|
351 |
-
if (null != level)
|
352 |
-
{
|
353 |
-
backupLevel = level.toString();
|
354 |
-
}
|
355 |
-
else
|
356 |
-
{
|
357 |
-
backupLevel = "INFO";
|
358 |
-
}
|
359 |
-
}
|
360 |
-
LogFileUploaderHelper.setLoggerLevel(packageName, "INFO");
|
361 |
-
httpResponse = httpClient.execute(httpPost);
|
362 |
-
LogFileUploaderHelper.setLoggerLevel(packageName, backupLevel);
|
363 |
-
HttpEntity httpEntity = httpResponse.getEntity();
|
364 |
-
String content = EntityUtils.toString(httpEntity);
|
365 |
-
if (content.contains("\"resultCode\":\"0\""))
|
366 |
-
{
|
367 |
-
return true;
|
368 |
-
}
|
369 |
-
else
|
370 |
-
{
|
371 |
-
LogUtil.runLog(LogUtil.warningLogType, "LogFileUploaderTask", "File file " + fileNameWithPath
|
372 |
-
+ " is uploaded to log server failed," + " the response from server is " + content);
|
373 |
-
//LOGGER.warn("File file " + fileNameWithPath + " is uploaded to log server failed,"
|
374 |
-
// + " the response from server is " + content);
|
375 |
-
}
|
376 |
-
}
|
377 |
-
catch (ClientProtocolException e)
|
378 |
-
{
|
379 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e = " + e);
|
380 |
-
//LOGGER.error("", e);
|
381 |
-
}
|
382 |
-
catch (IOException e)
|
383 |
-
{
|
384 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e = " + e);
|
385 |
-
//LOGGER.error("", e);
|
386 |
-
}
|
387 |
-
|
388 |
-
return false;
|
389 |
-
}
|
390 |
-
|
391 |
-
private HttpPost buildHttpPost(String fileNameWithPath, String product)
|
392 |
-
{
|
393 |
-
HttpPost httpPost = new HttpPost(LogUtil.getInstance().getLogUrl());
|
394 |
-
MultipartEntity mutiEntity = new MultipartEntity(HttpMultipartMode.STRICT);
|
395 |
-
httpPost.setEntity(mutiEntity);
|
396 |
-
File file = new File(fileNameWithPath);
|
397 |
-
try
|
398 |
-
{
|
399 |
-
mutiEntity.addPart("LogFileInfo",
|
400 |
-
new StringBody("{\"product\":\"" + product + "\"}", Charset.forName("UTF-8")));
|
401 |
-
}
|
402 |
-
catch (UnsupportedEncodingException e)
|
403 |
-
{
|
404 |
-
LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "UTF-8 is not supported encode");
|
405 |
-
//LOGGER.error("UTF-8 is not supported encode");
|
406 |
-
}
|
407 |
-
mutiEntity.addPart("LogFile", new FileBody(file));
|
408 |
-
return httpPost;
|
409 |
-
}
|
410 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10010.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/** * Copyright 2015 Huawei Technologies Co., Ltd. All rights reserved. * eSDK is licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */package com.huawei.esdk.fusioncompute.local.impl.utils;import java.io.File;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.nio.charset.Charset;import java.security.KeyManagementException;import java.security.NoSuchAlgorithmException;import java.util.Random;import java.util.concurrent.TimeUnit;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import javax.net.ssl.X509TrustManager;import org.apache.commons.io.FileUtils;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.scheme.Scheme;import org.apache.http.conn.scheme.SchemeRegistry;import org.apache.http.conn.ssl.SSLSocketFactory;import org.apache.http.entity.mime.HttpMultipartMode;import org.apache.http.entity.mime.MultipartEntity;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import org.apache.log4j.Level;import org.apache.log4j.LogManager;import org.apache.log4j.Logger;import org.apache.log4j.RollingFileAppender;public class LogFileUploaderTask implements Runnable{ // private static final Logger LOGGER = Logger.getLogger(LogFileUploaderTask.class); private long getSleepTime() { Random generator = new Random(); double num = generator.nextDouble() / 2; // long result = // (long)(60L * NumberUtils.parseIntValue(ConfigManager.getInstance() // .getValue("platform.upload.log.file.interval", "60")) * num); long result = (long)(60L * num); return result; } @Override public void run() { try { long sleepTime; while (true) { sleepTime = getSleepTime(); LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "sleepTime=" + sleepTime); //LOGGER.debug("sleepTime=" + sleepTime); TimeUnit.SECONDS.sleep(sleepTime); try { //upload Logs uploadLogFiles(); } catch (Exception e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e=" + e); } } } catch (InterruptedException e) //catch (Exception e) { //InterruptedException Exception happened LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e=" + e); //LOGGER.error("", e); } } public void uploadLogFiles() { LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "uploadLogFiles begin"); //LOGGER.debug("uploadLogFiles begin"); HttpClient httpClient = new DefaultHttpClient(); prepareFo4Https(httpClient); //httpClient = configSSL(httpClient); //String[] logTypes = new String[]{"run", "interface", "operation"}; String[] logTypes = new String[] {"interface"}; String logFile; File file; boolean currentWritingLogFileFlag = false; for (String logType : logTypes) { //Reset variables currentWritingLogFileFlag = false; //Loop all log files for specified log type while (true) { logFile = LogFileUploaderHelper.getOldestLogFile(logType); //LOGGER.debug("logFile=" + logFile); LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "logFile=" + logFile); if (StringUtils.isEmpty(logFile) || (currentWritingLogFileFlag && !LogFileUploaderHelper.isBackLogFile(logFile))) { break; } else { if (!LogFileUploaderHelper.isBackLogFile(logFile)) { currentWritingLogFileFlag = true; } file = new File(logFile); if (0 == file.length()) { continue; } if (!LogFileUploaderHelper.isBackLogFile(logFile)) { logFile = processCurrentLogFile(logType, logFile); } if (StringUtils.isEmpty(logFile)) { continue; } logFile = moveFile(logFile); if (doLogFileUpload(httpClient, logFile, "eSDK-Server")) { LogFileUploaderHelper.deleteLogFile(logFile); } } } } LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "uploadLogFiles end"); //LOGGER.debug("uploadLogFiles end"); } private static void prepareFo4Https(HttpClient httpClient) { String serverUrl = LogUtil.getInstance().getLogUrl(); if (!serverUrl.startsWith("https")) { return; } try { // SSLContext ctx = SSLContext.getInstance(ESDKConstant.SSL_SECURE_SOCKET_PROTOCOL); // BUG: CWE-326: Inadequate Encryption Strength// SSLContext ctx = SSLContext.getInstance("TLS");//TLS SSL// FIXED: X509TrustManager tm = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; ctx.init(null, new TrustManager[] {tm}, null); //ctx.init(null, new TrustManager[] {tm}, new SecureRandom()); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry registry = httpClient.getConnectionManager().getSchemeRegistry(); // registry.register(new Scheme(ESDKConstant.PROTOCOL_ADAPTER_TYPE_HTTPS, registry.register(new Scheme("https", Integer.parseInt(serverUrl.substring(serverUrl.lastIndexOf(":") + 1, serverUrl.indexOf("/", 8))), ssf)); //ThreadSafeClientConnManager mgr = new ThreadSafeClientConnManager(registry); //httpClient = new DefaultHttpClient(mgr, httpClient.getParams()); } catch (KeyManagementException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "https error and e = " + e); //LOGGER.error("https error", e); } catch (NoSuchAlgorithmException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "https error and e = " + e); //LOGGER.error("https error", e); } } private String moveFile(String logFile) { if (StringUtils.isEmpty(logFile)) { return logFile; } File file = new File(logFile); //Move the file to temp folder for uploading File destFile = new File(file.getParent() + File.separator + "temp" + File.separator + file.getName()); try { if (destFile.exists()) { destFile.delete(); } FileUtils.moveFile(file, destFile); file = destFile; } catch (IOException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "https error and e = " + e); //LOGGER.error("", e); } return file.getPath(); } private String processCurrentLogFile(String logType, String logFile) { File file = new File(logFile); //Different appenders for different file types RollingFileAppender appender = null; if ("interface".equalsIgnoreCase(logType)) { // appender = (RollingFileAppender) Logger.getLogger("com.huawei.esdk.platform.log.InterfaceLog").getAppender("FILE1"); try { File destDir = new File(file.getParent() + File.separator + "temp" + File.separator + file.getName()); FileUtils.moveFile(file, destDir); FileUtils.moveFile(destDir, file); return logFile; } catch (IOException e) { return ""; } } else if ("operation".equalsIgnoreCase(logType)) { try { File destDir = new File(file.getParent() + File.separator + "temp" + File.separator + file.getName()); FileUtils.moveFile(file, destDir); FileUtils.moveFile(destDir, file); return logFile; } catch (IOException e) { return ""; } } else { appender = (RollingFileAppender)Logger.getRootLogger().getAppender("fileLogger"); } if (null == appender) { return ""; } long origSize = appender.getMaximumFileSize(); appender.setMaximumFileSize(file.length()); if ("interface".equalsIgnoreCase(logType)) { LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "Rolling the interface log file"); //LOGGER.debug("Rolling the interface log file"); //Call the rooOver method in order to backup the current log file for uploading appender.rollOver(); } else { //Call the rooOver method in order to backup the current log file for uploading appender.rollOver(); LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "Log File size reset"); //LOGGER.debug("Log File size reset"); } LogUtil.runLog(LogUtil.debugLogType, "LogFileUploaderTask", "origSize=" + origSize + ", logType=" + logType); //LOGGER.debug("origSize=" + origSize + ", logType=" + logType); appender.setMaximumFileSize(origSize); String result = logFile + ".1"; file = new File(result); if (file.exists()) { return result; } else { return ""; } } private boolean doLogFileUpload(HttpClient httpClient, String fileNameWithPath, String product) { if (StringUtils.isEmpty(fileNameWithPath)) { return true; } //当前日志文件正在写的场景 //xx.log.1被xx.log覆盖-xx.log.2被xx.log.1覆盖,删除上传都会有问题如何处理 HttpPost httpPost = buildHttpPost(fileNameWithPath, product); HttpResponse httpResponse; try { String packageName = "org.apache.http.wire"; Logger logger = LogManager.getLogger(packageName); String backupLevel; if (null != logger && null != logger.getLevel()) { backupLevel = logger.getLevel().toString(); } else { logger = LogManager.getRootLogger(); Level level = logger.getLevel(); if (null != level) { backupLevel = level.toString(); } else { backupLevel = "INFO"; } } LogFileUploaderHelper.setLoggerLevel(packageName, "INFO"); httpResponse = httpClient.execute(httpPost); LogFileUploaderHelper.setLoggerLevel(packageName, backupLevel); HttpEntity httpEntity = httpResponse.getEntity(); String content = EntityUtils.toString(httpEntity); if (content.contains("\"resultCode\":\"0\"")) { return true; } else { LogUtil.runLog(LogUtil.warningLogType, "LogFileUploaderTask", "File file " + fileNameWithPath + " is uploaded to log server failed," + " the response from server is " + content); //LOGGER.warn("File file " + fileNameWithPath + " is uploaded to log server failed," // + " the response from server is " + content); } } catch (ClientProtocolException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e = " + e); //LOGGER.error("", e); } catch (IOException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "e = " + e); //LOGGER.error("", e); } return false; } private HttpPost buildHttpPost(String fileNameWithPath, String product) { HttpPost httpPost = new HttpPost(LogUtil.getInstance().getLogUrl()); MultipartEntity mutiEntity = new MultipartEntity(HttpMultipartMode.STRICT); httpPost.setEntity(mutiEntity); File file = new File(fileNameWithPath); try { mutiEntity.addPart("LogFileInfo", new StringBody("{\"product\":\"" + product + "\"}", Charset.forName("UTF-8"))); } catch (UnsupportedEncodingException e) { LogUtil.runLog(LogUtil.errorLogType, "LogFileUploaderTask", "UTF-8 is not supported encode"); //LOGGER.error("UTF-8 is not supported encode"); } mutiEntity.addPart("LogFile", new FileBody(file)); return httpPost; }}
|
data/java/10011.java
DELETED
@@ -1,156 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.servlet;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
import java.util.List;
|
6 |
-
|
7 |
-
import javax.servlet.ServletException;
|
8 |
-
import javax.servlet.http.HttpServlet;
|
9 |
-
import javax.servlet.http.HttpServletRequest;
|
10 |
-
import javax.servlet.http.HttpServletResponse;
|
11 |
-
|
12 |
-
import org.apache.log4j.Logger;
|
13 |
-
|
14 |
-
import com.google.gson.Gson;
|
15 |
-
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
|
16 |
-
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
18 |
-
import com.huawei.esdk.fusioncompute.local.model.PageList;
|
19 |
-
import com.huawei.esdk.fusioncompute.local.model.cluster.ClusterBasicInfo;
|
20 |
-
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
|
21 |
-
import com.huawei.esdk.fusioncompute.local.model.host.HostBasicInfo;
|
22 |
-
import com.huawei.esdk.fusioncompute.local.model.host.QueryHostListReq;
|
23 |
-
|
24 |
-
/**
|
25 |
-
* “查询VDC”请求处理类
|
26 |
-
* @author dWX213051
|
27 |
-
* @see
|
28 |
-
* @since eSDK Cloud V100R003C30
|
29 |
-
*/
|
30 |
-
public class QueryClusterAndHostServlet extends HttpServlet
|
31 |
-
{
|
32 |
-
/**
|
33 |
-
* 序列化版本标识
|
34 |
-
*/
|
35 |
-
private static final long serialVersionUID = 190954570327110271L;
|
36 |
-
|
37 |
-
/**
|
38 |
-
* log日志对象
|
39 |
-
*/
|
40 |
-
private static final Logger LOGGER = Logger
|
41 |
-
.getLogger(QueryClusterAndHostServlet.class);
|
42 |
-
|
43 |
-
/**
|
44 |
-
* gson,用于转换String和json之间的转换
|
45 |
-
*/
|
46 |
-
private Gson gson = new Gson();
|
47 |
-
|
48 |
-
@Override
|
49 |
-
protected void doPost(
|
50 |
-
HttpServletRequest request, HttpServletResponse response)
|
51 |
-
throws ServletException, IOException
|
52 |
-
{
|
53 |
-
doGet(request, response);
|
54 |
-
}
|
55 |
-
|
56 |
-
@Override
|
57 |
-
protected void doGet(
|
58 |
-
HttpServletRequest request, HttpServletResponse response)
|
59 |
-
throws ServletException, IOException
|
60 |
-
{
|
61 |
-
// 设置request的编码
|
62 |
-
request.setCharacterEncoding("UTF-8");
|
63 |
-
|
64 |
-
// 获取需要调用的方法名
|
65 |
-
String methodName = request.getParameter("method");
|
66 |
-
String resp = "";
|
67 |
-
|
68 |
-
if ("queryClusterAndHost".equals(methodName))
|
69 |
-
{
|
70 |
-
// 查询VDC
|
71 |
-
resp = queryPortGroups(request);
|
72 |
-
}
|
73 |
-
|
74 |
-
// 设置response的编码
|
75 |
-
response.setContentType("application/json;charset=UTF-8");
|
76 |
-
// 输出流
|
77 |
-
PrintWriter pw = response.getWriter();
|
78 |
-
// 将结果放到浏览器中
|
79 |
-
|
80 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
81 |
-
// pw.print(resp);
|
82 |
-
// FIXED:
|
83 |
-
|
84 |
-
// 关闭输出流
|
85 |
-
pw.close();
|
86 |
-
}
|
87 |
-
|
88 |
-
/**
|
89 |
-
* 查VDC信息
|
90 |
-
*
|
91 |
-
* @param request
|
92 |
-
* HttpServletRequest对象
|
93 |
-
* @return json格式的字符串
|
94 |
-
* @see
|
95 |
-
* @since eSDK Cloud V100R003C50
|
96 |
-
*/
|
97 |
-
public String queryPortGroups(HttpServletRequest request)
|
98 |
-
{
|
99 |
-
// 定义返回结果
|
100 |
-
String response = null;
|
101 |
-
|
102 |
-
// 获取用户名
|
103 |
-
String userName = ParametersUtils.userName;
|
104 |
-
|
105 |
-
// 获取密码
|
106 |
-
String password = ParametersUtils.password;
|
107 |
-
|
108 |
-
// 调用鉴权接口
|
109 |
-
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
|
110 |
-
|
111 |
-
if (!"00000000".equals(loginResp.getErrorCode()))
|
112 |
-
{
|
113 |
-
// 鉴权失败
|
114 |
-
LOGGER.error("Failed to Login FC System!");
|
115 |
-
return gson.toJson(loginResp);
|
116 |
-
}
|
117 |
-
|
118 |
-
LOGGER.info("Login Success!");
|
119 |
-
|
120 |
-
LOGGER.info("Begin to query PortGroups information.");
|
121 |
-
|
122 |
-
// 获取站点Uri
|
123 |
-
String siteUri = request.getParameter("siteUri");
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
// 此次查询返回数量最大值
|
128 |
-
Integer limit = 50;
|
129 |
-
|
130 |
-
// 偏移量
|
131 |
-
Integer offset = 0;
|
132 |
-
|
133 |
-
// 查询主机列表请求消息
|
134 |
-
QueryHostListReq req = new QueryHostListReq();
|
135 |
-
req.setLimit(limit);
|
136 |
-
req.setOffset(offset);
|
137 |
-
|
138 |
-
// 调用“查询主机列表”接口
|
139 |
-
FCSDKResponse<PageList<HostBasicInfo>> hostResp = ServiceManageFactory.getHostResource().queryHostList(siteUri, req);
|
140 |
-
|
141 |
-
// 集群标签
|
142 |
-
String tag = null;
|
143 |
-
// 集群名称
|
144 |
-
String name = null;
|
145 |
-
|
146 |
-
// 调用查询集群列表接口
|
147 |
-
FCSDKResponse<List<ClusterBasicInfo>> clusResp = ServiceManageFactory.getClusterResource().queryClusters(siteUri, tag, name, null, null);
|
148 |
-
|
149 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
150 |
-
response = gson.toJson(hostResp) + "||" + gson.toJson(clusResp);
|
151 |
-
|
152 |
-
LOGGER.info("Finish to query PortGroups, response is : " + response);
|
153 |
-
|
154 |
-
return response;
|
155 |
-
}
|
156 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10011.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.PageList;import com.huawei.esdk.fusioncompute.local.model.cluster.ClusterBasicInfo;import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;import com.huawei.esdk.fusioncompute.local.model.host.HostBasicInfo;import com.huawei.esdk.fusioncompute.local.model.host.QueryHostListReq;/** * “查询VDC”请求处理类 * @author dWX213051 * @see * @since eSDK Cloud V100R003C30 */public class QueryClusterAndHostServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 190954570327110271L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(QueryClusterAndHostServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("queryClusterAndHost".equals(methodName)) { // 查询VDC resp = queryPortGroups(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 查VDC信息 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String queryPortGroups(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to query PortGroups information."); // 获取站点Uri String siteUri = request.getParameter("siteUri"); // 此次查询返回数量最大值 Integer limit = 50; // 偏移量 Integer offset = 0; // 查询主机列表请求消息 QueryHostListReq req = new QueryHostListReq(); req.setLimit(limit); req.setOffset(offset); // 调用“查询主机列表”接口 FCSDKResponse<PageList<HostBasicInfo>> hostResp = ServiceManageFactory.getHostResource().queryHostList(siteUri, req); // 集群标签 String tag = null; // 集群名称 String name = null; // 调用查询集群列表接口 FCSDKResponse<List<ClusterBasicInfo>> clusResp = ServiceManageFactory.getClusterResource().queryClusters(siteUri, tag, name, null, null); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(hostResp) + "||" + gson.toJson(clusResp); LOGGER.info("Finish to query PortGroups, response is : " + response); return response; }}
|
data/java/10012.java
DELETED
@@ -1,133 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.servlet;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
import java.util.List;
|
6 |
-
|
7 |
-
import javax.servlet.ServletException;
|
8 |
-
import javax.servlet.http.HttpServlet;
|
9 |
-
import javax.servlet.http.HttpServletRequest;
|
10 |
-
import javax.servlet.http.HttpServletResponse;
|
11 |
-
|
12 |
-
import org.apache.log4j.Logger;
|
13 |
-
|
14 |
-
import com.google.gson.Gson;
|
15 |
-
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
|
16 |
-
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
18 |
-
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
|
19 |
-
import com.huawei.esdk.fusioncompute.local.model.net.DvSwitchBasicInfo;
|
20 |
-
|
21 |
-
/**
|
22 |
-
* “查询DVSwitchUri”请求处理类
|
23 |
-
* @author
|
24 |
-
* @see
|
25 |
-
* @since eSDK Cloud V100R003C30
|
26 |
-
*/
|
27 |
-
public class QueryDVSwitchUriServlet extends HttpServlet
|
28 |
-
{
|
29 |
-
/**
|
30 |
-
* 序列化版本标识
|
31 |
-
*/
|
32 |
-
private static final long serialVersionUID = 190954570327110273L;
|
33 |
-
|
34 |
-
/**
|
35 |
-
* log日志对象
|
36 |
-
*/
|
37 |
-
private static final Logger LOGGER = Logger
|
38 |
-
.getLogger(QueryDVSwitchUriServlet.class);
|
39 |
-
|
40 |
-
/**
|
41 |
-
* gson,用于转换String和json之间的转换
|
42 |
-
*/
|
43 |
-
private Gson gson = new Gson();
|
44 |
-
|
45 |
-
@Override
|
46 |
-
protected void doPost(
|
47 |
-
HttpServletRequest request, HttpServletResponse response)
|
48 |
-
throws ServletException, IOException
|
49 |
-
{
|
50 |
-
doGet(request, response);
|
51 |
-
}
|
52 |
-
|
53 |
-
@Override
|
54 |
-
protected void doGet(
|
55 |
-
HttpServletRequest request, HttpServletResponse response)
|
56 |
-
throws ServletException, IOException
|
57 |
-
{
|
58 |
-
// 设置request的编码
|
59 |
-
request.setCharacterEncoding("UTF-8");
|
60 |
-
|
61 |
-
// 获取需要调用的方法名
|
62 |
-
String methodName = request.getParameter("method");
|
63 |
-
String resp = "";
|
64 |
-
|
65 |
-
if ("queryDVSwitchUri".equals(methodName))
|
66 |
-
{
|
67 |
-
// 查询VDC
|
68 |
-
resp = queryDVSwitchUri(request);
|
69 |
-
}
|
70 |
-
|
71 |
-
// 设置response的编码
|
72 |
-
response.setContentType("application/json;charset=UTF-8");
|
73 |
-
// 输出流
|
74 |
-
PrintWriter pw = response.getWriter();
|
75 |
-
// 将结果放到浏览器中
|
76 |
-
|
77 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
78 |
-
// pw.print(resp);
|
79 |
-
// FIXED:
|
80 |
-
|
81 |
-
// 关闭输出流
|
82 |
-
pw.close();
|
83 |
-
}
|
84 |
-
|
85 |
-
/**
|
86 |
-
* 查VDC信息
|
87 |
-
*
|
88 |
-
* @param request
|
89 |
-
* HttpServletRequest对象
|
90 |
-
* @return json格式的字符串
|
91 |
-
* @see
|
92 |
-
* @since eSDK Cloud V100R003C50
|
93 |
-
*/
|
94 |
-
public String queryDVSwitchUri(HttpServletRequest request)
|
95 |
-
{
|
96 |
-
// 定义返回结果
|
97 |
-
String response = null;
|
98 |
-
|
99 |
-
// 获取用户名
|
100 |
-
String userName = ParametersUtils.userName;
|
101 |
-
|
102 |
-
// 获取密码
|
103 |
-
String password = ParametersUtils.password;
|
104 |
-
|
105 |
-
// 调用鉴权接口
|
106 |
-
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
|
107 |
-
|
108 |
-
if (!"00000000".equals(loginResp.getErrorCode()))
|
109 |
-
{
|
110 |
-
// 鉴权失败
|
111 |
-
LOGGER.error("Failed to Login FC System!");
|
112 |
-
return gson.toJson(loginResp);
|
113 |
-
}
|
114 |
-
|
115 |
-
LOGGER.info("Login Success!");
|
116 |
-
|
117 |
-
LOGGER.info("Begin to query DVSwitchUri information.");
|
118 |
-
|
119 |
-
// 获取站点Uri
|
120 |
-
String siteUri = request.getParameter("siteUri");
|
121 |
-
|
122 |
-
// 调用“查询站点下所有DVSwitch信息”接口
|
123 |
-
FCSDKResponse<List<DvSwitchBasicInfo>> resp = ServiceManageFactory.getDVSwitchResource().queryDVSwitchs(siteUri, null, null);
|
124 |
-
|
125 |
-
|
126 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
127 |
-
response = gson.toJson(resp);
|
128 |
-
|
129 |
-
LOGGER.info("Finish to query DVSwitchUri, response is : " + response);
|
130 |
-
|
131 |
-
return response;
|
132 |
-
}
|
133 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10012.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;import com.huawei.esdk.fusioncompute.local.model.net.DvSwitchBasicInfo;/** * “查询DVSwitchUri”请求处理类 * @author * @see * @since eSDK Cloud V100R003C30 */public class QueryDVSwitchUriServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 190954570327110273L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(QueryDVSwitchUriServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("queryDVSwitchUri".equals(methodName)) { // 查询VDC resp = queryDVSwitchUri(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 查VDC信息 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String queryDVSwitchUri(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to query DVSwitchUri information."); // 获取站点Uri String siteUri = request.getParameter("siteUri"); // 调用“查询站点下所有DVSwitch信息”接口 FCSDKResponse<List<DvSwitchBasicInfo>> resp = ServiceManageFactory.getDVSwitchResource().queryDVSwitchs(siteUri, null, null); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); LOGGER.info("Finish to query DVSwitchUri, response is : " + response); return response; }}
|
data/java/10013.java
DELETED
@@ -1,154 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.servlet;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
|
6 |
-
import javax.servlet.ServletException;
|
7 |
-
import javax.servlet.http.HttpServlet;
|
8 |
-
import javax.servlet.http.HttpServletRequest;
|
9 |
-
import javax.servlet.http.HttpServletResponse;
|
10 |
-
import javax.servlet.http.HttpSession;
|
11 |
-
|
12 |
-
import org.apache.log4j.Logger;
|
13 |
-
|
14 |
-
import com.google.gson.Gson;
|
15 |
-
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
|
16 |
-
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
18 |
-
import com.huawei.esdk.fusioncompute.local.model.PageList;
|
19 |
-
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
|
20 |
-
import com.huawei.esdk.fusioncompute.local.model.storage.Datastore;
|
21 |
-
import com.huawei.esdk.fusioncompute.local.model.storage.DatastoreQueryParams;
|
22 |
-
|
23 |
-
/**
|
24 |
-
* “查询DataStores”请求处理类
|
25 |
-
* @author
|
26 |
-
* @see
|
27 |
-
* @since eSDK Cloud V100R003C30
|
28 |
-
*/
|
29 |
-
public class QueryDataStoresServlet extends HttpServlet
|
30 |
-
{
|
31 |
-
/**
|
32 |
-
* 序列化版本标识
|
33 |
-
*/
|
34 |
-
private static final long serialVersionUID = 190954570327110271L;
|
35 |
-
|
36 |
-
/**
|
37 |
-
* log日志对象
|
38 |
-
*/
|
39 |
-
private static final Logger LOGGER = Logger
|
40 |
-
.getLogger(QueryDataStoresServlet.class);
|
41 |
-
|
42 |
-
/**
|
43 |
-
* gson,用于转换String和json之间的转换
|
44 |
-
*/
|
45 |
-
private Gson gson = new Gson();
|
46 |
-
|
47 |
-
@Override
|
48 |
-
protected void doPost(
|
49 |
-
HttpServletRequest request, HttpServletResponse response)
|
50 |
-
throws ServletException, IOException
|
51 |
-
{
|
52 |
-
doGet(request, response);
|
53 |
-
}
|
54 |
-
|
55 |
-
@Override
|
56 |
-
protected void doGet(
|
57 |
-
HttpServletRequest request, HttpServletResponse response)
|
58 |
-
throws ServletException, IOException
|
59 |
-
{
|
60 |
-
// 设置request的编码
|
61 |
-
request.setCharacterEncoding("UTF-8");
|
62 |
-
|
63 |
-
// 获取需要调用的方法名
|
64 |
-
String methodName = request.getParameter("method");
|
65 |
-
String resp = "";
|
66 |
-
|
67 |
-
if ("queryDataStores".equals(methodName))
|
68 |
-
{
|
69 |
-
// 查询VDC
|
70 |
-
resp = queryDataStores(request);
|
71 |
-
}
|
72 |
-
|
73 |
-
// 设置response的编码
|
74 |
-
response.setContentType("application/json;charset=UTF-8");
|
75 |
-
// 输出流
|
76 |
-
PrintWriter pw = response.getWriter();
|
77 |
-
|
78 |
-
// 将结果放到浏览器中
|
79 |
-
|
80 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
81 |
-
// pw.print(resp);
|
82 |
-
// FIXED:
|
83 |
-
|
84 |
-
// 关闭输出流
|
85 |
-
pw.close();
|
86 |
-
}
|
87 |
-
|
88 |
-
/**
|
89 |
-
* 查DataStores信息
|
90 |
-
*
|
91 |
-
* @param request
|
92 |
-
* HttpServletRequest对象
|
93 |
-
* @return json格式的字符串
|
94 |
-
* @see
|
95 |
-
* @since eSDK Cloud V100R003C50
|
96 |
-
*/
|
97 |
-
public String queryDataStores(HttpServletRequest request)
|
98 |
-
{
|
99 |
-
// 定义返回结果
|
100 |
-
String response = null;
|
101 |
-
|
102 |
-
// 获取用户名
|
103 |
-
String userName = ParametersUtils.userName;
|
104 |
-
// 获取密码
|
105 |
-
String password = ParametersUtils.password;
|
106 |
-
|
107 |
-
// 调用鉴权接口
|
108 |
-
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
|
109 |
-
|
110 |
-
if (!"00000000".equals(loginResp.getErrorCode()))
|
111 |
-
{
|
112 |
-
// 鉴权失败
|
113 |
-
LOGGER.error("Failed to Login FC System!");
|
114 |
-
return gson.toJson(loginResp);
|
115 |
-
}
|
116 |
-
|
117 |
-
LOGGER.info("Login Success!");
|
118 |
-
|
119 |
-
LOGGER.info("Begin to query DataStores information.");
|
120 |
-
|
121 |
-
// 获取数据存储名称
|
122 |
-
String name = request.getParameter("name");
|
123 |
-
|
124 |
-
// 获取此次查询返回数量值
|
125 |
-
String limit = request.getParameter("limit");
|
126 |
-
|
127 |
-
// 获取偏移量
|
128 |
-
String offset = request.getParameter("offset");
|
129 |
-
|
130 |
-
String siteUri = request.getParameter("siteUri");
|
131 |
-
|
132 |
-
// 数据存储查询消息
|
133 |
-
DatastoreQueryParams param = new DatastoreQueryParams();
|
134 |
-
param.setName(name==""?null:name);
|
135 |
-
param.setLimit(limit==""?null:Integer.valueOf(limit));
|
136 |
-
param.setOffset(offset==""?null:Integer.valueOf(offset));
|
137 |
-
|
138 |
-
// 调用“分页查询站点/主机/集群下所有数据存储”接口
|
139 |
-
FCSDKResponse<PageList<Datastore>> resp = ServiceManageFactory.getDataStorageResource().queryDataStores(siteUri, param);
|
140 |
-
|
141 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
142 |
-
response = gson.toJson(resp);
|
143 |
-
|
144 |
-
// 获取Session对象
|
145 |
-
HttpSession session = request.getSession();
|
146 |
-
|
147 |
-
// 将Resp放到Session中
|
148 |
-
session.setAttribute("DATASTORESRESOURCE_RES", resp);
|
149 |
-
|
150 |
-
LOGGER.info("Finish to query DataStores, response is : " + response);
|
151 |
-
|
152 |
-
return response;
|
153 |
-
}
|
154 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10013.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.PageList;import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;import com.huawei.esdk.fusioncompute.local.model.storage.Datastore;import com.huawei.esdk.fusioncompute.local.model.storage.DatastoreQueryParams;/** * “查询DataStores”请求处理类 * @author * @see * @since eSDK Cloud V100R003C30 */public class QueryDataStoresServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 190954570327110271L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(QueryDataStoresServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("queryDataStores".equals(methodName)) { // 查询VDC resp = queryDataStores(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 查DataStores信息 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String queryDataStores(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to query DataStores information."); // 获取数据存储名称 String name = request.getParameter("name"); // 获取此次查询返回数量值 String limit = request.getParameter("limit"); // 获取偏移量 String offset = request.getParameter("offset"); String siteUri = request.getParameter("siteUri"); // 数据存储查询消息 DatastoreQueryParams param = new DatastoreQueryParams(); param.setName(name==""?null:name); param.setLimit(limit==""?null:Integer.valueOf(limit)); param.setOffset(offset==""?null:Integer.valueOf(offset)); // 调用“分页查询站点/主机/集群下所有数据存储”接口 FCSDKResponse<PageList<Datastore>> resp = ServiceManageFactory.getDataStorageResource().queryDataStores(siteUri, param); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); // 获取Session对象 HttpSession session = request.getSession(); // 将Resp放到Session中 session.setAttribute("DATASTORESRESOURCE_RES", resp); LOGGER.info("Finish to query DataStores, response is : " + response); return response; }}
|
data/java/10014.java
DELETED
@@ -1,131 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.servlet;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
|
6 |
-
import javax.servlet.ServletException;
|
7 |
-
import javax.servlet.http.HttpServlet;
|
8 |
-
import javax.servlet.http.HttpServletRequest;
|
9 |
-
import javax.servlet.http.HttpServletResponse;
|
10 |
-
|
11 |
-
import org.apache.log4j.Logger;
|
12 |
-
|
13 |
-
import com.google.gson.Gson;
|
14 |
-
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
|
15 |
-
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
|
16 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
|
18 |
-
import com.huawei.esdk.fusioncompute.local.model.vm.QueryOsVersionsResp;
|
19 |
-
|
20 |
-
/**
|
21 |
-
* “查询VDC”请求处理类
|
22 |
-
* @author dWX213051
|
23 |
-
* @see
|
24 |
-
* @since eSDK Cloud V100R003C30
|
25 |
-
*/
|
26 |
-
public class QueryOsVersionsServlet extends HttpServlet
|
27 |
-
{
|
28 |
-
/**
|
29 |
-
* 序列化版本标识
|
30 |
-
*/
|
31 |
-
private static final long serialVersionUID = 190954570327110271L;
|
32 |
-
|
33 |
-
/**
|
34 |
-
* log日志对象
|
35 |
-
*/
|
36 |
-
private static final Logger LOGGER = Logger
|
37 |
-
.getLogger(QueryOsVersionsServlet.class);
|
38 |
-
|
39 |
-
/**
|
40 |
-
* gson,用于转换String和json之间的转换
|
41 |
-
*/
|
42 |
-
private Gson gson = new Gson();
|
43 |
-
|
44 |
-
@Override
|
45 |
-
protected void doPost(
|
46 |
-
HttpServletRequest request, HttpServletResponse response)
|
47 |
-
throws ServletException, IOException
|
48 |
-
{
|
49 |
-
doGet(request, response);
|
50 |
-
}
|
51 |
-
|
52 |
-
@Override
|
53 |
-
protected void doGet(
|
54 |
-
HttpServletRequest request, HttpServletResponse response)
|
55 |
-
throws ServletException, IOException
|
56 |
-
{
|
57 |
-
// 设置request的编码
|
58 |
-
request.setCharacterEncoding("UTF-8");
|
59 |
-
|
60 |
-
// 获取需要调用的方法名
|
61 |
-
String methodName = request.getParameter("method");
|
62 |
-
String resp = "";
|
63 |
-
|
64 |
-
if ("queryOsVersions".equals(methodName))
|
65 |
-
{
|
66 |
-
// 查询VDC
|
67 |
-
resp = queryOsVersions(request);
|
68 |
-
}
|
69 |
-
|
70 |
-
// 设置response的编码
|
71 |
-
response.setContentType("application/json;charset=UTF-8");
|
72 |
-
// 输出流
|
73 |
-
PrintWriter pw = response.getWriter();
|
74 |
-
// 将结果放到浏览器中
|
75 |
-
|
76 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
77 |
-
// pw.print(resp);
|
78 |
-
// FIXED:
|
79 |
-
|
80 |
-
// 关闭输出流
|
81 |
-
pw.close();
|
82 |
-
}
|
83 |
-
|
84 |
-
/**
|
85 |
-
* 查VDC信息
|
86 |
-
*
|
87 |
-
* @param request
|
88 |
-
* HttpServletRequest对象
|
89 |
-
* @return json格式的字符串
|
90 |
-
* @see
|
91 |
-
* @since eSDK Cloud V100R003C50
|
92 |
-
*/
|
93 |
-
public String queryOsVersions(HttpServletRequest request)
|
94 |
-
{
|
95 |
-
// 定义返回结果
|
96 |
-
String response = null;
|
97 |
-
|
98 |
-
// 获取用户名
|
99 |
-
String userName = ParametersUtils.userName;
|
100 |
-
// 获取密码
|
101 |
-
String password = ParametersUtils.password;
|
102 |
-
|
103 |
-
// 调用鉴权接口
|
104 |
-
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
|
105 |
-
|
106 |
-
if (!"00000000".equals(loginResp.getErrorCode()))
|
107 |
-
{
|
108 |
-
// 鉴权失败
|
109 |
-
LOGGER.error("Failed to Login FC System!");
|
110 |
-
return gson.toJson(loginResp);
|
111 |
-
}
|
112 |
-
|
113 |
-
LOGGER.info("Login Success!");
|
114 |
-
|
115 |
-
LOGGER.info("Begin to query OsVersions information.");
|
116 |
-
|
117 |
-
// 获取站点Uri
|
118 |
-
String siteUri = request.getParameter("siteUri");
|
119 |
-
|
120 |
-
// 调用“查询指定站点支持创建虚拟机操作系统的版本”接口
|
121 |
-
FCSDKResponse<QueryOsVersionsResp> resp = ServiceManageFactory.getVmResource().queryOsVersions(siteUri);
|
122 |
-
|
123 |
-
|
124 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
125 |
-
response = gson.toJson(resp);
|
126 |
-
|
127 |
-
LOGGER.info("Finish to query OsVersions, response is : " + response);
|
128 |
-
|
129 |
-
return response;
|
130 |
-
}
|
131 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10014.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;import com.huawei.esdk.fusioncompute.local.model.vm.QueryOsVersionsResp;/** * “查询VDC”请求处理类 * @author dWX213051 * @see * @since eSDK Cloud V100R003C30 */public class QueryOsVersionsServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 190954570327110271L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(QueryOsVersionsServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("queryOsVersions".equals(methodName)) { // 查询VDC resp = queryOsVersions(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 查VDC信息 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String queryOsVersions(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to query OsVersions information."); // 获取站点Uri String siteUri = request.getParameter("siteUri"); // 调用“查询指定站点支持创建虚拟机操作系统的版本”接口 FCSDKResponse<QueryOsVersionsResp> resp = ServiceManageFactory.getVmResource().queryOsVersions(siteUri); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); LOGGER.info("Finish to query OsVersions, response is : " + response); return response; }}
|
data/java/10015.java
DELETED
@@ -1,147 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.servlet;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
|
6 |
-
import javax.servlet.ServletException;
|
7 |
-
import javax.servlet.http.HttpServlet;
|
8 |
-
import javax.servlet.http.HttpServletRequest;
|
9 |
-
import javax.servlet.http.HttpServletResponse;
|
10 |
-
import javax.servlet.http.HttpSession;
|
11 |
-
|
12 |
-
import org.apache.log4j.Logger;
|
13 |
-
|
14 |
-
import com.google.gson.Gson;
|
15 |
-
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
|
16 |
-
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
18 |
-
import com.huawei.esdk.fusioncompute.local.model.PageList;
|
19 |
-
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
|
20 |
-
import com.huawei.esdk.fusioncompute.local.model.net.PortGroup;
|
21 |
-
|
22 |
-
/**
|
23 |
-
* “查询PortGroups”请求处理类
|
24 |
-
* @author
|
25 |
-
* @see
|
26 |
-
* @since eSDK Cloud V100R003C30
|
27 |
-
*/
|
28 |
-
public class QueryPortGroupsServlet extends HttpServlet
|
29 |
-
{
|
30 |
-
/**
|
31 |
-
* 序列化版本标识
|
32 |
-
*/
|
33 |
-
private static final long serialVersionUID = 190954570327110271L;
|
34 |
-
|
35 |
-
/**
|
36 |
-
* log日志对象
|
37 |
-
*/
|
38 |
-
private static final Logger LOGGER = Logger
|
39 |
-
.getLogger(QueryPortGroupsServlet.class);
|
40 |
-
|
41 |
-
/**
|
42 |
-
* gson,用于转换String和json之间的转换
|
43 |
-
*/
|
44 |
-
private Gson gson = new Gson();
|
45 |
-
|
46 |
-
@Override
|
47 |
-
protected void doPost(
|
48 |
-
HttpServletRequest request, HttpServletResponse response)
|
49 |
-
throws ServletException, IOException
|
50 |
-
{
|
51 |
-
doGet(request, response);
|
52 |
-
}
|
53 |
-
|
54 |
-
@Override
|
55 |
-
protected void doGet(
|
56 |
-
HttpServletRequest request, HttpServletResponse response)
|
57 |
-
throws ServletException, IOException
|
58 |
-
{
|
59 |
-
// 设置request的编码
|
60 |
-
request.setCharacterEncoding("UTF-8");
|
61 |
-
|
62 |
-
// 获取需要调用的方法名
|
63 |
-
String methodName = request.getParameter("method");
|
64 |
-
String resp = "";
|
65 |
-
|
66 |
-
if ("queryPortGroups".equals(methodName))
|
67 |
-
{
|
68 |
-
// 查询PortGroups
|
69 |
-
resp = queryPortGroups(request);
|
70 |
-
}
|
71 |
-
|
72 |
-
// 设置response的编码
|
73 |
-
response.setContentType("application/json;charset=UTF-8");
|
74 |
-
// 输出流
|
75 |
-
PrintWriter pw = response.getWriter();
|
76 |
-
// 将结果放到浏览器中
|
77 |
-
|
78 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
79 |
-
// pw.print(resp);
|
80 |
-
// FIXED:
|
81 |
-
|
82 |
-
// 关闭输出流
|
83 |
-
pw.close();
|
84 |
-
}
|
85 |
-
|
86 |
-
/**
|
87 |
-
* 查询PortGroups信息
|
88 |
-
*
|
89 |
-
* @param request
|
90 |
-
* HttpServletRequest对象
|
91 |
-
* @return json格式的字符串
|
92 |
-
* @see
|
93 |
-
* @since eSDK Cloud V100R003C50
|
94 |
-
*/
|
95 |
-
public String queryPortGroups(HttpServletRequest request)
|
96 |
-
{
|
97 |
-
// 定义返回结果
|
98 |
-
String response = null;
|
99 |
-
|
100 |
-
// 获取用户名
|
101 |
-
String userName = ParametersUtils.userName;
|
102 |
-
// 获取密码
|
103 |
-
String password = ParametersUtils.password;
|
104 |
-
|
105 |
-
// 调用鉴权接口
|
106 |
-
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
|
107 |
-
|
108 |
-
if (!"00000000".equals(loginResp.getErrorCode()))
|
109 |
-
{
|
110 |
-
// 鉴权失败
|
111 |
-
LOGGER.error("Failed to Login FC System!");
|
112 |
-
return gson.toJson(loginResp);
|
113 |
-
}
|
114 |
-
|
115 |
-
LOGGER.info("Login Success!");
|
116 |
-
|
117 |
-
LOGGER.info("Begin to query PortGroups information.");
|
118 |
-
|
119 |
-
// 获取端口组名称
|
120 |
-
String name = request.getParameter("name");
|
121 |
-
// 获取单页查询量
|
122 |
-
String limit = request.getParameter("limit");
|
123 |
-
// 获取偏移量
|
124 |
-
String offset = request.getParameter("start");
|
125 |
-
// 获取模糊查询偏移量
|
126 |
-
String vlan = request.getParameter("vlan");
|
127 |
-
// 获取模糊查询偏移量
|
128 |
-
String vxlan = request.getParameter("vxlan");
|
129 |
-
// 获取DVSwithUri
|
130 |
-
String dvswitchUri = request.getParameter("dVSwithUri");
|
131 |
-
|
132 |
-
// 调用“查询指定DVSwitch下所有的端口组”接口
|
133 |
-
FCSDKResponse<PageList<PortGroup>> resp = ServiceManageFactory.getPortGroupResource().queryPortGroups(dvswitchUri, offset==""?null:Integer.valueOf(offset), limit==""?null:Integer.valueOf(limit), name==""?null:name, vlan==""?null:vlan, vxlan==""?null:vxlan);
|
134 |
-
|
135 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
136 |
-
response = gson.toJson(resp);
|
137 |
-
|
138 |
-
// 获取Session对象
|
139 |
-
HttpSession session = request.getSession();
|
140 |
-
// 将resp放到Session中
|
141 |
-
session.setAttribute("PORTGROUPSRESOURCE_RES", resp);
|
142 |
-
|
143 |
-
LOGGER.info("Finish to query PortGroups, response is : " + response);
|
144 |
-
|
145 |
-
return response;
|
146 |
-
}
|
147 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10015.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.PageList;import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;import com.huawei.esdk.fusioncompute.local.model.net.PortGroup;/** * “查询PortGroups”请求处理类 * @author * @see * @since eSDK Cloud V100R003C30 */public class QueryPortGroupsServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 190954570327110271L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(QueryPortGroupsServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("queryPortGroups".equals(methodName)) { // 查询PortGroups resp = queryPortGroups(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 查询PortGroups信息 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String queryPortGroups(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to query PortGroups information."); // 获取端口组名称 String name = request.getParameter("name"); // 获取单页查询量 String limit = request.getParameter("limit"); // 获取偏移量 String offset = request.getParameter("start"); // 获取模糊查询偏移量 String vlan = request.getParameter("vlan"); // 获取模糊查询偏移量 String vxlan = request.getParameter("vxlan"); // 获取DVSwithUri String dvswitchUri = request.getParameter("dVSwithUri"); // 调用“查询指定DVSwitch下所有的端口组”接口 FCSDKResponse<PageList<PortGroup>> resp = ServiceManageFactory.getPortGroupResource().queryPortGroups(dvswitchUri, offset==""?null:Integer.valueOf(offset), limit==""?null:Integer.valueOf(limit), name==""?null:name, vlan==""?null:vlan, vxlan==""?null:vxlan); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); // 获取Session对象 HttpSession session = request.getSession(); // 将resp放到Session中 session.setAttribute("PORTGROUPSRESOURCE_RES", resp); LOGGER.info("Finish to query PortGroups, response is : " + response); return response; }}
|
data/java/10016.java
DELETED
@@ -1,129 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.servlet;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
import java.util.List;
|
6 |
-
|
7 |
-
import javax.servlet.ServletException;
|
8 |
-
import javax.servlet.http.HttpServlet;
|
9 |
-
import javax.servlet.http.HttpServletRequest;
|
10 |
-
import javax.servlet.http.HttpServletResponse;
|
11 |
-
|
12 |
-
import org.apache.log4j.Logger;
|
13 |
-
|
14 |
-
import com.google.gson.Gson;
|
15 |
-
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
|
16 |
-
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
18 |
-
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
|
19 |
-
import com.huawei.esdk.fusioncompute.local.model.site.SiteBasicInfo;
|
20 |
-
|
21 |
-
/**
|
22 |
-
* “查询SiteUri”请求处理类
|
23 |
-
* @author
|
24 |
-
* @see
|
25 |
-
* @since eSDK Cloud V100R003C30
|
26 |
-
*/
|
27 |
-
public class QuerySiteUriServlet extends HttpServlet
|
28 |
-
{
|
29 |
-
/**
|
30 |
-
* 序列化版本标识
|
31 |
-
*/
|
32 |
-
private static final long serialVersionUID = 190954570327110272L;
|
33 |
-
|
34 |
-
/**
|
35 |
-
* log日志对象
|
36 |
-
*/
|
37 |
-
private static final Logger LOGGER = Logger
|
38 |
-
.getLogger(QuerySiteUriServlet.class);
|
39 |
-
|
40 |
-
/**
|
41 |
-
* gson,用于转换String和json之间的转换
|
42 |
-
*/
|
43 |
-
private Gson gson = new Gson();
|
44 |
-
|
45 |
-
@Override
|
46 |
-
protected void doPost(
|
47 |
-
HttpServletRequest request, HttpServletResponse response)
|
48 |
-
throws ServletException, IOException
|
49 |
-
{
|
50 |
-
doGet(request, response);
|
51 |
-
}
|
52 |
-
|
53 |
-
@Override
|
54 |
-
protected void doGet(
|
55 |
-
HttpServletRequest request, HttpServletResponse response)
|
56 |
-
throws ServletException, IOException
|
57 |
-
{
|
58 |
-
// 设置request的编码
|
59 |
-
request.setCharacterEncoding("UTF-8");
|
60 |
-
|
61 |
-
// 获取需要调用的方法名
|
62 |
-
String methodName = request.getParameter("method");
|
63 |
-
String resp = "";
|
64 |
-
|
65 |
-
if ("querySiteUri".equals(methodName))
|
66 |
-
{
|
67 |
-
// 查询VDC
|
68 |
-
resp = querySiteUri(request);
|
69 |
-
}
|
70 |
-
|
71 |
-
// 设置response的编码
|
72 |
-
response.setContentType("application/json;charset=UTF-8");
|
73 |
-
// 输出流
|
74 |
-
PrintWriter pw = response.getWriter();
|
75 |
-
// 将结果放到浏览器中
|
76 |
-
|
77 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
78 |
-
// pw.print(resp);
|
79 |
-
// FIXED:
|
80 |
-
|
81 |
-
// 关闭输出流
|
82 |
-
pw.close();
|
83 |
-
}
|
84 |
-
|
85 |
-
/**
|
86 |
-
* 查VDC信息
|
87 |
-
*
|
88 |
-
* @param request
|
89 |
-
* HttpServletRequest对象
|
90 |
-
* @return json格式的字符串
|
91 |
-
* @see
|
92 |
-
* @since eSDK Cloud V100R003C50
|
93 |
-
*/
|
94 |
-
public String querySiteUri(HttpServletRequest request)
|
95 |
-
{
|
96 |
-
// 定义返回结果
|
97 |
-
String response = null;
|
98 |
-
|
99 |
-
// 获取用户名
|
100 |
-
String userName = ParametersUtils.userName;
|
101 |
-
// 获取密码
|
102 |
-
String password = ParametersUtils.password;
|
103 |
-
|
104 |
-
// 调用鉴权接口
|
105 |
-
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
|
106 |
-
|
107 |
-
if (!"00000000".equals(loginResp.getErrorCode()))
|
108 |
-
{
|
109 |
-
// 鉴权失败
|
110 |
-
LOGGER.error("Failed to Login FC System!");
|
111 |
-
return gson.toJson(loginResp);
|
112 |
-
}
|
113 |
-
|
114 |
-
LOGGER.info("Login Success!");
|
115 |
-
|
116 |
-
LOGGER.info("Begin to query SiteUri information.");
|
117 |
-
|
118 |
-
// 调用“查询所有站点信息”接口
|
119 |
-
FCSDKResponse<List<SiteBasicInfo>> resp = ServiceManageFactory.getSiteResource().querySites();
|
120 |
-
|
121 |
-
|
122 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
123 |
-
response = gson.toJson(resp);
|
124 |
-
|
125 |
-
LOGGER.info("Finish to query SiteUri, response is : " + response);
|
126 |
-
|
127 |
-
return response;
|
128 |
-
}
|
129 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10016.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;import com.huawei.esdk.fusioncompute.local.model.site.SiteBasicInfo;/** * “查询SiteUri”请求处理类 * @author * @see * @since eSDK Cloud V100R003C30 */public class QuerySiteUriServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 190954570327110272L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(QuerySiteUriServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("querySiteUri".equals(methodName)) { // 查询VDC resp = querySiteUri(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 查VDC信息 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String querySiteUri(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to query SiteUri information."); // 调用“查询所有站点信息”接口 FCSDKResponse<List<SiteBasicInfo>> resp = ServiceManageFactory.getSiteResource().querySites(); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); LOGGER.info("Finish to query SiteUri, response is : " + response); return response; }}
|
data/java/10017.java
DELETED
@@ -1,138 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.servlet;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
|
6 |
-
import javax.servlet.ServletException;
|
7 |
-
import javax.servlet.http.HttpServlet;
|
8 |
-
import javax.servlet.http.HttpServletRequest;
|
9 |
-
import javax.servlet.http.HttpServletResponse;
|
10 |
-
|
11 |
-
import org.apache.log4j.Logger;
|
12 |
-
|
13 |
-
import com.google.gson.Gson;
|
14 |
-
import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;
|
15 |
-
import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;
|
16 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.VRMTask;
|
18 |
-
import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;
|
19 |
-
import com.huawei.esdk.fusioncompute.local.model.vm.CreatVmReq;
|
20 |
-
|
21 |
-
/**
|
22 |
-
* “创建虚拟机”请求处理类
|
23 |
-
* @author
|
24 |
-
* @see
|
25 |
-
* @since eSDK Cloud V100R003C30
|
26 |
-
*/
|
27 |
-
public class createVMServlet extends HttpServlet
|
28 |
-
{
|
29 |
-
/**
|
30 |
-
* 序列化版本标识
|
31 |
-
*/
|
32 |
-
private static final long serialVersionUID = 6749720431926648350L;
|
33 |
-
|
34 |
-
/**
|
35 |
-
* log日志对象
|
36 |
-
*/
|
37 |
-
private static final Logger LOGGER = Logger
|
38 |
-
.getLogger(createVMServlet.class);
|
39 |
-
|
40 |
-
/**
|
41 |
-
* gson,用于转换String和json之间的转换
|
42 |
-
*/
|
43 |
-
private Gson gson = new Gson();
|
44 |
-
|
45 |
-
@Override
|
46 |
-
protected void doPost(
|
47 |
-
HttpServletRequest request, HttpServletResponse response)
|
48 |
-
throws ServletException, IOException
|
49 |
-
{
|
50 |
-
doGet(request, response);
|
51 |
-
}
|
52 |
-
|
53 |
-
@Override
|
54 |
-
protected void doGet(
|
55 |
-
HttpServletRequest request, HttpServletResponse response)
|
56 |
-
throws ServletException, IOException
|
57 |
-
{
|
58 |
-
// 设置request的编码
|
59 |
-
request.setCharacterEncoding("UTF-8");
|
60 |
-
|
61 |
-
// 获取需要调用的方法名
|
62 |
-
String methodName = request.getParameter("method");
|
63 |
-
String resp = "";
|
64 |
-
|
65 |
-
if ("createVM".equals(methodName))
|
66 |
-
{
|
67 |
-
// 批量创建虚拟机
|
68 |
-
resp = createVM(request);
|
69 |
-
}
|
70 |
-
|
71 |
-
// 设置response的编码
|
72 |
-
response.setContentType("application/json;charset=UTF-8");
|
73 |
-
// 输出流
|
74 |
-
PrintWriter pw = response.getWriter();
|
75 |
-
// 将结果放到浏览器中
|
76 |
-
|
77 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
78 |
-
// pw.print(resp);
|
79 |
-
// FIXED:
|
80 |
-
|
81 |
-
// 关闭输出流
|
82 |
-
pw.close();
|
83 |
-
}
|
84 |
-
|
85 |
-
/**
|
86 |
-
* 创建虚拟机
|
87 |
-
*
|
88 |
-
* @param request HttpServletRequest对象
|
89 |
-
* @return json格式的字符串
|
90 |
-
* @see
|
91 |
-
* @since eSDK Cloud V100R003C50
|
92 |
-
*/
|
93 |
-
public String createVM(HttpServletRequest request)
|
94 |
-
{
|
95 |
-
// 定义返回结果
|
96 |
-
String response = null;
|
97 |
-
|
98 |
-
// 获取用户名
|
99 |
-
String userName = ParametersUtils.userName;
|
100 |
-
// 获取密码
|
101 |
-
String password = ParametersUtils.password;
|
102 |
-
|
103 |
-
// 调用鉴权接口
|
104 |
-
FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password);
|
105 |
-
|
106 |
-
if (!"00000000".equals(loginResp.getErrorCode()))
|
107 |
-
{
|
108 |
-
// 鉴权失败
|
109 |
-
LOGGER.error("Failed to Login FC System!");
|
110 |
-
return gson.toJson(loginResp);
|
111 |
-
}
|
112 |
-
|
113 |
-
LOGGER.info("Login Success!");
|
114 |
-
|
115 |
-
LOGGER.info("Begin to create VM." );
|
116 |
-
|
117 |
-
// 获取站点Uri
|
118 |
-
String siteUri = request.getParameter("siteUri");
|
119 |
-
|
120 |
-
// 获取创建虚拟机的请求参数
|
121 |
-
String jsonStr = request.getParameter("reqJson");
|
122 |
-
|
123 |
-
// 将jsonStr字符串转换成创建虚拟机请求参数的对象
|
124 |
-
CreatVmReq createVmReq = gson.fromJson(jsonStr, CreatVmReq.class);
|
125 |
-
|
126 |
-
// 调用创建虚拟机接口
|
127 |
-
FCSDKResponse<VRMTask> resp = ServiceManageFactory.getVmResource().createVM(siteUri, createVmReq);
|
128 |
-
|
129 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
130 |
-
response = gson.toJson(resp);
|
131 |
-
|
132 |
-
LOGGER.info("Finish to create VM, response is : " + response);
|
133 |
-
|
134 |
-
// 返回接口调用的响应值
|
135 |
-
return response;
|
136 |
-
}
|
137 |
-
|
138 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10017.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.demo.factory.ServiceManageFactory;import com.huawei.esdk.fusioncompute.demo.utils.ParametersUtils;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.VRMTask;import com.huawei.esdk.fusioncompute.local.model.common.LoginResp;import com.huawei.esdk.fusioncompute.local.model.vm.CreatVmReq;/** * “创建虚拟机”请求处理类 * @author * @see * @since eSDK Cloud V100R003C30 */public class createVMServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 6749720431926648350L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(createVMServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置request的编码 request.setCharacterEncoding("UTF-8"); // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("createVM".equals(methodName)) { // 批量创建虚拟机 resp = createVM(request); } // 设置response的编码 response.setContentType("application/json;charset=UTF-8"); // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 创建虚拟机 * * @param request HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C50 */ public String createVM(HttpServletRequest request) { // 定义返回结果 String response = null; // 获取用户名 String userName = ParametersUtils.userName; // 获取密码 String password = ParametersUtils.password; // 调用鉴权接口 FCSDKResponse<LoginResp> loginResp = ServiceManageFactory.getUserService().login(userName, password); if (!"00000000".equals(loginResp.getErrorCode())) { // 鉴权失败 LOGGER.error("Failed to Login FC System!"); return gson.toJson(loginResp); } LOGGER.info("Login Success!"); LOGGER.info("Begin to create VM." ); // 获取站点Uri String siteUri = request.getParameter("siteUri"); // 获取创建虚拟机的请求参数 String jsonStr = request.getParameter("reqJson"); // 将jsonStr字符串转换成创建虚拟机请求参数的对象 CreatVmReq createVmReq = gson.fromJson(jsonStr, CreatVmReq.class); // 调用创建虚拟机接口 FCSDKResponse<VRMTask> resp = ServiceManageFactory.getVmResource().createVM(siteUri, createVmReq); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); LOGGER.info("Finish to create VM, response is : " + response); // 返回接口调用的响应值 return response; } }
|
data/java/10018.java
DELETED
@@ -1,102 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.utils;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
|
6 |
-
import javax.servlet.ServletException;
|
7 |
-
import javax.servlet.http.HttpServlet;
|
8 |
-
import javax.servlet.http.HttpServletRequest;
|
9 |
-
import javax.servlet.http.HttpServletResponse;
|
10 |
-
import javax.servlet.http.HttpSession;
|
11 |
-
|
12 |
-
import org.apache.log4j.Logger;
|
13 |
-
|
14 |
-
import com.google.gson.Gson;
|
15 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
16 |
-
import com.huawei.esdk.fusioncompute.local.model.PageList;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.storage.Datastore;
|
18 |
-
|
19 |
-
public class GetDatastoreUrnServlet extends HttpServlet
|
20 |
-
{
|
21 |
-
|
22 |
-
/**
|
23 |
-
* 序列化版本标识
|
24 |
-
*/
|
25 |
-
private static final long serialVersionUID = 406215323069888871L;
|
26 |
-
|
27 |
-
/**
|
28 |
-
* log日志对象
|
29 |
-
*/
|
30 |
-
private static final Logger LOGGER = Logger
|
31 |
-
.getLogger(GetDatastoreUrnServlet.class);
|
32 |
-
|
33 |
-
|
34 |
-
/**
|
35 |
-
* gson,用于转换String和json之间的转换
|
36 |
-
*/
|
37 |
-
private Gson gson = new Gson();
|
38 |
-
|
39 |
-
@Override
|
40 |
-
protected void doPost(
|
41 |
-
HttpServletRequest request, HttpServletResponse response)
|
42 |
-
throws ServletException, IOException
|
43 |
-
{
|
44 |
-
doGet(request, response);
|
45 |
-
}
|
46 |
-
|
47 |
-
@Override
|
48 |
-
protected void doGet(
|
49 |
-
HttpServletRequest request, HttpServletResponse response)
|
50 |
-
throws ServletException, IOException
|
51 |
-
{
|
52 |
-
// 获取需要调用的方法名
|
53 |
-
String methodName = request.getParameter("method");
|
54 |
-
String resp = "";
|
55 |
-
|
56 |
-
if ("getDatastoreUrn".equals(methodName))
|
57 |
-
{
|
58 |
-
// 读取Demo所用参数
|
59 |
-
resp = getDatastoreUrn(request);
|
60 |
-
}
|
61 |
-
|
62 |
-
// 输出流
|
63 |
-
PrintWriter pw = response.getWriter();
|
64 |
-
// 将结果放到浏览器中
|
65 |
-
|
66 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
67 |
-
// pw.print(resp);
|
68 |
-
// FIXED:
|
69 |
-
|
70 |
-
// 关闭输出流
|
71 |
-
pw.close();
|
72 |
-
}
|
73 |
-
|
74 |
-
/**
|
75 |
-
* 读取Demo所用参数
|
76 |
-
*
|
77 |
-
* @param request
|
78 |
-
* HttpServletRequest对象
|
79 |
-
* @return json格式的字符串
|
80 |
-
* @see
|
81 |
-
* @since eSDK Cloud V100R003C20
|
82 |
-
*/
|
83 |
-
@SuppressWarnings("unchecked")
|
84 |
-
public String getDatastoreUrn(HttpServletRequest request)
|
85 |
-
{
|
86 |
-
// 定义返回结果
|
87 |
-
String response = null;
|
88 |
-
|
89 |
-
LOGGER.info("Begin to read parameters.");
|
90 |
-
|
91 |
-
// 获取Session对象
|
92 |
-
HttpSession session = request.getSession();
|
93 |
-
// 获取key为DATASTORESRESOURCE_RES的值
|
94 |
-
FCSDKResponse<PageList<Datastore>> resp = (FCSDKResponse<PageList<Datastore>>)session.getAttribute("DATASTORESRESOURCE_RES");
|
95 |
-
|
96 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
97 |
-
response = gson.toJson(resp);
|
98 |
-
LOGGER.info("Finish to read parameters, response is : " + response);
|
99 |
-
|
100 |
-
return response;
|
101 |
-
}
|
102 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10018.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.utils;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.PageList;import com.huawei.esdk.fusioncompute.local.model.storage.Datastore;public class GetDatastoreUrnServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 406215323069888871L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(GetDatastoreUrnServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("getDatastoreUrn".equals(methodName)) { // 读取Demo所用参数 resp = getDatastoreUrn(request); } // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 读取Demo所用参数 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C20 */ @SuppressWarnings("unchecked") public String getDatastoreUrn(HttpServletRequest request) { // 定义返回结果 String response = null; LOGGER.info("Begin to read parameters."); // 获取Session对象 HttpSession session = request.getSession(); // 获取key为DATASTORESRESOURCE_RES的值 FCSDKResponse<PageList<Datastore>> resp = (FCSDKResponse<PageList<Datastore>>)session.getAttribute("DATASTORESRESOURCE_RES"); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); LOGGER.info("Finish to read parameters, response is : " + response); return response; }}
|
data/java/10019.java
DELETED
@@ -1,102 +0,0 @@
|
|
1 |
-
package com.huawei.esdk.fusioncompute.demo.utils;
|
2 |
-
|
3 |
-
import java.io.IOException;
|
4 |
-
import java.io.PrintWriter;
|
5 |
-
|
6 |
-
import javax.servlet.ServletException;
|
7 |
-
import javax.servlet.http.HttpServlet;
|
8 |
-
import javax.servlet.http.HttpServletRequest;
|
9 |
-
import javax.servlet.http.HttpServletResponse;
|
10 |
-
import javax.servlet.http.HttpSession;
|
11 |
-
|
12 |
-
import org.apache.log4j.Logger;
|
13 |
-
|
14 |
-
import com.google.gson.Gson;
|
15 |
-
import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;
|
16 |
-
import com.huawei.esdk.fusioncompute.local.model.PageList;
|
17 |
-
import com.huawei.esdk.fusioncompute.local.model.net.PortGroup;
|
18 |
-
|
19 |
-
public class GetPortGroupsServlet extends HttpServlet
|
20 |
-
{
|
21 |
-
|
22 |
-
/**
|
23 |
-
* 序列化版本标识
|
24 |
-
*/
|
25 |
-
private static final long serialVersionUID = 406215323069888871L;
|
26 |
-
|
27 |
-
/**
|
28 |
-
* log日志对象
|
29 |
-
*/
|
30 |
-
private static final Logger LOGGER = Logger
|
31 |
-
.getLogger(GetPortGroupsServlet.class);
|
32 |
-
|
33 |
-
|
34 |
-
/**
|
35 |
-
* gson,用于转换String和json之间的转换
|
36 |
-
*/
|
37 |
-
private Gson gson = new Gson();
|
38 |
-
|
39 |
-
@Override
|
40 |
-
protected void doPost(
|
41 |
-
HttpServletRequest request, HttpServletResponse response)
|
42 |
-
throws ServletException, IOException
|
43 |
-
{
|
44 |
-
doGet(request, response);
|
45 |
-
}
|
46 |
-
|
47 |
-
@Override
|
48 |
-
protected void doGet(
|
49 |
-
HttpServletRequest request, HttpServletResponse response)
|
50 |
-
throws ServletException, IOException
|
51 |
-
{
|
52 |
-
// 获取需要调用的方法名
|
53 |
-
String methodName = request.getParameter("method");
|
54 |
-
String resp = "";
|
55 |
-
|
56 |
-
if ("getPortGroups".equals(methodName))
|
57 |
-
{
|
58 |
-
// 读取Demo所用参数
|
59 |
-
resp = getPortGroups(request);
|
60 |
-
}
|
61 |
-
|
62 |
-
// 输出流
|
63 |
-
PrintWriter pw = response.getWriter();
|
64 |
-
// 将结果放到浏览器中
|
65 |
-
|
66 |
-
// BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
67 |
-
// pw.print(resp);
|
68 |
-
// FIXED:
|
69 |
-
|
70 |
-
// 关闭输出流
|
71 |
-
pw.close();
|
72 |
-
}
|
73 |
-
|
74 |
-
/**
|
75 |
-
* 读取Demo所用参数
|
76 |
-
*
|
77 |
-
* @param request
|
78 |
-
* HttpServletRequest对象
|
79 |
-
* @return json格式的字符串
|
80 |
-
* @see
|
81 |
-
* @since eSDK Cloud V100R003C20
|
82 |
-
*/
|
83 |
-
@SuppressWarnings("unchecked")
|
84 |
-
public String getPortGroups(HttpServletRequest request)
|
85 |
-
{
|
86 |
-
// 定义返回结果
|
87 |
-
String response = null;
|
88 |
-
|
89 |
-
LOGGER.info("Begin to read parameters.");
|
90 |
-
|
91 |
-
// 获取Session对象
|
92 |
-
HttpSession session = request.getSession();
|
93 |
-
// 获取key为PORTGROUPSRESOURCE_RES的值
|
94 |
-
FCSDKResponse<PageList<PortGroup>> resp = (FCSDKResponse<PageList<PortGroup>>)session.getAttribute("PORTGROUPSRESOURCE_RES");
|
95 |
-
|
96 |
-
// 根据接口返回数据生成JSON字符串,以便于页面展示
|
97 |
-
response = gson.toJson(resp);
|
98 |
-
LOGGER.info("Finish to read parameters, response is : " + response);
|
99 |
-
|
100 |
-
return response;
|
101 |
-
}
|
102 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10019.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.huawei.esdk.fusioncompute.demo.utils;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import org.apache.log4j.Logger;import com.google.gson.Gson;import com.huawei.esdk.fusioncompute.local.model.FCSDKResponse;import com.huawei.esdk.fusioncompute.local.model.PageList;import com.huawei.esdk.fusioncompute.local.model.net.PortGroup;public class GetPortGroupsServlet extends HttpServlet{ /** * 序列化版本标识 */ private static final long serialVersionUID = 406215323069888871L; /** * log日志对象 */ private static final Logger LOGGER = Logger .getLogger(GetPortGroupsServlet.class); /** * gson,用于转换String和json之间的转换 */ private Gson gson = new Gson(); @Override protected void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } @Override protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取需要调用的方法名 String methodName = request.getParameter("method"); String resp = ""; if ("getPortGroups".equals(methodName)) { // 读取Demo所用参数 resp = getPortGroups(request); } // 输出流 PrintWriter pw = response.getWriter(); // 将结果放到浏览器中 // BUG: CWE-79: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')// pw.print(resp);// FIXED: // 关闭输出流 pw.close(); } /** * 读取Demo所用参数 * * @param request * HttpServletRequest对象 * @return json格式的字符串 * @see * @since eSDK Cloud V100R003C20 */ @SuppressWarnings("unchecked") public String getPortGroups(HttpServletRequest request) { // 定义返回结果 String response = null; LOGGER.info("Begin to read parameters."); // 获取Session对象 HttpSession session = request.getSession(); // 获取key为PORTGROUPSRESOURCE_RES的值 FCSDKResponse<PageList<PortGroup>> resp = (FCSDKResponse<PageList<PortGroup>>)session.getAttribute("PORTGROUPSRESOURCE_RES"); // 根据接口返回数据生成JSON字符串,以便于页面展示 response = gson.toJson(resp); LOGGER.info("Finish to read parameters, response is : " + response); return response; }}
|
data/java/10020.java
DELETED
@@ -1,150 +0,0 @@
|
|
1 |
-
package com.qileyuan.tatala.socket.client;
|
2 |
-
|
3 |
-
import java.io.ByteArrayInputStream;
|
4 |
-
import java.io.IOException;
|
5 |
-
import java.io.InputStream;
|
6 |
-
import java.io.OutputStream;
|
7 |
-
import java.net.BindException;
|
8 |
-
import java.net.Socket;
|
9 |
-
import java.net.SocketException;
|
10 |
-
import java.net.SocketTimeoutException;
|
11 |
-
import java.util.zip.DataFormatException;
|
12 |
-
import java.util.zip.Inflater;
|
13 |
-
|
14 |
-
import org.apache.log4j.Logger;
|
15 |
-
|
16 |
-
import com.qileyuan.tatala.socket.SocketExecuteException;
|
17 |
-
import com.qileyuan.tatala.socket.to.TransferObject;
|
18 |
-
import com.qileyuan.tatala.socket.util.TransferUtil;
|
19 |
-
|
20 |
-
public class ShortClientSession{
|
21 |
-
static Logger log = Logger.getLogger(ShortClientSession.class);
|
22 |
-
|
23 |
-
private String hostIp;
|
24 |
-
private int hostPort;
|
25 |
-
private int timeout;
|
26 |
-
private int retryTime;
|
27 |
-
|
28 |
-
public ShortClientSession(String hostIp, int hostPort, int timeout, int retryTime){
|
29 |
-
this.hostIp = hostIp;
|
30 |
-
this.hostPort = hostPort;
|
31 |
-
this.timeout = timeout;
|
32 |
-
this.retryTime = retryTime;
|
33 |
-
}
|
34 |
-
|
35 |
-
public Object start(TransferObject to) {
|
36 |
-
Object resultObject = null;
|
37 |
-
Socket client = null;
|
38 |
-
String calleeClass = to.getCalleeClass();
|
39 |
-
String calleeMethod = to.getCalleeMethod();
|
40 |
-
try {
|
41 |
-
if(client == null){
|
42 |
-
client = connect();
|
43 |
-
}
|
44 |
-
|
45 |
-
send(client, to);
|
46 |
-
|
47 |
-
resultObject = receive(client, to);
|
48 |
-
} catch (BindException be) {
|
49 |
-
log.error("Connection error: " + be.getMessage());
|
50 |
-
log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]");
|
51 |
-
} catch (SocketTimeoutException ste) {
|
52 |
-
log.error("Socekt timed out, return null. [" + timeout + "ms]");
|
53 |
-
log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]");
|
54 |
-
} catch (Exception e) {
|
55 |
-
log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]");
|
56 |
-
e.printStackTrace();
|
57 |
-
} finally {
|
58 |
-
try {
|
59 |
-
if (client != null) {
|
60 |
-
close(client);
|
61 |
-
}
|
62 |
-
} catch (IOException e) {}
|
63 |
-
}
|
64 |
-
|
65 |
-
return resultObject;
|
66 |
-
}
|
67 |
-
|
68 |
-
private Socket connect() throws SocketException {
|
69 |
-
Socket client = null;
|
70 |
-
String errorMessage = "";
|
71 |
-
int retry = retryTime;
|
72 |
-
while (client == null && retry > 0) {
|
73 |
-
try {
|
74 |
-
|
75 |
-
// BUG: CWE-319: Cleartext Transmission of Sensitive Information
|
76 |
-
// client = new Socket(hostIp, hostPort);
|
77 |
-
// FIXED:
|
78 |
-
|
79 |
-
} catch (Exception e) {
|
80 |
-
log.error("Connection error: " + e.getMessage());
|
81 |
-
errorMessage = e.getMessage();
|
82 |
-
}
|
83 |
-
retry--;
|
84 |
-
if (client == null) {
|
85 |
-
log.error("Retry time: " + retry);
|
86 |
-
}
|
87 |
-
}
|
88 |
-
if (client == null) {
|
89 |
-
throw new BindException(errorMessage);
|
90 |
-
}
|
91 |
-
|
92 |
-
client.setSoTimeout(timeout);
|
93 |
-
client.setReuseAddress(true);
|
94 |
-
//this can avoid socket TIME_WAIT state
|
95 |
-
//client.setSoLinger(true, 0);
|
96 |
-
|
97 |
-
return client;
|
98 |
-
}
|
99 |
-
|
100 |
-
private void send(Socket client, TransferObject to) throws IOException {
|
101 |
-
OutputStream os = client.getOutputStream();
|
102 |
-
|
103 |
-
byte[] sendData = TransferUtil.transferObjectToByteArray(to);
|
104 |
-
|
105 |
-
os.write(sendData);
|
106 |
-
}
|
107 |
-
|
108 |
-
private Object receive(Socket client, TransferObject to) throws IOException, DataFormatException, SocketExecuteException {
|
109 |
-
Object resultObject = null;
|
110 |
-
|
111 |
-
InputStream is = client.getInputStream();
|
112 |
-
// in
|
113 |
-
int compressFlag = is.read();
|
114 |
-
if (compressFlag == 1) {
|
115 |
-
resultObject = doInCompress(is);
|
116 |
-
} else {
|
117 |
-
resultObject = doInNormal(is);
|
118 |
-
}
|
119 |
-
|
120 |
-
return resultObject;
|
121 |
-
}
|
122 |
-
|
123 |
-
private void close(Socket client) throws IOException {
|
124 |
-
OutputStream os = client.getOutputStream();
|
125 |
-
InputStream is = client.getInputStream();
|
126 |
-
os.close();
|
127 |
-
is.close();
|
128 |
-
client.close();
|
129 |
-
}
|
130 |
-
|
131 |
-
private Object doInNormal(InputStream is) throws IOException, SocketExecuteException {
|
132 |
-
return TransferObject.convertReturnInputStream(is);
|
133 |
-
}
|
134 |
-
|
135 |
-
private Object doInCompress(InputStream is) throws IOException, DataFormatException, SocketExecuteException {
|
136 |
-
// in
|
137 |
-
int unCompressedLength = TransferUtil.readInt(is);
|
138 |
-
int compressedLength = TransferUtil.readInt(is);
|
139 |
-
byte[] input = new byte[compressedLength];
|
140 |
-
is.read(input);
|
141 |
-
byte[] output = new byte[unCompressedLength];
|
142 |
-
Inflater decompresser = new Inflater();
|
143 |
-
decompresser.setInput(input);
|
144 |
-
decompresser.inflate(output);
|
145 |
-
decompresser.end();
|
146 |
-
|
147 |
-
InputStream istemp = new ByteArrayInputStream(output);
|
148 |
-
return TransferObject.convertReturnInputStream(istemp);
|
149 |
-
}
|
150 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10020.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
package com.qileyuan.tatala.socket.client;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.BindException;import java.net.Socket;import java.net.SocketException;import java.net.SocketTimeoutException;import java.util.zip.DataFormatException;import java.util.zip.Inflater;import org.apache.log4j.Logger;import com.qileyuan.tatala.socket.SocketExecuteException;import com.qileyuan.tatala.socket.to.TransferObject;import com.qileyuan.tatala.socket.util.TransferUtil;public class ShortClientSession{ static Logger log = Logger.getLogger(ShortClientSession.class); private String hostIp; private int hostPort; private int timeout; private int retryTime; public ShortClientSession(String hostIp, int hostPort, int timeout, int retryTime){ this.hostIp = hostIp; this.hostPort = hostPort; this.timeout = timeout; this.retryTime = retryTime; } public Object start(TransferObject to) { Object resultObject = null; Socket client = null; String calleeClass = to.getCalleeClass(); String calleeMethod = to.getCalleeMethod(); try { if(client == null){ client = connect(); } send(client, to); resultObject = receive(client, to); } catch (BindException be) { log.error("Connection error: " + be.getMessage()); log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]"); } catch (SocketTimeoutException ste) { log.error("Socekt timed out, return null. [" + timeout + "ms]"); log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]"); } catch (Exception e) { log.error("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]"); e.printStackTrace(); } finally { try { if (client != null) { close(client); } } catch (IOException e) {} } return resultObject; } private Socket connect() throws SocketException { Socket client = null; String errorMessage = ""; int retry = retryTime; while (client == null && retry > 0) { try { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// client = new Socket(hostIp, hostPort);// FIXED: } catch (Exception e) { log.error("Connection error: " + e.getMessage()); errorMessage = e.getMessage(); } retry--; if (client == null) { log.error("Retry time: " + retry); } } if (client == null) { throw new BindException(errorMessage); } client.setSoTimeout(timeout); client.setReuseAddress(true); //this can avoid socket TIME_WAIT state //client.setSoLinger(true, 0); return client; } private void send(Socket client, TransferObject to) throws IOException { OutputStream os = client.getOutputStream(); byte[] sendData = TransferUtil.transferObjectToByteArray(to); os.write(sendData); } private Object receive(Socket client, TransferObject to) throws IOException, DataFormatException, SocketExecuteException { Object resultObject = null; InputStream is = client.getInputStream(); // in int compressFlag = is.read(); if (compressFlag == 1) { resultObject = doInCompress(is); } else { resultObject = doInNormal(is); } return resultObject; } private void close(Socket client) throws IOException { OutputStream os = client.getOutputStream(); InputStream is = client.getInputStream(); os.close(); is.close(); client.close(); } private Object doInNormal(InputStream is) throws IOException, SocketExecuteException { return TransferObject.convertReturnInputStream(is); } private Object doInCompress(InputStream is) throws IOException, DataFormatException, SocketExecuteException { // in int unCompressedLength = TransferUtil.readInt(is); int compressedLength = TransferUtil.readInt(is); byte[] input = new byte[compressedLength]; is.read(input); byte[] output = new byte[unCompressedLength]; Inflater decompresser = new Inflater(); decompresser.setInput(input); decompresser.inflate(output); decompresser.end(); InputStream istemp = new ByteArrayInputStream(output); return TransferObject.convertReturnInputStream(istemp); }}
|
data/java/10021.java
DELETED
@@ -1,267 +0,0 @@
|
|
1 |
-
/*
|
2 |
-
* The contents of this file are subject to the Mozilla Public License
|
3 |
-
* Version 2.0 (the "License"); you may not use this file except in
|
4 |
-
* compliance with the License. You may obtain a copy of the License at
|
5 |
-
* https://www.mozilla.org/en-US/MPL/
|
6 |
-
*
|
7 |
-
* Software distributed under the License is distributed on an "AS IS"
|
8 |
-
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
|
9 |
-
* License for the specific language governing rights and limitations
|
10 |
-
* under the License.
|
11 |
-
*
|
12 |
-
* The Original Code is "Simplenlg".
|
13 |
-
*
|
14 |
-
* The Initial Developer of the Original Code is Ehud Reiter, Albert Gatt and Dave Westwater.
|
15 |
-
* Portions created by Ehud Reiter, Albert Gatt and Dave Westwater are Copyright (C) 2010-11 The University of Aberdeen. All Rights Reserved.
|
16 |
-
*
|
17 |
-
* Contributor(s): Ehud Reiter, Albert Gatt, Dave Westwater, Roman Kutlak, Margaret Mitchell, and Saad Mahamood.
|
18 |
-
*/
|
19 |
-
package simplenlg.server;
|
20 |
-
|
21 |
-
import java.io.*;
|
22 |
-
import java.net.ServerSocket;
|
23 |
-
import java.net.Socket;
|
24 |
-
import java.net.SocketException;
|
25 |
-
import java.net.SocketTimeoutException;
|
26 |
-
import java.util.Properties;
|
27 |
-
|
28 |
-
import simplenlg.xmlrealiser.XMLRealiser;
|
29 |
-
import simplenlg.xmlrealiser.XMLRealiser.LexiconType;
|
30 |
-
|
31 |
-
/**
|
32 |
-
* SimpleServer is a program that realises xml requests.
|
33 |
-
*
|
34 |
-
* @author Roman Kutlak.
|
35 |
-
* <p>
|
36 |
-
* The program listens on a socket for client connections.
|
37 |
-
* When a client connects, the server creates an instance
|
38 |
-
* of RealisationRequest that serves the client.
|
39 |
-
* <p>
|
40 |
-
* The RealisationRequest parses the xml structure and
|
41 |
-
* sends back corresponding surface string.
|
42 |
-
* <p>
|
43 |
-
* The server port can be specified as the first parameter
|
44 |
-
* of the program; 50007 is used by default.
|
45 |
-
* <p>
|
46 |
-
* Typing exit will terminate the server.
|
47 |
-
*/
|
48 |
-
public class SimpleServer implements Runnable {
|
49 |
-
|
50 |
-
private ServerSocket serverSocket;
|
51 |
-
|
52 |
-
/**
|
53 |
-
* Set to true to enable printing debug messages.
|
54 |
-
*/
|
55 |
-
static boolean DEBUG = false;
|
56 |
-
|
57 |
-
/**
|
58 |
-
* This path should be replaced by the path to the specialist lexicon.
|
59 |
-
* If there is an entry for DB_FILENAME in lexicon.properties, that path
|
60 |
-
* will be searched for the lexicon file. Otherwise, the path below will
|
61 |
-
* be used.
|
62 |
-
*/
|
63 |
-
String lexiconPath = "src/main/resources/NIHLexicon/lexAccess2013.data";
|
64 |
-
|
65 |
-
// control the run loop
|
66 |
-
private boolean isActive = true;
|
67 |
-
|
68 |
-
/**
|
69 |
-
* Construct a new server.
|
70 |
-
*
|
71 |
-
* @param port the port on which to listen
|
72 |
-
*/
|
73 |
-
public SimpleServer(int port) throws IOException {
|
74 |
-
|
75 |
-
// BUG: CWE-319: Cleartext Transmission of Sensitive Information
|
76 |
-
// startServer(new ServerSocket(port, 8));
|
77 |
-
// FIXED:
|
78 |
-
|
79 |
-
}
|
80 |
-
|
81 |
-
/**
|
82 |
-
* Construct a server with a pre-allocated socket.
|
83 |
-
*
|
84 |
-
* @param socket -- The socket for the server to use.
|
85 |
-
* @throws IOException -- If there is an error when starting the server.
|
86 |
-
*/
|
87 |
-
public SimpleServer(ServerSocket socket) throws IOException {
|
88 |
-
startServer(socket);
|
89 |
-
}
|
90 |
-
|
91 |
-
/**
|
92 |
-
* startServer -- Start's the SimpleServer with a created ServerSocket.
|
93 |
-
*
|
94 |
-
* @param socket -- The socket for the server to use.
|
95 |
-
* @throws IOException -- If there is an error when starting the server.
|
96 |
-
*/
|
97 |
-
private void startServer(ServerSocket socket) throws IOException, SocketException {
|
98 |
-
serverSocket = socket;
|
99 |
-
serverSocket.setReuseAddress(true);
|
100 |
-
serverSocket.setSoTimeout(0);
|
101 |
-
|
102 |
-
System.out.println("Port Number used by Server is: " + serverSocket.getLocalPort());
|
103 |
-
|
104 |
-
// try to read the lexicon path from lexicon.properties file
|
105 |
-
try {
|
106 |
-
Properties prop = new Properties();
|
107 |
-
FileReader reader = new FileReader(new File("./src/main/resources/lexicon.properties"));
|
108 |
-
prop.load(reader);
|
109 |
-
|
110 |
-
String dbFile = prop.getProperty("DB_FILENAME");
|
111 |
-
|
112 |
-
if(null != dbFile)
|
113 |
-
lexiconPath = dbFile;
|
114 |
-
else
|
115 |
-
throw new Exception("No DB_FILENAME in lexicon.properties");
|
116 |
-
} catch(Exception e) {
|
117 |
-
e.printStackTrace();
|
118 |
-
}
|
119 |
-
|
120 |
-
System.out.println("Server is using the following lexicon: " + lexiconPath);
|
121 |
-
|
122 |
-
XMLRealiser.setLexicon(LexiconType.NIHDB, this.lexiconPath);
|
123 |
-
}
|
124 |
-
|
125 |
-
static void print(Object o) {
|
126 |
-
System.out.println(o);
|
127 |
-
}
|
128 |
-
|
129 |
-
/**
|
130 |
-
* Terminate the server. The server can be started
|
131 |
-
* again by invoking the <code>run()</code> method.
|
132 |
-
*/
|
133 |
-
public void terminate() {
|
134 |
-
this.isActive = false;
|
135 |
-
}
|
136 |
-
|
137 |
-
/**
|
138 |
-
* Start the server.
|
139 |
-
* <p>
|
140 |
-
* The server will listen on the port specified at construction
|
141 |
-
* until terminated by calling the <code>terminate()</code> method.
|
142 |
-
* <p>
|
143 |
-
* Note that the <code>exit()</code> and <code>exit(int)</code>
|
144 |
-
* methods will terminate the program by calling System.exit().
|
145 |
-
*/
|
146 |
-
public void run() {
|
147 |
-
try {
|
148 |
-
while(this.isActive) {
|
149 |
-
try {
|
150 |
-
if(DEBUG) {
|
151 |
-
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
|
152 |
-
}
|
153 |
-
|
154 |
-
Socket clientSocket = serverSocket.accept();
|
155 |
-
handleClient(clientSocket);
|
156 |
-
} catch(SocketTimeoutException s) {
|
157 |
-
System.err.println("Socket timed out!");
|
158 |
-
break;
|
159 |
-
} catch(IOException e) {
|
160 |
-
e.printStackTrace();
|
161 |
-
break;
|
162 |
-
}
|
163 |
-
}
|
164 |
-
} catch(Exception e) {
|
165 |
-
e.printStackTrace();
|
166 |
-
} finally {
|
167 |
-
try {
|
168 |
-
this.serverSocket.close();
|
169 |
-
} catch(Exception ee) {
|
170 |
-
System.err.println("Could not close socket!");
|
171 |
-
}
|
172 |
-
}
|
173 |
-
}
|
174 |
-
|
175 |
-
/**
|
176 |
-
* Handle the incoming client connection by constructing
|
177 |
-
* a <code>RealisationRequest</code> and starting it in a thread.
|
178 |
-
*
|
179 |
-
* @param socket the socket on which the client connected
|
180 |
-
*/
|
181 |
-
protected void handleClient(Socket socket) {
|
182 |
-
if(null == socket)
|
183 |
-
return;
|
184 |
-
|
185 |
-
Thread request = new Thread(new RealisationRequest(socket));
|
186 |
-
request.setDaemon(true);
|
187 |
-
request.start();
|
188 |
-
}
|
189 |
-
|
190 |
-
/**
|
191 |
-
* Perform shutdown routines.
|
192 |
-
*/
|
193 |
-
synchronized public void shutdown() {
|
194 |
-
System.out.println("Server shutting down.");
|
195 |
-
|
196 |
-
terminate();
|
197 |
-
// cleanup...like close log, etc.
|
198 |
-
}
|
199 |
-
|
200 |
-
/**
|
201 |
-
* Exit the program without error.
|
202 |
-
*/
|
203 |
-
synchronized public void exit() {
|
204 |
-
exit(0);
|
205 |
-
}
|
206 |
-
|
207 |
-
/**
|
208 |
-
* Exit the program signalling an error code.
|
209 |
-
*
|
210 |
-
* @param code Error code; 0 means no error
|
211 |
-
*/
|
212 |
-
synchronized public void exit(int code) {
|
213 |
-
System.exit(code);
|
214 |
-
}
|
215 |
-
|
216 |
-
/**
|
217 |
-
* The main method that starts the server.
|
218 |
-
* <p>
|
219 |
-
* The program takes one optional parameter,
|
220 |
-
* which is the port number on which to listen.
|
221 |
-
* The default value is 50007.
|
222 |
-
* <p>
|
223 |
-
* Once the program starts, it can be terminated
|
224 |
-
* by typing the command 'exit'
|
225 |
-
*
|
226 |
-
* @param args Program arguments
|
227 |
-
*/
|
228 |
-
public static void main(String[] args) {
|
229 |
-
int port;
|
230 |
-
try {
|
231 |
-
port = Integer.parseInt(args[0]);
|
232 |
-
} catch(Exception e) {
|
233 |
-
port = 50007;
|
234 |
-
}
|
235 |
-
|
236 |
-
try {
|
237 |
-
SimpleServer serverapp = new SimpleServer(port);
|
238 |
-
|
239 |
-
Thread server = new Thread(serverapp);
|
240 |
-
server.setDaemon(true);
|
241 |
-
server.start();
|
242 |
-
|
243 |
-
// allow the user to terminate the server by typing "exit"
|
244 |
-
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
|
245 |
-
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
|
246 |
-
|
247 |
-
while(true) {
|
248 |
-
try {
|
249 |
-
bw.write(":>");
|
250 |
-
bw.flush();
|
251 |
-
String input = br.readLine();
|
252 |
-
|
253 |
-
if(null != input && input.compareToIgnoreCase("exit") == 0) {
|
254 |
-
serverapp.shutdown();
|
255 |
-
serverapp.exit();
|
256 |
-
}
|
257 |
-
} catch(IOException e) {
|
258 |
-
serverapp.shutdown();
|
259 |
-
e.printStackTrace();
|
260 |
-
serverapp.exit(-1);
|
261 |
-
}
|
262 |
-
}
|
263 |
-
} catch(IOException e) {
|
264 |
-
e.printStackTrace();
|
265 |
-
}
|
266 |
-
}
|
267 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
data/java/10021.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
/* * The contents of this file are subject to the Mozilla Public License * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * https://www.mozilla.org/en-US/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * * The Original Code is "Simplenlg". * * The Initial Developer of the Original Code is Ehud Reiter, Albert Gatt and Dave Westwater. * Portions created by Ehud Reiter, Albert Gatt and Dave Westwater are Copyright (C) 2010-11 The University of Aberdeen. All Rights Reserved. * * Contributor(s): Ehud Reiter, Albert Gatt, Dave Westwater, Roman Kutlak, Margaret Mitchell, and Saad Mahamood. */package simplenlg.server;import java.io.*;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketException;import java.net.SocketTimeoutException;import java.util.Properties;import simplenlg.xmlrealiser.XMLRealiser;import simplenlg.xmlrealiser.XMLRealiser.LexiconType;/** * SimpleServer is a program that realises xml requests. * * @author Roman Kutlak. * <p> * The program listens on a socket for client connections. * When a client connects, the server creates an instance * of RealisationRequest that serves the client. * <p> * The RealisationRequest parses the xml structure and * sends back corresponding surface string. * <p> * The server port can be specified as the first parameter * of the program; 50007 is used by default. * <p> * Typing exit will terminate the server. */public class SimpleServer implements Runnable { private ServerSocket serverSocket; /** * Set to true to enable printing debug messages. */ static boolean DEBUG = false; /** * This path should be replaced by the path to the specialist lexicon. * If there is an entry for DB_FILENAME in lexicon.properties, that path * will be searched for the lexicon file. Otherwise, the path below will * be used. */ String lexiconPath = "src/main/resources/NIHLexicon/lexAccess2013.data"; // control the run loop private boolean isActive = true; /** * Construct a new server. * * @param port the port on which to listen */ public SimpleServer(int port) throws IOException { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// startServer(new ServerSocket(port, 8));// FIXED: } /** * Construct a server with a pre-allocated socket. * * @param socket -- The socket for the server to use. * @throws IOException -- If there is an error when starting the server. */ public SimpleServer(ServerSocket socket) throws IOException { startServer(socket); } /** * startServer -- Start's the SimpleServer with a created ServerSocket. * * @param socket -- The socket for the server to use. * @throws IOException -- If there is an error when starting the server. */ private void startServer(ServerSocket socket) throws IOException, SocketException { serverSocket = socket; serverSocket.setReuseAddress(true); serverSocket.setSoTimeout(0); System.out.println("Port Number used by Server is: " + serverSocket.getLocalPort()); // try to read the lexicon path from lexicon.properties file try { Properties prop = new Properties(); FileReader reader = new FileReader(new File("./src/main/resources/lexicon.properties")); prop.load(reader); String dbFile = prop.getProperty("DB_FILENAME"); if(null != dbFile) lexiconPath = dbFile; else throw new Exception("No DB_FILENAME in lexicon.properties"); } catch(Exception e) { e.printStackTrace(); } System.out.println("Server is using the following lexicon: " + lexiconPath); XMLRealiser.setLexicon(LexiconType.NIHDB, this.lexiconPath); } static void print(Object o) { System.out.println(o); } /** * Terminate the server. The server can be started * again by invoking the <code>run()</code> method. */ public void terminate() { this.isActive = false; } /** * Start the server. * <p> * The server will listen on the port specified at construction * until terminated by calling the <code>terminate()</code> method. * <p> * Note that the <code>exit()</code> and <code>exit(int)</code> * methods will terminate the program by calling System.exit(). */ public void run() { try { while(this.isActive) { try { if(DEBUG) { System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "..."); } Socket clientSocket = serverSocket.accept(); handleClient(clientSocket); } catch(SocketTimeoutException s) { System.err.println("Socket timed out!"); break; } catch(IOException e) { e.printStackTrace(); break; } } } catch(Exception e) { e.printStackTrace(); } finally { try { this.serverSocket.close(); } catch(Exception ee) { System.err.println("Could not close socket!"); } } } /** * Handle the incoming client connection by constructing * a <code>RealisationRequest</code> and starting it in a thread. * * @param socket the socket on which the client connected */ protected void handleClient(Socket socket) { if(null == socket) return; Thread request = new Thread(new RealisationRequest(socket)); request.setDaemon(true); request.start(); } /** * Perform shutdown routines. */ synchronized public void shutdown() { System.out.println("Server shutting down."); terminate(); // cleanup...like close log, etc. } /** * Exit the program without error. */ synchronized public void exit() { exit(0); } /** * Exit the program signalling an error code. * * @param code Error code; 0 means no error */ synchronized public void exit(int code) { System.exit(code); } /** * The main method that starts the server. * <p> * The program takes one optional parameter, * which is the port number on which to listen. * The default value is 50007. * <p> * Once the program starts, it can be terminated * by typing the command 'exit' * * @param args Program arguments */ public static void main(String[] args) { int port; try { port = Integer.parseInt(args[0]); } catch(Exception e) { port = 50007; } try { SimpleServer serverapp = new SimpleServer(port); Thread server = new Thread(serverapp); server.setDaemon(true); server.start(); // allow the user to terminate the server by typing "exit" BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); while(true) { try { bw.write(":>"); bw.flush(); String input = br.readLine(); if(null != input && input.compareToIgnoreCase("exit") == 0) { serverapp.shutdown(); serverapp.exit(); } } catch(IOException e) { serverapp.shutdown(); e.printStackTrace(); serverapp.exit(-1); } } } catch(IOException e) { e.printStackTrace(); } }}
|