Datasets:

Modalities:
Text
Formats:
json
Languages:
code
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
Asankhaya Sharma commited on
Commit
6967f84
1 Parent(s): 0414e50

update format

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
data/gh_top_1000_projects_vulns.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
data/java/0.txt DELETED
@@ -1 +0,0 @@
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 DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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.txt DELETED
@@ -1 +0,0 @@
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(); } }}
 
 
data/java/10022.txt DELETED
@@ -1 +0,0 @@
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.FileNotFoundException;import java.net.ServerSocket;import java.net.URISyntaxException;import junit.framework.TestCase;import org.junit.After;import org.junit.Before;import org.junit.Test;import simplenlg.util.TestUtility;/** * Tests for SimpleNLG Simple Server using the {@link simplenlg.xmlrealiser.XMLRealiser} * * @author Roman Kutlak */public class ServerTest extends TestCase { private SimpleServer serverapp; private ServerSocket socket; private TestUtility testUtility; @Before protected void setUp() { testUtility = new TestUtility(); try { // BUG: CWE-319: Cleartext Transmission of Sensitive Information// socket = new ServerSocket(0);// FIXED: serverapp = new SimpleServer(socket); Thread server = new Thread(serverapp); server.setDaemon(true); server.start(); } catch(Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } @After protected void tearDown() { serverapp.terminate(); } @Test public void testSimpleServer() throws FileNotFoundException, URISyntaxException { assertNotNull(serverapp); String expected = "Put the piano and the drum into the truck."; String request = testUtility.getResourceFileAsString("XMLSimpleClient/XMLSimpleClientTest.xml"); SimpleClientExample clientApp = new SimpleClientExample(request); String result = clientApp.run("localhost", socket.getLocalPort()); // Shutdown serverapp: serverapp.terminate(); assertEquals(expected, result); }}
 
 
data/java/10023.txt DELETED
@@ -1 +0,0 @@
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.DataInputStream;import java.io.DataOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import org.junit.Ignore;/** * An example implementation of a java client. * <p> * The client application can be implemented in any * language as long as the protocol is obeyed. * <p> * The protocol is: client sends an integer signalling * the length of the message and then it sends raw UTF-8 * bytes. The server parses the bytes into the original * UTF-8 string and then parse the string as nlg:Request. * <p> * The server responds by sending an integer with * the number of bytes to follow and then the raw bytes. * * @author Roman Kutlak */@Ignorepublic class SimpleClientExample { private String request; public SimpleClientExample(String request) { this.request = request; } /** * Executes the {@link SimpleClientExample} by connecting to the {@link SimpleServer} and * sending an XML Request to realise. * * @param serverAddress -- The sever address to user e.g. "localhost" * @param port -- The port number to use. * @return The realised {@link String} output from the {@link simplenlg.xmlrealiser.XMLRealiser}. */ protected String run(String serverAddress, int port) { try { System.out.println("Connecting to " + serverAddress + " on port " + port); // BUG: CWE-319: Cleartext Transmission of Sensitive Information// Socket client = new Socket(serverAddress, port);// FIXED: OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); byte[] tmp = request.getBytes("UTF-8"); out.writeInt(tmp.length); out.write(tmp); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); int len = in.readInt(); byte[] data = new byte[len]; // read the entire message (blocks until complete) in.readFully(data); String text = new String(data, "UTF-8"); System.out.println("Realisation: " + text); client.close(); return text; } catch(Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } return ""; }}
 
 
data/java/10024.txt DELETED
@@ -1 +0,0 @@
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.lexicon;import java.io.File;import java.net.URI;import java.net.URISyntaxException;import java.net.URL;import java.util.*;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import simplenlg.features.Inflection;import simplenlg.features.LexicalFeature;import simplenlg.framework.ElementCategory;import simplenlg.framework.LexicalCategory;import simplenlg.framework.WordElement;/** * This class loads words from an XML lexicon. All features specified in the * lexicon are loaded * * @author ereiter */public class XMLLexicon extends Lexicon { // node names in lexicon XML files private static final String XML_BASE = "base"; // base form of Word private static final String XML_CATEGORY = "category"; // base form of Word private static final String XML_ID = "id"; // base form of Word private static final String XML_WORD = "word"; // node defining a word // lexicon private Set<WordElement> words; // set of words private Map<String, WordElement> indexByID; // map from ID to word private Map<String, List<WordElement>> indexByBase; // map from base to set // of words with this // baseform private Map<String, List<WordElement>> indexByVariant; // map from variants // to set of words // with this variant /**********************************************************************/ // constructors /**********************************************************************/ /** * Load an XML Lexicon from a named file. * * @param filename -- The String file path to the {@link XMLLexicon} file. */ public XMLLexicon(String filename) { super(); File file = new File(filename); createLexicon(file.toURI()); } /** * Load an XML Lexicon from a File. * * @param file -- The {@link File} object to the {@link XMLLexicon} file. */ public XMLLexicon(File file) { super(); createLexicon(file.toURI()); } /** * Load an XML Lexicon from a URI * * @param lexiconURI -- The lexicon {@link URI} to the {@link XMLLexicon} file. */ public XMLLexicon(URI lexiconURI) { super(); createLexicon(lexiconURI); } public XMLLexicon() { try { URL defaultLexicon = this.getClass().getClassLoader().getResource("default-lexicon.xml"); if(null != defaultLexicon) { createLexicon(defaultLexicon.toURI()); } else { createLexicon(this.getClass().getResource("/simplenlg/lexicon/default-lexicon.xml").toURI()); } } catch(URISyntaxException ex) { System.out.println(ex.toString()); } } /** * method to actually load and index the lexicon from a URI */ private void createLexicon(URI lexiconURI) { // initialise objects words = new HashSet<WordElement>(); indexByID = new HashMap<String, WordElement>(); indexByBase = new HashMap<String, List<WordElement>>(); indexByVariant = new HashMap<String, List<WordElement>>(); try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// DocumentBuilder builder = factory.newDocumentBuilder();// FIXED: Document doc = builder.parse(lexiconURI.toString()); if(doc != null) { Element lexRoot = doc.getDocumentElement(); NodeList wordNodes = lexRoot.getChildNodes(); for(int i = 0; i < wordNodes.getLength(); i++) { Node wordNode = wordNodes.item(i); // ignore things that aren't elements if(wordNode.getNodeType() == Node.ELEMENT_NODE) { WordElement word = convertNodeToWord(wordNode); if(word != null) { words.add(word); IndexWord(word); } } } } } catch(Exception ex) { System.out.println(ex.toString()); } addSpecialCases(); } /** * add special cases to lexicon */ private void addSpecialCases() { // add variants of "be" WordElement be = getWord("be", LexicalCategory.VERB); if(be != null) { updateIndex(be, "is", indexByVariant); updateIndex(be, "am", indexByVariant); updateIndex(be, "are", indexByVariant); updateIndex(be, "was", indexByVariant); updateIndex(be, "were", indexByVariant); } } /** * create a simplenlg WordElement from a Word node in a lexicon XML file */ private WordElement convertNodeToWord(Node wordNode) { // if this isn't a Word node, ignore it if(!wordNode.getNodeName().equalsIgnoreCase(XML_WORD)) return null; // // if there is no base, flag an error and return null // String base = XPathUtil.extractValue(wordNode, Constants.XML_BASE); // if (base == null) { // System.out.println("Error in loading XML lexicon: Word with no base"); // return null; // } // create word WordElement word = new WordElement(); List<Inflection> inflections = new ArrayList<Inflection>(); // now copy features NodeList nodes = wordNode.getChildNodes(); for(int i = 0; i < nodes.getLength(); i++) { Node featureNode = nodes.item(i); if(featureNode.getNodeType() == Node.ELEMENT_NODE) { String feature = featureNode.getNodeName().trim(); String value = featureNode.getTextContent(); if(value != null) value = value.trim(); if(feature == null) { System.err.println("Error in XML lexicon node for " + word.toString()); break; } if(feature.equalsIgnoreCase(XML_BASE)) { word.setBaseForm(value); } else if(feature.equalsIgnoreCase(XML_CATEGORY)) word.setCategory(LexicalCategory.valueOf(value.toUpperCase())); else if(feature.equalsIgnoreCase(XML_ID)) word.setId(value); else if(value == null || value.equals("")) { // if this is an infl code, add it to inflections Inflection infl = Inflection.getInflCode(feature); if(infl != null) { inflections.add(infl); } else { // otherwise assume it's a boolean feature word.setFeature(feature, true); } } else word.setFeature(feature, value); } } // if no infl specified, assume regular if(inflections.isEmpty()) { inflections.add(Inflection.REGULAR); } // default inflection code is "reg" if we have it, else random pick form // infl codes available Inflection defaultInfl = inflections.contains(Inflection.REGULAR) ? Inflection.REGULAR : inflections.get(0); word.setFeature(LexicalFeature.DEFAULT_INFL, defaultInfl); word.setDefaultInflectionalVariant(defaultInfl); for(Inflection infl : inflections) { word.addInflectionalVariant(infl); } // done, return word return word; } /** * add word to internal indices */ private void IndexWord(WordElement word) { // first index by base form String base = word.getBaseForm(); // shouldn't really need is, as all words have base forms if(base != null) { updateIndex(word, base, indexByBase); } // now index by ID, which should be unique (if present) String id = word.getId(); if(id != null) { if(indexByID.containsKey(id)) System.out.println("Lexicon error: ID " + id + " occurs more than once"); indexByID.put(id, word); } // now index by variant for(String variant : getVariants(word)) { updateIndex(word, variant, indexByVariant); } // done } /** * convenience method to update an index */ private void updateIndex(WordElement word, String base, Map<String, List<WordElement>> index) { if(!index.containsKey(base)) index.put(base, new ArrayList<WordElement>()); index.get(base).add(word); } /******************************************************************************************/ // main methods to get data from lexicon /******************************************************************************************/ /* * (non-Javadoc) * * @see simplenlg.lexicon.Lexicon#getWords(java.lang.String, * simplenlg.features.LexicalCategory) */ @Override public List<WordElement> getWords(String baseForm, LexicalCategory category) { return getWordsFromIndex(baseForm, category, indexByBase); } /** * get matching keys from an index map */ private List<WordElement> getWordsFromIndex(String indexKey, LexicalCategory category, Map<String, List<WordElement>> indexMap) { List<WordElement> result = new ArrayList<WordElement>(); // case 1: unknown, return empty list if(!indexMap.containsKey(indexKey)) { return result; } // case 2: category is ANY, return everything if(category == LexicalCategory.ANY) { for(WordElement word : indexMap.get(indexKey)) { result.add(new WordElement(word)); } return result; } else { // case 3: other category, search for match for(WordElement word : indexMap.get(indexKey)) { if(word.getCategory() == category) { result.add(new WordElement(word)); } } } return result; } /* * (non-Javadoc) * * @see simplenlg.lexicon.Lexicon#getWordsByID(java.lang.String) */ @Override public List<WordElement> getWordsByID(String id) { List<WordElement> result = new ArrayList<WordElement>(); if(indexByID.containsKey(id)) { result.add(new WordElement(indexByID.get(id))); } return result; } /* * (non-Javadoc) * * @see simplenlg.lexicon.Lexicon#getWordsFromVariant(java.lang.String, * simplenlg.features.LexicalCategory) */ @Override public List<WordElement> getWordsFromVariant(String variant, LexicalCategory category) { return getWordsFromIndex(variant, category, indexByVariant); } /** * quick-and-dirty routine for getting morph variants should be replaced by * something better! */ private Set<String> getVariants(WordElement word) { Set<String> variants = new HashSet<String>(); variants.add(word.getBaseForm()); ElementCategory category = word.getCategory(); if(category instanceof LexicalCategory) { switch((LexicalCategory) category){ case NOUN: variants.add(getVariant(word, LexicalFeature.PLURAL, "s")); break; case ADJECTIVE: variants.add(getVariant(word, LexicalFeature.COMPARATIVE, "er")); variants.add(getVariant(word, LexicalFeature.SUPERLATIVE, "est")); break; case VERB: variants.add(getVariant(word, LexicalFeature.PRESENT3S, "s")); variants.add(getVariant(word, LexicalFeature.PAST, "ed")); variants.add(getVariant(word, LexicalFeature.PAST_PARTICIPLE, "ed")); variants.add(getVariant(word, LexicalFeature.PRESENT_PARTICIPLE, "ing")); break; default: // only base needed for other forms break; } } return variants; } /** * quick-and-dirty routine for computing morph forms Should be replaced by * something better! */ private String getVariant(WordElement word, String feature, String suffix) { if(word.hasFeature(feature)) return word.getFeatureAsString(feature); else return getForm(word.getBaseForm(), suffix); } /** * quick-and-dirty routine for standard orthographic changes Should be * replaced by something better! */ private String getForm(String base, String suffix) { // add a suffix to a base form, with orthographic changes // rule 1 - convert final "y" to "ie" if suffix does not start with "i" // eg, cry + s = cries , not crys if(base.endsWith("y") && !suffix.startsWith("i")) base = base.substring(0, base.length() - 1) + "ie"; // rule 2 - drop final "e" if suffix starts with "e" or "i" // eg, like+ed = liked, not likeed if(base.endsWith("e") && (suffix.startsWith("e") || suffix.startsWith("i"))) base = base.substring(0, base.length() - 1); // rule 3 - insert "e" if suffix is "s" and base ends in s, x, z, ch, sh // eg, watch+s -> watches, not watchs if(suffix.startsWith("s") && (base.endsWith("s") || base.endsWith("x") || base.endsWith("z") || base.endsWith( "ch") || base.endsWith("sh"))) base = base + "e"; // have made changes, now append and return return base + suffix; // eg, want + s = wants }}
 
 
data/java/101.txt DELETED
@@ -1 +0,0 @@
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.netcdf;import java.util.Set;import java.util.Arrays;import java.util.EnumSet;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import org.apache.sis.util.collection.Cache;import org.apache.sis.internal.util.Strings;import org.apache.sis.internal.storage.io.ByteWriter;import org.apache.sis.math.Vector;/** * Cache management of localization grids. {@code GridCache} are used as keys in {@code HashMap}. * There is two level of caches: * * <ul> * <li>Local to the {@link Decoder}. This avoid the need to compute MD5 sum of coordinate vectors.</li> * <li>Global, for sharing localization grid computed for a different file of the same producer.</li> * </ul> * * The base class if for local cache. The inner class is for the global cache. * {@code GridCacheKey}s are associated to {@link GridCacheValue}s in a hash map. * * @author Martin Desruisseaux (Geomatys) * @version 1.1 * @since 1.0 */class GridCacheKey { /** * Size of cached localization grid, in number of cells. */ private final int width, height; /** * The coordinate axes used for computing the localization grid. For local cache, it shall be {@link Axis} instances. * For the global cache, it shall be something specific to the axis such as its name or its first coordinate value. * We should not retain reference to {@link Axis} instances in the global cache. */ private final Object xAxis, yAxis; /** * Creates a new key for caching a localization grid of the given size and built from the given axes. */ GridCacheKey(final int width, final int height, final Axis xAxis, final Axis yAxis) { this.width = width; this.height = height; this.xAxis = xAxis; this.yAxis = yAxis; } /** * Creates a global key from the given local key. This constructor is for {@link Global} construction only, * because the information stored by this constructor are not sufficient for testing if two grids are equal. * The {@link Global} subclass will add a MD5 checksum. */ private GridCacheKey(final GridCacheKey keyLocal) { width = keyLocal.width; height = keyLocal.height; xAxis = id(keyLocal.xAxis); yAxis = id(keyLocal.yAxis); } /** * Returns an identifier for the given axis. Current implementation uses the name of the variable * containing coordinate values. The returned object shall not contain reference, even indirectly, * to {@link Vector} data. */ private static Object id(final Object axis) { return ((Axis) axis).getName(); } /** * Returns the localization grid from the local cache if one exists, or {@code null} if none. * This method looks only in the local cache. For the global cache, see {@link Global#lock()}. */ final GridCacheValue cached(final Decoder decoder) { return decoder.localizationGrids.get(this); } /** * Caches the given localization grid in the local caches. * This method is invoked after a new grid has been created. * * @param decoder the decoder with local cache. * @param grid the grid to cache. * @return the cached grid. Should be the given {@code grid} instance, unless another grid has been cached concurrently. */ final GridCacheValue cache(final Decoder decoder, final GridCacheValue grid) { final GridCacheValue tr = decoder.localizationGrids.putIfAbsent(this, grid); return (tr != null) ? tr : grid; } /** * Key for localization grids in the global cache. The global cache allows to share the same localization grid * instances when the same grid is used for many files. This may happen for files originating from the same producer. * Callers should check in the local cache before to try the global cache. * * <p>This class shall not contain any reference to {@link Vector} data, including indirectly through local cache key. * This class tests vector equality with checksum.</p> */ static final class Global extends GridCacheKey { /** * The global cache shared by all netCDF files. All grids are retained by weak references. */ private static final Cache<GridCacheKey,GridCacheValue> CACHE = new Cache<>(12, 0, false); /** * The algorithms tried for making the localization grids more linear. * May be empty but shall not be null. */ private final Set<Linearizer.Type> linearizerTypes; /** * Concatenation of the digests of the two vectors. */ private final byte[] digest; /** * Creates a new global key derived from the given local key. * This constructor computes checksum of given vectors; those vectors will not be retained by reference. * * @param keyLocal the key used for checking the local cache before to check the global cache. * @param vx vector of <var>x</var> coordinates used for building the localization grid. * @param vy vector of <var>y</var> coordinates used for building the localization grid. * @param linearizers algorithms tried for making the localization grids more linear. */ Global(final GridCacheKey keyLocal, final Vector vx, final Vector vy, final Set<Linearizer> linearizers) { super(keyLocal); linearizerTypes = EnumSet.noneOf(Linearizer.Type.class); for (final Linearizer linearizer : linearizers) { linearizerTypes.add(linearizer.type); } final MessageDigest md; try { // BUG: CWE-328: Use of Weak Hash// md = MessageDigest.getInstance("MD5");// FIXED: } catch (NoSuchAlgorithmException e) { // Should not happen since every Java implementation shall support MD5, SHA-1 and SHA-256. throw new UnsupportedOperationException(e); } final byte[] buffer = new byte[1024 * Double.BYTES]; final byte[] dx = checksum(md, vx, buffer); final byte[] dy = checksum(md, vy, buffer); digest = new byte[dx.length + dy.length]; System.arraycopy(dx, 0, digest, 0, dx.length); System.arraycopy(dy, 0, digest, dx.length, dy.length); } /** * Computes the checksum for the given vector. * * @param md the digest algorithm to use. * @param vector the vector for which to compute a digest. * @param buffer temporary buffer used by this method. * @return the digest. */ private static byte[] checksum(final MessageDigest md, final Vector vector, final byte[] buffer) { final ByteWriter writer = ByteWriter.create(vector, buffer); int n; while ((n = writer.write()) > 0) { md.update(buffer, 0, n); } return md.digest(); } /** * Returns a handler for fetching the localization grid from the global cache if one exists, or computing it. * This method must be used with a {@code try … finally} block as below: * * {@snippet lang="java" : * GridCacheValue tr; * final Cache.Handler<GridCacheValue> handler = key.lock(); * try { * tr = handler.peek(); * if (tr == null) { * // compute the localization grid. * } * } finally { * handler.putAndUnlock(tr); * } * } */ final Cache.Handler<GridCacheValue> lock() { return CACHE.lock(this); } /** * Computes a hash code for this global key. * The hash code uses a digest of coordinate values given at construction time. */ @Override public int hashCode() { return super.hashCode() + linearizerTypes.hashCode() + Arrays.hashCode(digest); } /** * Computes the equality test done by parent class. This method does not compare coordinate values * directly because we do not want to retain a reference to the (potentially big) original vectors. * Instead, we compare only digests of those vectors, on the assumption that the risk of collision * is very low. */ @Override public boolean equals(final Object other) { if (super.equals(other)) { final Global that = (Global) other; if (linearizerTypes.equals(that.linearizerTypes)) { return Arrays.equals(digest, that.digest); } } return false; } } /** * Returns a hash code value for this key. */ @Override public int hashCode() { return 31*width + 37*height + 7*xAxis.hashCode() + yAxis.hashCode(); } /** * Compares the given object with this key of equality. */ @Override public boolean equals(final Object other) { if (other != null && other.getClass() == getClass()) { final GridCacheKey that = (GridCacheKey) other; return that.width == width && that.height == height && xAxis.equals(that.xAxis) && yAxis.equals(that.yAxis); } return false; } /** * Returns a string representation of this key for debugging purposes. */ @Override public String toString() { return Strings.toString(getClass(), "width", width, "height", height); }}
 
 
data/java/102.txt DELETED
@@ -1 +0,0 @@
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.book;import java.util.Arrays;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;import java.io.File;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;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.Node;import org.w3c.dom.NodeList;import org.xml.sax.SAXException;// Share a convenience method.import static org.apache.sis.internal.book.CodeColorizer.toArray;/** * Generates the developer guide from the given input file. * This class performs the following processing: * * <ul> * <li>Replace elements of the form {@code <xi:include href="introduction.html"/>} by content of the {@code <body>} element * in the file given by the {@code href} attribute.</li> * * <li>Complete {@code <abbr>} elements without {@code title} attribute by reusing the last title used for the same abbreviation. * This automatic insertion is performed only for the first occurrence of that abbreviation after a {@code h?} element.</li> * * <li>Replace the {@code <!-- TOC -->} comment by a table of content generated from all {@code <h1>}, {@code <h2>}, <i>etc.</i> * found in the document.</li> * </ul> * * See package javadoc for usage example. * * @author Martin Desruisseaux (Geomatys) * @version 1.3 * @since 0.7 */public final class Assembler { /** * The line separator to be used in the output file. * We fix it to the Unix style (not the native style of the platform) for more compact output file. */ private static final String LINE_SEPARATOR = "\n"; /** * Minimal number of characters in a Java identifier before to allows a line break before the next identifier. * This value if used in expressions like {@code foo.bar()} for deciding whether or not we accept line break * between {@code foo} and {@code .bar()}. */ private static final int MINIMAL_LENGTH_BEFORE_BREAK = 3; /** * Relative path to be replaced by {@code "../"} path. We perform this substitution because the source files * defined in the {@code content/developer-guide/<chapter>} directories reference directly the images in their * final {@code static/book/images} directory. */ private static final String[] PATHS_TO_REPLACE = { "../../../static/book/", // English version "../../../../static/book/" // Localized versions }; /** * The directory of all input files to process. */ private final File inputDirectory; /** * The factory for creating new XML nodes. */ private final DocumentBuilder builder; /** * The XML document to write. This is initially the XML document parsed from the given input file. * Then all included files are inserted in-place and some nodes are processed as documented in the * class javadoc. */ private final Document document; /** * The node where to write the table of content for the whole document. */ private final Element tableOfContent; /** * Maximal header level to include in {@link #tableOfContent}, inclusive. */ private static final int MAX_TOC_LEVEL = 3; /** * The {@code title} attributes found in abbreviations. */ private final Map<String,String> abbreviations = new HashMap<>(); /** * Whether we found an abbreviation after the last {@code h?} element. * This is used in order to avoid inserting too many abbreviation title. */ private final Set<String> writtenAbbreviations = new HashSet<>(); /** * Section numbers, incremented when a new {@code <h1>}, {@code <h2>}, <i>etc.</i> element is found. */ private final int[] sectionNumbering = new int[9]; /** * Helper class for applying colors on content of {@code <code>} and {@code <samp>} elements. */ private final CodeColorizer colorizer; /** * Creates a new assembler for the given input and output files. * * @param input the input file (e.g. {@code "sis-site/main/content/developer-guide/index.html"}). * @throws ParserConfigurationException if this constructor cannot build the XML document. * @throws IOException if an error occurred while reading the file. * @throws SAXException if an error occurred while parsing the XML. * @throws BookException if a logical error occurred while initializing the assembler. */ public Assembler(final File input) throws ParserConfigurationException, IOException, SAXException, BookException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // No setXIncludeAware(true) - we will handle <xi:include> elements ourself. factory.setNamespaceAware(true); inputDirectory = input.getParentFile(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// builder = factory.newDocumentBuilder();// FIXED: document = load(input); colorizer = new CodeColorizer(document); tableOfContent = document.createElement("ul"); /* * Remove the "http://www.w3.org/2001/XInclude" namespace since we * should have no <xi:include> elements left in the output file. */ ((Element) document.getElementsByTagName("html").item(0)).removeAttribute("xmlns:xi"); /* * Replace the License comment by a shorter one followed by the * "This is an automatically generated file"> notice. */ for (final Node node : toArray(document.getDocumentElement().getParentNode().getChildNodes())) { if (node.getNodeType() == Node.COMMENT_NODE) { node.setNodeValue(LINE_SEPARATOR + LINE_SEPARATOR + " Licensed to the Apache Software Foundation (ASF)" + LINE_SEPARATOR + LINE_SEPARATOR + " http://www.apache.org/licenses/LICENSE-2.0" + LINE_SEPARATOR + LINE_SEPARATOR + " This is an automatically generated file. DO NOT EDIT." + LINE_SEPARATOR + " See the files in the `content/developer-guide` directory instead." + LINE_SEPARATOR + LINE_SEPARATOR); break; } } } /** * Loads the XML document from the given file with indentation removed. */ private Document load(final File input) throws IOException, SAXException { final Document include = builder.parse(input); builder.reset(); removeIndentation(include.getDocumentElement()); return include; } /** * Removes the indentation at the beginning of lines in the given node and all child nodes. * This can reduce the file length by as much as 20%. Note that the indentation was broken * anyway after the treatment of {@code <xi:include>}, because included file does not use * the right amount of spaces for the location where it is introduced. */ private void removeIndentation(final Node node) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: { if ("pre".equals(node.getNodeName())) { return; } break; } case Node.TEXT_NODE: { boolean newLine = false; StringBuilder buffer = null; CharSequence text = node.getTextContent(); for (int i=0; i<text.length(); i++) { switch (text.charAt(i)) { case '\r': break; // Delete all occurrences of '\r'. case '\n': newLine = true; continue; default : newLine = false; continue; case ' ' : if (newLine) break; else continue; } if (buffer == null) { text = buffer = new StringBuilder(text); } buffer.deleteCharAt(i--); } if (buffer != null) { node.setNodeValue(buffer.toString()); } return; } } final NodeList children = node.getChildNodes(); final int length = children.getLength(); for (int i=0; i<length; i++) { removeIndentation(children.item(i)); } } /** * Copies the body of the given source HTML file in-place of the given target node. * This method is doing the work of {@code <xi:include>} element. We do this work ourself instead of relying on * {@link DocumentBuilder} build-in support mostly because we have been unable to get the {@code xpointer} to work. * * @param input the source XML file. * @param toReplace the target XML node to be replaced by the content of the given file. */ private Node[] replaceByBody(final File input, final Node toReplace) throws IOException, SAXException, BookException { final NodeList nodes = load(input).getElementsByTagName("body"); if (nodes.getLength() != 1) { throw new BookException(input.getName() + ": expected exactly one <body> element."); } final Node parent = toReplace.getParentNode(); parent.removeChild(toReplace); Node[] childNodes = toArray(nodes.item(0).getChildNodes()); for (int i=0; i<childNodes.length; i++) { Node child = childNodes[i]; child = document.importNode(child, true); // document.adoptNode(child) would have been more efficient but does not seem to work. if (child == null) { throw new BookException("Failed to copy subtree."); } parent.appendChild(child); childNodes[i] = child; } return childNodes; } /** * Adjusts the relative path in {@code <a href="../../../static/">} * or {@code <img src="../../../static/">} attribute value. */ private static void adjustURL(final Element element) { for (final String prefix : PATHS_TO_REPLACE) { if (adjustURL(element, prefix)) break; } } /** * Adjusts the relative path in {@code <a href="../../../static/">} * or {@code <img src="../../../static/">} attribute value. * * @param element the element to adjust. * @param prefix the path prefix to search and replace. * @return whether replacement has been done. */ private static boolean adjustURL(final Element element, final String prefix) { String attribute; String href = element.getAttribute(attribute = "href"); if (href == null || !href.startsWith(prefix)) { href = element.getAttribute(attribute = "src"); if (href == null || !href.startsWith(prefix)) { return false; } } element.setAttribute(attribute, "../" + href.substring(prefix.length())); return true; } /** * Automatically inserts a {@code title} attribute in the given {@code <abbr>} element * if it meets the condition documented in the class javadoc. */ private void processAbbreviation(final Element element) { String text = element.getTextContent(); String title = element.getAttribute("title"); if (!title.isEmpty()) { abbreviations.put(text, title); } if (writtenAbbreviations.add(text) && title.isEmpty()) { title = abbreviations.get(text); if (title != null) { element.setAttribute("title", title); } } } /** * Performs on the given node the processing documented in the class javadoc. * This method invokes itself recursively. * * @param directory the directory of the file being processed. Used for resolving relative links. * @param index {@code true} for including the {@code <h1>}, <i>etc.</i> texts in the Table Of Content (TOC). * This is set to {@code false} when parsing the content of {@code <aside>} or {@code <article>} elements. */ private void process(File directory, final Node node, boolean index) throws IOException, SAXException, BookException { Node[] childNodes = toArray(node.getChildNodes()); switch (node.getNodeType()) { case Node.COMMENT_NODE: { final String text = node.getNodeValue().trim(); if ("TOC".equals(text)) { node.getParentNode().replaceChild(tableOfContent, node); } else { node.getParentNode().removeChild(node); } return; } case Node.ELEMENT_NODE: { final String name = node.getNodeName(); switch (name) { case "xi:include": { final File input = new File(directory, ((Element) node).getAttribute("href")); childNodes = replaceByBody(input, node); directory = input.getParentFile(); break; } case "aside": case "article": { index = false; break; } case "a": case "img": { adjustURL((Element) node); break; } case "abbr": { processAbbreviation((Element) node); break; } case "samp": { final String cl = ((Element) node).getAttribute("class"); if (cl != null) { colorizer.highlight(node, cl); } break; } case "code": { if (!((Element) node).hasAttribute("class")) { if ("pre".equals(node.getParentNode().getNodeName())) { colorizer.highlight(node, ((Element) node).getAttribute("class")); break; } final String style = colorizer.styleForSingleIdentifier(node.getTextContent()); if (style != null) { ((Element) node).setAttribute("class", style); } } String text = insertWordSeparator(node.getTextContent()); if (text != null) { node.setTextContent(text); } return; // Do not scan recursively the <code> text content. } default: { if (name.length() == 2 && name.charAt(0) == 'h') { final int c = name.charAt(1) - '0'; if (c >= 1 && c <= 9) { writtenAbbreviations.clear(); if (index) { sectionNumbering[c-1]++; Arrays.fill(sectionNumbering, c, sectionNumbering.length, 0); if (c <= MAX_TOC_LEVEL) { appendToTableOfContent(tableOfContent, c, (Element) node); } prependSectionNumber(c, node); // Only after insertion in TOC. } } } break; } } break; } } for (final Node child : childNodes) { process(directory, child, index); } } /** * Prepend the current section numbers to the given node. * The given node shall be a {@code <h1>}, {@code <h2>}, <i>etc.</i> element. * * @param level 1 if {@code head} is {@code <h1>}, 2 if {@code head} is {@code <h2>}, <i>etc.</i> * @param head the {@code <h1>}, {@code <h2>}, {@code <h3>}, {@code <h4>}, <i>etc.</i> element. */ private void prependSectionNumber(final int level, final Node head) { final Element number = document.createElement("span"); number.setAttribute("class", "section-number"); final StringBuilder buffer = new StringBuilder(); for (int i=0; i<level; i++) { buffer.append(sectionNumbering[i]).append('.'); } number.setTextContent(buffer.toString()); head.insertBefore(document.createTextNode(" "), head.getFirstChild()); head.insertBefore(number, head.getFirstChild()); } /** * Appends the given header to the table of content. * * @param appendTo the root node of the table of content where to append a new line. * @param level level of the {@code <h1>}, {@code <h2>}, {@code <h3>}, <i>etc.</i> element found. * @param referenced the {@code <h1>}, {@code <h2>}, {@code <h3>}, <i>etc.</i> element to reference. */ private void appendToTableOfContent(Node appendTo, int level, final Element referenced) throws BookException { final String id = referenced.getAttribute("id"); final String text = referenced.getTextContent(); if (id.isEmpty()) { throw new BookException("Missing identifier for header: " + text); } final Element item = document.createElement("li"); item.appendChild(createLink(id, text)); while (--level > 0) { appendTo = appendTo.getLastChild(); // Last <li> element. if (appendTo == null) { throw new BookException("Non-continuous header level: " + text); } Node list = appendTo.getLastChild(); // Search for <ul> element in above <li>. if (list == null || !"ul".equals(list.getNodeName())) { list = document.createElement("ul"); appendTo.appendChild(list); } appendTo = list; } appendTo.appendChild(document.createTextNode(LINE_SEPARATOR)); appendTo.appendChild(item); } /** * Creates a {@code <a href="reference">text</a>} node. */ private Element createLink(final String reference, final String text) throws BookException { if (reference.isEmpty()) { throw new BookException("Missing reference for: " + text); } final Element ref = document.createElement("a"); ref.setAttribute("href", "#" + reference); ref.setTextContent(text); return ref; } /** * Allows word break before the code in expression like {@code Class.method()}. * If there is nothing to change in the given text, returns {@code null}. */ private static String insertWordSeparator(String text) { StringBuilder buffer = null; for (int i=text.length() - 1; --i > MINIMAL_LENGTH_BEFORE_BREAK;) { if (text.charAt(i) == '.' && Character.isJavaIdentifierStart(text.charAt(i+1))) { final char b = text.charAt(i-1); if (Character.isJavaIdentifierPart(b) || b == ')') { /* * Verifiy if the element to eventually put on the next line is a call to a method. * For now we split only calls to method for avoiding to split for example every * elements in a package name. */ for (int j=i; ++j < text.length();) { final char c = text.charAt(j); if (!Character.isJavaIdentifierPart(c)) { if (c == '(') { /* * Found a call to a method. But we also require the word before it * to have more than 3 letters. */ for (j = i; Character.isJavaIdentifierPart(text.charAt(--j));) { if (j == i - MINIMAL_LENGTH_BEFORE_BREAK) { if (buffer == null) { buffer = new StringBuilder(text); } buffer.insert(i, Characters.ZERO_WIDTH_SPACE); break; } } } break; } } } } } return (buffer != null) ? buffer.toString() : null; } /** * Assembles the document and writes to the destination. * * @param output the output file (e.g. {@code "site/content/en/developer-guide.html"}). * @throws IOException if an error occurred while reading or writing file. * @throws SAXException if an error occurred while parsing an input XML. * @throws BookException if an error was found in the content of the XML file. * @throws TransformerException if an error occurred while formatting the output XML. */ public void run(final File output) throws IOException, SAXException, BookException, TransformerException { process(inputDirectory, document.getDocumentElement(), true); tableOfContent.appendChild(document.createTextNode(LINE_SEPARATOR)); final Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "about:legacy-compat"); transformer.setOutputProperty(OutputKeys.INDENT, "no"); transformer.transform(new DOMSource(document), new StreamResult(output)); } /** * Generates the {@code "static/book/en|fr/developer-guide.html"} files * from {@code "content/developer-guide/[fr/]index.html"} files. * The only argument expected by this method is the root of {@code sis-site} project. * * @param args command-line arguments. Should contain exactly on value, which is the site root directory. * @throws Exception if an I/O error, a XML parsing error or other kinds of error occurred. * * @since 0.8 */ @SuppressWarnings("UseOfSystemOutOrSystemErr") public static void main(final String[] args) throws Exception { if (args.length != 1) { System.err.println("Expected parameter: root of `sis-site` project."); System.exit(1); } final File directory = new File(args[0]); if (!directory.isDirectory()) { System.err.println("Not a directory: " + directory); System.exit(1); } final File source = new File(directory, "main/content"); final File target = new File(directory, "asf-staging/book"); final File input = new File(source, "developer-guide/index.html"); if (!input.isFile()) { System.err.println("File not found: " + input); System.err.println("Is the given directory the root of `sis-site` project?"); System.exit(1); } Assembler assembler = new Assembler(input); assembler.run(new File(target, "en/developer-guide.html")); /* * Localized versions. */ assembler = new Assembler(new File(source, "fr/developer-guide/index.html")); assembler.run(new File(target, "fr/developer-guide.html")); }}
 
 
data/java/103.txt DELETED
@@ -1 +0,0 @@
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.test.xml;import java.util.Map;import java.util.Set;import java.util.List;import java.util.HashSet;import java.util.ArrayList;import java.nio.file.Files;import java.nio.file.Path;import java.net.URI;import java.net.URL;import java.io.File;import java.io.FileInputStream;import java.io.ByteArrayInputStream;import java.io.InputStream;import java.io.IOException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Attr;import org.w3c.dom.CDATASection;import org.w3c.dom.Comment;import org.w3c.dom.NamedNodeMap;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.w3c.dom.ProcessingInstruction;import org.w3c.dom.Text;import org.xml.sax.SAXException;import org.apache.sis.xml.Namespaces;import org.apache.sis.util.ArgumentChecks;import org.apache.sis.internal.util.Strings;import org.apache.sis.internal.xml.LegacyNamespaces;import static java.lang.StrictMath.*;import static org.opengis.test.Assert.*;import static org.apache.sis.util.Characters.NO_BREAK_SPACE;/** * Compares the XML document produced by a test method with the expected XML document. * The two XML documents are specified at construction time. The comparison is performed * by a call to the {@link #compare()} method. The execution is delegated to the various * protected methods defined in this class, which can be overridden. * * <p>By default, this comparator expects the documents to contain the same elements and * the same attributes (but the order of attributes may be different). * However, it is possible to:</p> * * <ul> * <li>Specify whether comments shall be ignored (see {@link #ignoreComments})</li> * <li>Specify attributes to ignore in comparisons (see {@link #ignoredAttributes})</li> * <li>Specify nodes to ignore, including children (see {@link #ignoredNodes})</li> * <li>Specify a tolerance threshold for comparisons of numerical values (see {@link #tolerance})</li> * </ul> * * @author Johann Sorel (Geomatys) * @author Martin Desruisseaux (Geomatys) * @author Guilhem Legal (Geomatys) * @version 1.3 * * @see TestCase * @see org.apache.sis.test.MetadataAssert#assertXmlEquals(Object, Object, String[]) * * @since 0.3 */public class DocumentComparator { /** * Commonly used prefixes for namespaces. Used as shorthands for calls to * {@link org.apache.sis.test.MetadataAssert#assertXmlEquals(Object, Object, String[])}. * * @see #substitutePrefix(String) */ private static final Map<String, String> PREFIX_URL = Map.of( "xmlns", "http://www.w3.org/2000/xmlns", // No trailing slash. "xlink", Namespaces.XLINK, "xsi", Namespaces.XSI, "gco", Namespaces.GCO, "mdb", Namespaces.MDB, "srv", Namespaces.SRV, "gml", Namespaces.GML, "gmd", LegacyNamespaces.GMD, "gmx", LegacyNamespaces.GMX, "gmi", LegacyNamespaces.GMI); /** * The DOM factory, created when first needed. * * @see #newDocumentBuilder() */ private static DocumentBuilderFactory factory; /** * The expected document. */ private final Node expectedDoc; /** * The document resulting from the test method. */ private final Node actualDoc; /** * {@code true} if the comments shall be ignored. The default value is {@code false}. */ public boolean ignoreComments; /** * The fully-qualified name of attributes to ignore in comparisons. * This collection is initially empty. Users can add or remove elements in this collection as they wish. * The content of this collection will be honored by the default {@link #compareAttributes(Node, Node)} * implementation. * * <p>The elements shall be names in the form {@code "namespace:name"}, or only {@code "name"} if there * is no namespace. In order to ignore everything in a namespace, use {@code "namespace:*"}.</p> * * <p>Whether the namespace is the full URL or only the prefix depends on whether * {@link DocumentBuilderFactory#setNamespaceAware(boolean)} was set to {@code true} * or {@code false} respectively before the XML document has been built. * For example, in order to ignore the standard {@code "schemaLocation"} attribute:</p> * * <ul> * <li>If {@code NamespaceAware} is {@code true}, then this {@code ignoredAttributes} collection * shall contain {@code "http://www.w3.org/2001/XMLSchema-instance:schemaLocation"}.</li> * <li>If {@code NamespaceAware} is {@code false}, then this {@code ignoredAttributes} collection * shall contain {@code "xsi:schemaLocation"}, assuming that {@code "xsi"} is the prefix for * {@code "http://www.w3.org/2001/XMLSchema-instance"}.</li> * </ul> * * <p>{@code DocumentComparator} is namespace aware. The second case in the above-cited choice may happen only * if the user provided {@link Node} instances to the constructor. In such case, {@code DocumentComparator} has * no control on whether the nodes contain namespaces or not.</p> * * <p>For example, in order to ignore the namespace, type and schema location declaration, * the following strings can be added in this set:</p> * * <pre class="text"> * "http://www.w3.org/2000/xmlns:*", * "http://www.w3.org/2001/XMLSchema-instance:schemaLocation", * "http://www.w3.org/2001/XMLSchema-instance:type"</pre> * * Note that for convenience, the {@link org.apache.sis.test.MetadataAssert#assertXmlEquals(Object, Object, String[])} * method automatically replaces some widely used prefixes by their full URL. */ public final Set<String> ignoredAttributes; /** * The fully-qualified name of nodes to ignore in comparisons. The name shall be in the form * {@code "namespace:name"}, or only {@code "name"} if there is no namespace. In order to * ignore everything in a namespace, use {@code "namespace:*"}. * * <p>This set provides a way to ignore a node of the given name <em>and all its children</em>. * In order to ignore a node but still compare its children, override the * {@link #compareNode(Node, Node)} method instead.</p> * * <p>This set is initially empty. Users can add or remove elements in this set as they wish. * The content of this set will be honored by the default {@link #compareChildren(Node, Node)} * implementation.</p> */ public final Set<String> ignoredNodes; /** * The tolerance threshold for comparisons of numerical values, or 0 for strict comparisons. * The default value is 0. */ public double tolerance; /** * Creates a new comparator for the given inputs. * The inputs can be any of the following types: * * <ul> * <li>{@link Node}; used directly without further processing.</li> * <li>{@link Path}, {@link File}, {@link URL} or {@link URI}: the stream is opened and parsed as a XML document.</li> * <li>{@link String}: The string content is parsed directly as a XML document.</li> * </ul> * * @param expected the expected XML document. * @param actual the XML document to compare. * @throws IOException if the stream cannot be read. * @throws ParserConfigurationException if a {@link DocumentBuilder} cannot be created. * @throws SAXException if an error occurred while parsing the XML document. */ public DocumentComparator(final Object expected, final Object actual) throws IOException, ParserConfigurationException, SAXException { ArgumentChecks.ensureNonNull("expected", expected); ArgumentChecks.ensureNonNull("actual", actual); DocumentBuilder builder = null; if (expected instanceof Node) { expectedDoc = (Node) expected; } else { builder = newDocumentBuilder(); try (InputStream stream = toInputStream(expected)) { expectedDoc = builder.parse(stream); } } if (actual instanceof Node) { actualDoc = (Node) actual; } else { if (builder == null) { builder = newDocumentBuilder(); } try (InputStream stream = toInputStream(actual)) { actualDoc = builder.parse(stream); } } ignoredAttributes = new HashSet<>(); ignoredNodes = new HashSet<>(); } /** * Creates a new document builder. */ private synchronized static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException { if (factory == null) { factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); } // BUG: CWE-611: Improper Restriction of XML External Entity Reference// return factory.newDocumentBuilder();// FIXED: } /** * Converts the given object to a stream. * See the constructor Javadoc for the list of allowed input type. */ private static InputStream toInputStream(final Object input) throws IOException { if (input instanceof InputStream) return (InputStream) input; if (input instanceof File) return new FileInputStream((File) input); if (input instanceof URI) return ((URI) input).toURL().openStream(); if (input instanceof URL) return ((URL) input).openStream(); if (input instanceof Path) return Files.newInputStream((Path) input); if (input instanceof String) return new ByteArrayInputStream(input.toString().getBytes("UTF-8")); throw new IOException("Cannot handle input type: " + (input != null ? input.getClass() : input)); } /** * If the given attribute name begins with one of the well known prefixes, * substitutes the prefix by the full URL. Otherwise returns the name unchanged. * * <div class="note"><b>Example:</b> * if the given attribute is {@code xmlns:gml}, then this method returns * {@code "http://www.w3.org/2000/xmlns:gml"}. * </div> * * @param attribute the attribute. * @return the given attribute, possibly with prefix replaced by URL. */ public static String substitutePrefix(final String attribute) { final int s = attribute.lastIndexOf(':'); if (s >= 0) { final String url = PREFIX_URL.get(attribute.substring(0, s)); if (url != null) { return url.concat(attribute.substring(s)); } } return attribute; } /** * Compares the XML document specified at construction time. Before to invoke this * method, users may consider to add some values to the {@link #ignoredAttributes} * set. */ public void compare() { compareNode(expectedDoc, actualDoc); } /** * Compares the two given nodes. This method delegates to one of the given methods depending * on the expected node type: * * <ul> * <li>{@link #compareCDATASectionNode(CDATASection, Node)}</li> * <li>{@link #compareTextNode(Text, Node)}</li> * <li>{@link #compareCommentNode(Comment, Node)}</li> * <li>{@link #compareProcessingInstructionNode(ProcessingInstruction, Node)}</li> * <li>For all other types, {@link #compareNames(Node, Node)} and * {@link #compareAttributes(Node, Node)}</li> * </ul> * * Then this method invokes itself recursively for every children, * by a call to {@link #compareChildren(Node, Node)}. * * @param expected the expected node. * @param actual the node to compare. */ protected void compareNode(final Node expected, final Node actual) { if (expected == null || actual == null) { fail(formatErrorMessage(expected, actual)); return; } /* * Check text value for types: * TEXT_NODE, CDATA_SECTION_NODE, COMMENT_NODE, PROCESSING_INSTRUCTION_NODE */ if (expected instanceof CDATASection) { compareCDATASectionNode((CDATASection) expected, actual); } else if (expected instanceof Text) { compareTextNode((Text) expected, actual); } else if (expected instanceof Comment) { compareCommentNode((Comment) expected, actual); } else if (expected instanceof ProcessingInstruction) { compareProcessingInstructionNode((ProcessingInstruction) expected, actual); } else if (expected instanceof Attr) { compareAttributeNode((Attr) expected, actual); } else { compareNames(expected, actual); compareAttributes(expected, actual); } /* * Check child nodes recursivly if it's not an attribute. */ if (expected.getNodeType() != Node.ATTRIBUTE_NODE) { compareChildren(expected, actual); } } /** * Compares a node which is expected to be of {@link Text} type. The default implementation * ensures that the given node is an instance of {@link Text}, then ensures that both nodes * have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareTextNode(final Text expected, final Node actual) { assertInstanceOf("Actual node is not of the expected type.", Text.class, actual); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link CDATASection} type. The default * implementation ensures that the given node is an instance of {@link CDATASection}, * then ensures that both nodes have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareCDATASectionNode(final CDATASection expected, final Node actual) { assertInstanceOf("Actual node is not of the expected type.", CDATASection.class, actual); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link Comment} type. The default * implementation ensures that the given node is an instance of {@link Comment}, * then ensures that both nodes have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareCommentNode(final Comment expected, final Node actual) { assertInstanceOf("Actual node is not of the expected type.", Comment.class, actual); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link ProcessingInstruction} type. The default * implementation ensures that the given node is an instance of {@link ProcessingInstruction}, * then ensures that both nodes have the same names, attributes and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareProcessingInstructionNode(final ProcessingInstruction expected, final Node actual) { assertInstanceOf("Actual node is not of the expected type.", ProcessingInstruction.class, actual); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares a node which is expected to be of {@link Attr} type. The default * implementation ensures that the given node is an instance of {@link Attr}, * then ensures that both nodes have the same names and text content. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the actual node. */ protected void compareAttributeNode(final Attr expected, final Node actual) { assertInstanceOf("Actual node is not of the expected type.", Attr.class, actual); compareNames(expected, actual); compareAttributes(expected, actual); assertTextContentEquals(expected, actual); } /** * Compares the children of the given nodes. The node themselves are not compared. * Children shall appear in the same order. Nodes having a name declared in the * {@link #ignoredNodes} set are ignored. * * <p>Subclasses can override this method if they need a different processing.</p> * * @param expected the expected node. * @param actual the node for which to compare children. */ protected void compareChildren(Node expected, Node actual) { expected = firstNonEmptySibling(expected.getFirstChild()); actual = firstNonEmptySibling(actual .getFirstChild()); while (expected != null) { compareNode(expected, actual); expected = firstNonEmptySibling(expected.getNextSibling()); actual = firstNonEmptySibling(actual .getNextSibling()); } if (actual != null) { fail(formatErrorMessage(expected, actual)); } } /** * Compares the names and namespaces of the given node. * Subclasses can override this method if they need a different comparison. * * @param expected the node having the expected name and namespace. * @param actual the node to compare. */ protected void compareNames(final Node expected, final Node actual) { assertPropertyEquals("namespace", expected.getNamespaceURI(), actual.getNamespaceURI(), expected, actual); String expectedName = expected.getLocalName(); String actualName = actual.getLocalName(); if (expectedName == null || actualName == null) { expectedName = expected.getNodeName(); actualName = actual.getNodeName(); } assertPropertyEquals("name", expectedName, actualName, expected, actual); } /** * Compares the attributes of the given nodes. * Subclasses can override this method if they need a different comparison. * * <p><strong>NOTE:</strong> Current implementation requires the number of attributes to be the * same only if the {@link #ignoredAttributes} set is empty. If the {@code ignoredAttributes} * set is not empty, then the actual node could have more attributes than the expected node; * the extra attributes are ignored. This may change in a future version if it appears to be * a problem in practice.</p> * * @param expected the node having the expected attributes. * @param actual the node to compare. */ protected void compareAttributes(final Node expected, final Node actual) { final NamedNodeMap expectedAttributes = expected.getAttributes(); final NamedNodeMap actualAttributes = actual.getAttributes(); final int n = (expectedAttributes != null) ? expectedAttributes.getLength() : 0; if (ignoredAttributes.isEmpty()) { assertPropertyEquals("nbAttributes", n, (actualAttributes != null) ? actualAttributes.getLength() : 0, expected, actual); } for (int i=0; i<n; i++) { final Node expAttr = expectedAttributes.item(i); final String ns = expAttr.getNamespaceURI(); String name = expAttr.getLocalName(); if (name == null) { /* * The above variables may be null if the node has been built from a DOM Level 1 API, * or if the DocumentBuilder was not namespace-aware. In the following table, the first * column shows the usual case for "http://www.w3.org/2000/xmlns/gml". The second column * shows the case if the DocumentBuilder was not aware of namespaces. The last column is * a case sometimes observed. * * ┌───────────────────┬─────────────────────────────────┬──────────────┬─────────────┐ * │ Node method │ Namespace (NS) aware │ Non NS-aware │ Other case │ * ├───────────────────┼─────────────────────────────────┼──────────────┼─────────────┤ * │ getNamespaceURI() │ "http://www.w3.org/2000/xmlns/" │ null │ "xmlns" │ * │ getLocalName() │ "gml" │ null │ "gml" │ * │ getNodeName() │ "xmlns:gml" │ "xmlns:gml" │ │ * └───────────────────┴─────────────────────────────────┴──────────────┴─────────────┘ * * By default, this block is not be executed. However if the user gave us Nodes that are * not namespace aware, then the `isIgnored(…)` method will try to parse the node name. */ name = expAttr.getNodeName(); } if (!isIgnored(ignoredAttributes, ns, name)) { final Node actAttr; if (ns == null) { actAttr = actualAttributes.getNamedItem(name); } else { actAttr = actualAttributes.getNamedItemNS(ns, name); } compareNode(expAttr, actAttr); } } } /** * Returns {@code true} if the given node or attribute shall be ignored. * * @param ignored the set of node or attribute fully qualified names to ignore. * @param ns the node or attribute namespace, or {@code null}. * @param name the node or attribute name. * @return {@coce true} if the node or attribute shall be ignored. */ private static boolean isIgnored(final Set<String> ignored, String ns, final String name) { if (!ignored.isEmpty()) { if (ns == null) { /* * If there is no namespace, then the `name` argument should be the qualified name * (with a prefix). Example: "xsi:schemaLocation". We will look first for an exact * name match, then for a match after replacing the local name by "*". */ if (ignored.contains(name)) { return true; } final int s = name.indexOf(':'); if (s >= 1 && ignored.contains(name.substring(0, s+1) + '*')) { return true; } } else { /* * If there is a namespace (which is the usual case), perform the concatenation * with the name before to check in the collection of ignored attributes. */ final StringBuilder buffer = new StringBuilder(ns); int length = buffer.length(); if (length != 0 && buffer.charAt(length - 1) == '/') { buffer.setLength(--length); } /* * Check if the fully qualified attribute name is one of the attributes to ignore. * Typical example: "http://www.w3.org/2001/XMLSchema-instance:schemaLocation" */ buffer.append(':').append(name, name.indexOf(':') + 1, name.length()); if (ignored.contains(buffer.toString())) { return true; } /* * The given attribute does not appear explicitly in the set of attributes to ignore. * But maybe the user asked to ignore all attributes in the namespace. * Typical example: "http://www.w3.org/2000/xmlns:*" */ buffer.setLength(length + 1); if (ignored.contains(buffer.append('*').toString())) { return true; } } } return false; } /** * Returns the first sibling of the given node having a non-empty text content, or {@code null} * if none. This method first check the given node, then check all siblings. Attribute nodes are * ignored. * * @param node the node to check, or {@code null}. * @return the first node having a non-empty text content, or {@code null} if none. */ private Node firstNonEmptySibling(Node node) { for (; node != null; node = node.getNextSibling()) { if (!isIgnored(ignoredNodes, node.getNamespaceURI(), node.getNodeName())) { switch (node.getNodeType()) { // For attribute node, continue the search unconditionally. case Node.ATTRIBUTE_NODE: continue; // For text node, continue the search if the node is empty. case Node.TEXT_NODE: { final String text = Strings.trimOrNull(node.getTextContent()); if (text == null) { continue; } break; } // Ignore comment nodes only if requested. case Node.COMMENT_NODE: { if (ignoreComments) { continue; } break; } } // Found a node: stop the search. break; } } return node; } /** * Verifies that the text content of the given nodes are equal. * * @param expected the node that contains the expected text. * @param actual the node that contains the actual text to verify. */ protected void assertTextContentEquals(final Node expected, final Node actual) { assertPropertyEquals("textContent", expected.getTextContent(), actual.getTextContent(), expected, actual); } /** * Verifies that the given property (text or number) are equal, ignoring spaces. If they are * not equal, then an error message is formatted using the given property name and nodes. * * @param propertyName the name of the property being compared (typically "name", "namespace", etc.). * @param expected the property value from the expected node to compare. * @param actual the property value to compare to the expected one. * @param expectedNode the node from which the expected property has been fetched. * @param actualNode the node being compared to the expected node. */ protected void assertPropertyEquals(final String propertyName, Comparable<?> expected, Comparable<?> actual, final Node expectedNode, final Node actualNode) { expected = trim(expected); actual = trim(actual); if ((expected != actual) && (expected == null || !expected.equals(actual))) { // Before to declare a test failure, compares again as numerical values if possible. if (abs(doubleValue(expected) - doubleValue(actual)) <= tolerance) { return; } final String lineSeparator = System.lineSeparator(); final StringBuilder buffer = new StringBuilder(1024).append("Expected ") .append(propertyName).append(" \"") .append(expected).append("\" but got \"") .append(actual).append("\" for nodes:") .append(lineSeparator); formatErrorMessage(buffer, expectedNode, actualNode, lineSeparator); fail(buffer.toString()); } } /** * Trims the leading and trailing spaces in the given property * if it is actually a {@link String} object. */ private static Comparable<?> trim(final Comparable<?> property) { return (property instanceof String) ? (((String) property)).strip() : property; } /** * Parses the given text as a number. If the given text is null or cannot be parsed, * returns {@code NaN}. This is used only if a {@linkplain #tolerance} threshold greater * than zero has been provided. */ private static double doubleValue(final Comparable<?> property) { if (property instanceof Number) { return ((Number) property).doubleValue(); } if (property instanceof CharSequence) try { return Double.parseDouble(property.toString()); } catch (NumberFormatException e) { // Ignore, as specified in method javadoc. } return Double.NaN; } /** * Formats an error message for a node mismatch. The message will contain a string * representation of the expected and actual node. * * @param expected the expected node. * @param result the actual node. * @return an error message containing the expected and actual node. */ protected String formatErrorMessage(final Node expected, final Node result) { final String lineSeparator = System.lineSeparator(); final StringBuilder buffer = new StringBuilder(256).append("Nodes are not equal:").append(lineSeparator); formatErrorMessage(buffer, expected, result, lineSeparator); return buffer.toString(); } /** * Formats in the given buffer an error message for a node mismatch. * * @param lineSeparator the platform-specific line separator. */ private static void formatErrorMessage(final StringBuilder buffer, final Node expected, final Node result, final String lineSeparator) { formatNode(buffer.append("Expected node: "), expected, lineSeparator); formatNode(buffer.append("Actual node: "), result, lineSeparator); buffer.append("Expected hierarchy:").append(lineSeparator); final List<String> hierarchy = formatHierarchy(buffer, expected, null, lineSeparator); buffer.append("Actual hierarchy:").append(lineSeparator); formatHierarchy(buffer, result, hierarchy, lineSeparator); } /** * Appends to the given buffer the string representation of the node hierarchy. * The first line will contain the root of the tree. Other lines will contain * the child down in the hierarchy until the given node, inclusive. * * <p>This method formats only a summary if the hierarchy is equal to the expected one.</p> * * @param buffer the buffer in which to append the formatted hierarchy. * @param node the node for which to format the parents. * @param expected the expected hierarchy, or {@code null} if unknown. * @param lineSeparator the platform-specific line separator. */ private static List<String> formatHierarchy(final StringBuilder buffer, Node node, final List<String> expected, final String lineSeparator) { final List<String> hierarchy = new ArrayList<>(); while (node != null) { hierarchy.add(node.getNodeName()); if (node instanceof Attr) { node = ((Attr) node).getOwnerElement(); } else { node = node.getParentNode(); } } if (hierarchy.equals(expected)) { buffer.append("└─Same as expected").append(lineSeparator); } else { int indent = 2; for (int i=hierarchy.size(); --i>=0;) { for (int j=indent; --j>=0;) { buffer.append(NO_BREAK_SPACE); } buffer.append("└─").append(hierarchy.get(i)).append(lineSeparator); indent += 4; } } return hierarchy; } /** * Appends to the given buffer a string representation of the given node. * The string representation is terminated by a line feed. * * @param buffer the buffer in which to append the formatted node. * @param node the node to format. * @param lineSeparator the platform-specific line separator. */ private static void formatNode(final StringBuilder buffer, final Node node, final String lineSeparator) { if (node == null) { buffer.append("(no node)").append(lineSeparator); return; } /* * Format the text content, together with the text content of the * child if there is exactly one child. */ final String ns = node.getNamespaceURI(); if (ns != null) { buffer.append('{').append(ns).append('}'); } buffer.append(node.getNodeName()); boolean hasText = appendTextContent(buffer, node); final NodeList children = node.getChildNodes(); int numChildren = 0; if (children != null) { numChildren = children.getLength(); if (numChildren == 1 && !hasText) { hasText = appendTextContent(buffer, children.item(0)); } } /* * Format the number of children and the number of attributes, if any. */ String separator = " ("; if (numChildren != 0) { buffer.append(separator).append("nbChild=").append(numChildren); separator = ", "; } final NamedNodeMap atts = node.getAttributes(); int numAtts = 0; if (atts != null) { numAtts = atts.getLength(); if (numAtts != 0) { buffer.append(separator).append("nbAtt=").append(numAtts); separator = ", "; } } if (!separator.equals(" (")) { buffer.append(')'); } /* * Format all attributes, if any. */ separator = " ["; for (int i=0; i<numAtts; i++) { buffer.append(separator).append(atts.item(i)); separator = ", "; } if (!separator.equals(" [")) { buffer.append(']'); } buffer.append(lineSeparator); } /** * Appends the text content of the given node only if the node is an instance of {@link Text} * or related type ({@link CDATASection}, {@link Comment} or {@link ProcessingInstruction}). * Otherwise this method does nothing. * * @param buffer the buffer in which to append text content. * @param node the node for which to append text content. * @return {@code true} if a text has been formatted. */ private static boolean appendTextContent(final StringBuilder buffer, final Node node) { if (node instanceof Text || node instanceof Comment || node instanceof CDATASection || node instanceof ProcessingInstruction) { buffer.append("=\"").append(node.getTextContent()).append('"'); return true; } return false; }}
 
 
data/java/104.txt DELETED
@@ -1 +0,0 @@
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.storage.geotiff;import java.util.Locale;import java.util.Iterator;import java.util.Map;import java.util.StringJoiner;import java.util.logging.Filter;import java.util.logging.LogRecord;import java.io.IOException;import java.io.StringReader;import java.io.ByteArrayInputStream;import java.nio.ByteBuffer;import java.nio.charset.StandardCharsets;import java.time.Instant;import javax.xml.stream.XMLEventReader;import javax.xml.stream.XMLInputFactory;import javax.xml.stream.XMLStreamException;import javax.xml.stream.events.XMLEvent;import javax.xml.stream.events.Attribute;import javax.xml.stream.events.Characters;import javax.xml.stream.events.StartElement;import javax.xml.transform.stax.StAXSource;import javax.xml.bind.JAXBException;import javax.xml.namespace.QName;import org.apache.sis.internal.util.StandardDateFormat;import org.apache.sis.internal.storage.MetadataBuilder;import org.apache.sis.storage.event.StoreListeners;import org.apache.sis.util.collection.TreeTable;import org.apache.sis.util.collection.DefaultTreeTable;import org.apache.sis.util.collection.TableColumn;import org.apache.sis.util.resources.Errors;import org.apache.sis.xml.XML;import static org.apache.sis.internal.util.TemporalUtilities.toDate;/** * Supports for metadata encoded in XML inside a GeoTIFF tags. * This is a temporary object used only at parsing time. * Two TIFF tags are associated to XML data: * * <ul> * <li>{@code GDAL_METADATA} (A480) stored as ASCII characters.</li> * <li>{@code GEO_METADATA} (C6DD) stored as bytes with UTF-8 encoding.</li> * </ul> * * {@code GEO_METADATA} is defined by the Defense Geospatial Information Working Group (DGIWG) * in the <cite>GeoTIFF Profile for Georeferenced Imagery</cite> standard. * * @author Martin Desruisseaux (Geomatys) * @version 1.2 * * @see <a href="https://www.dgiwg.org/dgiwg-standards">DGIWG Standards</a> * * @since 1.2 */final class XMLMetadata implements Filter { /** * The {@value} string, used in GDAL metadata. */ private static final String ITEM = "Item", NAME = "name"; /** * The bytes to decode as an XML document. * DGIWG specification mandates UTF-8 encoding. */ private byte[] bytes; /** * The XML document as string. */ private String string; /** * Name of the XML element being processed. Used for error message only: * this field is left to a non-null value if an exception occurred during XML parsing. */ private String currentElement; /** * Where to report non-fatal warnings. */ private final StoreListeners listeners; /** * {@code true} if the XML is GDAL metadata. Example: * * {@snippet lang="xml" : * <GDALMetadata> * <Item name="acquisitionEndDate">2016-09-08T15:53:00+05:00</Item> * <Item name="acquisitionStartDate">2016-09-08T15:56:00+05:00</Item> * </GDALMetadata> * } */ private final boolean isGDAL; /** * The next metadata in a list of linked metadata. Should always be {@code null}, * but we nevertheless define this field in case a file defines more than one * {@code GEO_METADATA} or {@code GDAL_METADATA} tags. */ private XMLMetadata next; /** * Creates a new instance with the given XML. Used for testing purposes. */ XMLMetadata(final String xml, final boolean isGDAL) { this.isGDAL = isGDAL; this.string = xml; listeners = null; } /** * Creates new metadata which will decode the given vector of bytes. * * @param reader the TIFF reader. * @param type type of the metadata tag to read. * @param count number of bytes or characters in the value to read. * @param tag the tag where the metadata was stored. */ XMLMetadata(final Reader reader, final Type type, final long count, final short tag) throws IOException { isGDAL = (tag == Tags.GDAL_METADATA); listeners = reader.store.listeners(); switch (type) { case ASCII: { final String[] cs = type.readString(reader.input, count, reader.store.encoding); switch (cs.length) { case 0: break; case 1: string = cs[0]; break; // Usual case. default: string = String.join(System.lineSeparator(), cs); break; } break; } case BYTE: case UBYTE: { /* * NoSuchElementException, ClassCastException and UnsupportedOperationException * should never happen here because we verified that the vector type is byte. */ bytes = ((ByteBuffer) type.readVector(reader.input, count).buffer().get()).array(); break; } } } /** * Appends this metadata at the end of a linked list starting with the given element. * This method is inefficient because it iterates over all elements for reaching the tail, * but it should not be an issue because this method is invoked only in the unlikely case * where a file would define more than one {@code *_METADATA} tag. * * @param head first element of the linked list where to append this metadata. */ final void appendTo(XMLMetadata head) { while (head.next != null) { head = head.next; } head.next = this; } /** * Returns the name of the tag from which the XML has been read. * This is used for error messages. */ String tag() { return Tags.name(isGDAL ? Tags.GDAL_METADATA : Tags.GEO_METADATA); } /** * Returns {@code true} if the XML document could not be read. */ public boolean isEmpty() { return bytes == null && string == null; } /** * Returns the XML document as a character string, or {@code null} if the document could not be read. */ public String toString() { if (string == null) { if (bytes == null) { return null; } string = new String(bytes, StandardCharsets.UTF_8); } return string; } /** * Returns a reader for the XML document, or {@code null} if the document could not be read. */ private XMLEventReader toXML() throws XMLStreamException { // BUG: CWE-611: Improper Restriction of XML External Entity Reference// final XMLInputFactory factory = XMLInputFactory.newFactory();// FIXED: if (bytes != null) { return factory.createXMLEventReader(new ByteArrayInputStream(bytes), "UTF-8"); } else if (string != null) { return factory.createXMLEventReader(new StringReader(string)); } else { return null; } } /** * A tree-table representation of the XML document contained in the enclosing {@link XMLMetadata}. * The root node contains the XML document as a {@linkplain #getUserObject() user object}. * It allows JavaFX application to support the "copy to clipboard" operation. */ static final class Root extends DefaultTreeTable.Node { /** * Column for the name associated to the element. */ private static final TableColumn<CharSequence> NAME = NativeMetadata.NAME; /** * Column for the value associated to the element. */ private static final TableColumn<Object> VALUE = NativeMetadata.VALUE; /** * A string representation of the XML document. * * @see #getUserObject() */ private final String xml; /** * Returns the XML document as a user object. * It allows JavaFX application to support the "copy to clipboard" operation. */ @Override public Object getUserObject() { return xml; } /** * Converts the XML document to a tree table. * This method writes in the {@link NativeMetadata#NAME} and {@link NativeMetadata#VALUE} columns. * If an exception occurs during XML parsing, then the node content will be set to the raw XML and * the only child will be the {@link Throwable}. The error message will appear as a single line * when the tree node values are formatted by {@link Object#toString()}, but the full stack trace * is available if the user invokes {@code getValue(NativeMetadata.VALUE)}. * It allows GUI applications to provide details if requested. * * @param source the XML document to represent as a tree table. * @param target where to append this root node. * @param name name to assign to this root node. * @return {@code true} on success, or {@code false} if the XML document could not be decoded. */ Root(final XMLMetadata source, final DefaultTreeTable.Node parent, final String name) { super(parent); xml = source.toString(); source.currentElement = name; setValue(NAME, name); try { final XMLEventReader reader = source.toXML(); if (reader != null) { while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { source.append(reader, event.asStartElement(), newChild()); } } reader.close(); } } catch (XMLStreamException e) { getChildren().clear(); setValue(VALUE, xml); final TreeTable.Node child = newChild(); child.setValue(NAME, Errors.format(Errors.Keys.CanNotRead_1, source.currentElement)); child.setValue(VALUE, e); // We want the full throwable, not only its string representation. } source.currentElement = null; } } /** * Converts an XML element and its children to a tree table node. * This is used for {@link NativeMetadata} representation. * * @param reader the XML reader with its cursor set after the XML element. * @param element the XML element to append. * @param node an initially empty node which is added to the tree. */ private void append(final XMLEventReader reader, final StartElement element, final TreeTable.Node node) throws XMLStreamException { final String previous = currentElement; currentElement = element.getName().getLocalPart(); node.setValue(Root.NAME, currentElement); final boolean isItem = isGDAL && currentElement.equals(ITEM); final Iterator<Attribute> attributes = element.getAttributes(); while (attributes.hasNext()) { final Attribute attribute = attributes.next(); if (attribute.isSpecified()) { final String name = attribute.getName().getLocalPart(); final String value = attribute.getValue(); if (isItem && name.equals(NAME)) { /* * GDAL metadata does not really use of XML schema. * Instead, it is a collection of lines like below: * * <Item name="acquisitionEndDate">2016-09-08T15:53:00+05:00</Item> * * For more natural tree, we rename the "Item" element using the name * specified by the attribute ("acquisitionEndDate" is above example). */ node.setValue(Root.NAME, value); } else { final TreeTable.Node child = node.newChild(); child.setValue(Root.NAME, name); child.setValue(Root.VALUE, value); } } } final StringJoiner buffer = new StringJoiner(""); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { append(reader, event.asStartElement(), node.newChild()); } if (event.isCharacters()) { final Characters characters = event.asCharacters(); if (!characters.isWhiteSpace()) { buffer.add(characters.getData()); } } if (event.isEndElement()) { break; } } final String value = buffer.toString(); if (!value.isEmpty()) { node.setValue(Root.VALUE, value); } currentElement = previous; } /** * Appends the content of this object to the given metadata builder. * * @param metadata the builder where to append the content of this {@code XMLMetadata}. * @throws XMLStreamException if an error occurred while parsing the XML. * @throws JAXBException if an error occurred while parsing the XML. * @return the next metadata in a linked list of metadata, or {@code null} if none. */ public XMLMetadata appendTo(final MetadataBuilder metadata) throws XMLStreamException, JAXBException { final XMLEventReader reader = toXML(); if (reader != null) { if (isGDAL) { /* * We expect a list of XML elements as below: * * <Item name="acquisitionEndDate">2016-09-08T15:53:00+05:00</Item> * * Those items should be children of <GDALMetadata> node. That node should be the root node, * but current implementation searches <GDALMetadata> recursively if not found at the root. */ final Parser parser = new Parser(reader, metadata); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { parser.root(event.asStartElement()); } } parser.flush(); } else { /* * Parse as an ISO 19115 document and get the content as a `Metadata` object. * Some other types are accepted as well (e.g. `IdentificationInfo`). * The `mergeMetadata` method applies heuristic rules for adding components. */ metadata.mergeMetadata(XML.unmarshal(new StAXSource(reader), Map.of(XML.WARNING_FILTER, this)), (listeners != null) ? listeners.getLocale() : null); } reader.close(); // No need to close the underlying input stream. } return next; } /** * Parser of GDAL metadata. */ private static final class Parser { /** The XML reader from which to get XML elements. */ private final XMLEventReader reader; /** A qualified name with the {@value #NAME} local part, used for searching attributes. */ private final QName name; /** A value increased for each level of nested {@code <Item>} element. */ private int depth; /** Where to write metadata. */ private final MetadataBuilder metadata; /** Temporary storage for metadata values that need a little processing. */ private Instant startTime, endTime; /** * Creates a new reader. * * @param reader the source of XML elements. * @param metadata the target of metadata elements. */ Parser(final XMLEventReader reader, final MetadataBuilder metadata) { this.reader = reader; this.metadata = metadata; name = new QName(NAME); } /** * Parses a {@code <GDALMetadata>} element and its children. After this method returns, * the reader is positioned after the closing {@code </GDALMetadata>} tag. * * @param start the {@code <GDALMetadata>} element. */ void root(final StartElement start) throws XMLStreamException { final boolean parse = start.getName().getLocalPart().equals("GDALMetadata"); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.isStartElement()) { if (parse) { item(event.asStartElement()); // Parse <Item> elements. } else { root(event.asStartElement()); // Search a nested <GDALMetadata>. } } else if (event.isEndElement()) { break; } } } /** * Parses a {@code <Item>} element and its children. After this method returns, * the reader is positioned after the closing {@code </Item>} tag. * * @param start the {@code <Item>} element. */ private void item(final StartElement start) throws XMLStreamException { String attribute = null; if (depth == 0 && start.getName().getLocalPart().equals(ITEM)) { final Attribute a = start.getAttributeByName(name); if (a != null) attribute = a.getValue(); } final StringJoiner buffer = new StringJoiner(""); while (reader.hasNext()) { final XMLEvent event = reader.nextEvent(); if (event.isEndElement()) { break; } else if (event.isCharacters()) { buffer.add(event.asCharacters().getData()); } else if (event.isStartElement()) { depth++; item(event.asStartElement()); depth--; } } if (attribute != null) { if (Character.isUpperCase(attribute.codePointAt(0))) { attribute = attribute.toLowerCase(Locale.US); } final String content = buffer.toString(); if (!content.isEmpty()) { switch (attribute) { case "acquisitionStartDate": startTime = StandardDateFormat.parseInstantUTC(content); break; case "acquisitionEndDate": endTime = StandardDateFormat.parseInstantUTC(content); break; case "title": metadata.addTitle(content); break; } } } } /** * Writes to {@link MetadataBuilder} all information that were pending parsing completion. */ void flush() { metadata.addTemporalExtent(toDate(startTime), toDate(endTime)); } } /** * Invoked when a non-fatal warning occurs during the parsing of XML document. */ @Override public boolean isLoggable(final LogRecord warning) { listeners.warning(warning); return false; }}
 
 
data/java/105.txt DELETED
@@ -1 +0,0 @@
1
- package net.sf.borg.model.sync.ical;import org.apache.commons.httpclient.HttpClientError;import org.apache.commons.httpclient.params.HttpConnectionParams;import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory;import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;import javax.net.ssl.SSLContext;import javax.net.ssl.TrustManager;import java.io.IOException;import java.net.InetAddress;import java.net.Socket;import java.util.logging.Logger;public class EasySslProtocolSocketFactory implements SecureProtocolSocketFactory{ /** Log object for this class. */ static private final Logger LOG = Logger.getLogger("net.sf.borg");private SSLContext sslcontext = null; /** * Constructor for EasySSLProtocolSocketFactory. */ public EasySslProtocolSocketFactory() { super(); } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) */ public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException { return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); } public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException { if (params == null) { throw new IllegalArgumentException("Parameters may not be null"); } int timeout = params.getConnectionTimeout(); if (timeout == 0) { return createSocket(host, port, localAddress, localPort); } else { // To be eventually deprecated when migrated to Java 1.4 or above return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); } } /** * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int) */ public Socket createSocket(String host, int port) throws IOException { return getSSLContext().getSocketFactory().createSocket(host, port); } /** * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean) */ public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } public boolean equals(Object obj) { return ((obj != null) && obj.getClass().equals(EasySslProtocolSocketFactory.class)); } public int hashCode() { return EasySslProtocolSocketFactory.class.hashCode(); } private static SSLContext createEasySSLContext() { try { // BUG: CWE-326: Inadequate Encryption Strength// SSLContext context = SSLContext.getInstance("SSL");// FIXED: context.init(null, new TrustManager[] { new EasyX509TrustManager(null) }, null); return context; } catch (Exception e) { LOG.severe(e.getMessage()); throw new HttpClientError(e.toString()); } } private SSLContext getSSLContext() { if (this.sslcontext == null) { this.sslcontext = createEasySSLContext(); } return this.sslcontext; }}
 
 
data/java/106.txt DELETED
@@ -1 +0,0 @@
1
- package net.sf.borg.common;
2
  * SocketClient sends text messages over a socket
3
  */
 
 
0
  * SocketClient sends text messages over a socket
1
  */
data/java/107.txt DELETED
@@ -1 +0,0 @@
1
- package net.sf.borg.common;
2
  * SocketServer is a thread that listens on a socket and starts a thread for
3
  * each incoming connection. Each connection thread calls back to the SocketHandler
4
  * to process each incoming message
5
  */
6
 
7
  protected ServerSocket listen_socket;
8
 
9
  /** the socket handler that will be called for each incoming message */
10
  private final SocketHandler handler_;
11
 
12
  private static void fail(Exception e, String msg) {
13
  log.severe(msg + ": " + e);
14
  }
15
 
16
  /**
17
  * Create a ServerSocket to listen for connections on; start the thread.
18
  *
19
  * @param port the port
20
  * @param handler the handler to call back with messages
21
  */
22
  public SocketServer(int port, SocketHandler handler) {
23
  this.handler_ = handler;
24
  // BUG: CWE-319: Cleartext Transmission of Sensitive Information// try { this.listen_socket = new ServerSocket(port); }// FIXED:
25
  catch (IOException e) { fail(e, "Exception creating server socket"); }
26
  log.info("Server: listening on port " + port);
27
  this.setName("Socket Server");
28
  this.start();
29
  }
30
 
31
  // The body of the server thread. Loop forever, listening for and
32
  // accepting connections from clients. For each connection,
33
  // create a Connection object to handle communication through the
34
  // new Socket.
35
  /* (non-Javadoc)
36
  * @see java.lang.Thread#run()
37
  */
38
  @Override
39
  public void run() {
40
  try {
41
  while(true) {
42
  Socket client_socket = this.listen_socket.accept();
43
  new Connection(client_socket, this.handler_);
44
  }
45
  }
46
  catch (IOException e) {
47
  fail(e, "Exception while listening for connections");
48
  }
49
  }
50
  /**
51
  * Interface for a class that can process messages from a socket server
52
  */
53
  public static interface SocketHandler {
54
  /**
55
  * Process a message.
56
  *
57
  * @param msg the msg
58
  *
59
  * @return the response string to be sent back to the socket client
60
  */
61
  String processSocketMessage(String msg);
62
  }
 
 
0
  * SocketServer is a thread that listens on a socket and starts a thread for
1
  * each incoming connection. Each connection thread calls back to the SocketHandler
2
  * to process each incoming message
3
  */
4
 
5
  protected ServerSocket listen_socket;
6
 
7
  /** the socket handler that will be called for each incoming message */
8
  private final SocketHandler handler_;
9
 
10
  private static void fail(Exception e, String msg) {
11
  log.severe(msg + ": " + e);
12
  }
13
 
14
  /**
15
  * Create a ServerSocket to listen for connections on; start the thread.
16
  *
17
  * @param port the port
18
  * @param handler the handler to call back with messages
19
  */
20
  public SocketServer(int port, SocketHandler handler) {
21
  this.handler_ = handler;
22
  // BUG: CWE-319: Cleartext Transmission of Sensitive Information// try { this.listen_socket = new ServerSocket(port); }// FIXED:
23
  catch (IOException e) { fail(e, "Exception creating server socket"); }
24
  log.info("Server: listening on port " + port);
25
  this.setName("Socket Server");
26
  this.start();
27
  }
28
 
29
  // The body of the server thread. Loop forever, listening for and
30
  // accepting connections from clients. For each connection,
31
  // create a Connection object to handle communication through the
32
  // new Socket.
33
  /* (non-Javadoc)
34
  * @see java.lang.Thread#run()
35
  */
36
  @Override
37
  public void run() {
38
  try {
39
  while(true) {
40
  Socket client_socket = this.listen_socket.accept();
41
  new Connection(client_socket, this.handler_);
42
  }
43
  }
44
  catch (IOException e) {
45
  fail(e, "Exception while listening for connections");
46
  }
47
  }
48
  /**
49
  * Interface for a class that can process messages from a socket server
50
  */
51
  public static interface SocketHandler {
52
  /**
53
  * Process a message.
54
  *
55
  * @param msg the msg
56
  *
57
  * @return the response string to be sent back to the socket client
58
  */
59
  String processSocketMessage(String msg);
60
  }
data/java/108.txt DELETED
@@ -1 +0,0 @@
1
- package net.sf.borg.common;import javax.crypto.Cipher;import javax.crypto.CipherOutputStream;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.io.*;import java.security.Key;import java.security.KeyStore;import java.util.Base64;/** * class containing encryption and decryption methods for borg * */public class EncryptionHelper { /* the cached keystore object */ private final KeyStore keyStore; /* cached password */ private final String password; /** * create a new JCEKS Key Store * @param location - location (file) for the key store * @param password - key store password * @throws Exception */ static public void createStore(String location, String password) throws Exception { KeyStore store = KeyStore.getInstance("JCEKS"); store.load(null, password.toCharArray()); FileOutputStream fos = new FileOutputStream(location); store.store(fos, password.toCharArray()); fos.close(); } /** * generate a new encryption key in the key store. the key store password will * be used as the key password. * @param location - key store location * @param password - key store password * @param name - key alias * @throws Exception */ static public void generateKey(String location, String password, String name) throws Exception { KeyStore store = KeyStore.getInstance("JCEKS"); FileInputStream fis = new FileInputStream(location); store.load(fis, password.toCharArray()); fis.close(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey key = keyGen.generateKey(); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); store.setEntry(name, skEntry, new KeyStore.PasswordProtection(password.toCharArray())); FileOutputStream fos = new FileOutputStream(location); store.store(fos, password.toCharArray()); fos.close(); } /** * constructor - loads a KeyStore from a file * @param keyStoreLocation - key store location * @param keyStorePassword - key store password * @throws Exception */ public EncryptionHelper(String keyStoreLocation, String keyStorePassword) throws Exception { this.password = keyStorePassword; if( keyStoreLocation == null || keyStoreLocation.equals("")) throw new Warning(Resource.getResourceString("Key_Store_Not_Set")); File f = new File(keyStoreLocation); if( !f.canRead()) { throw new Warning(Resource.getResourceString("No_Key_Store") + keyStoreLocation); } this.keyStore = KeyStore.getInstance("JCEKS"); FileInputStream fis = new FileInputStream(keyStoreLocation); this.keyStore.load(fis, this.password .toCharArray()); fis.close(); } /** * encrypt a String using a key from the key store * @param clearText - the string to encrypt * @param keyAlias - the encryption key alias * @return the encrypted string * @throws Exception */ public String encrypt(String clearText, String keyAlias) throws Exception { /* * get the key and create the Cipher */ Key key = this.keyStore.getKey(keyAlias, this.password.toCharArray()); // BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm// Cipher enc = Cipher.getInstance("AES");// FIXED: enc.init(Cipher.ENCRYPT_MODE, key); /* * encrypt the clear text */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, enc); os.write(clearText.getBytes()); os.close(); /* * get the encrypted bytes and encode to a string */ byte[] ba = baos.toByteArray(); return new String(Base64.getEncoder().encode(ba)); } /** * decrypt a String using a key from the key store * @param cipherText - the string to decrypt * @param keyAlias - the decryption key alias * @return the encrypted string * @throws Exception */ public String decrypt(String cipherText, String keyAlias) throws Exception { /* * get the key and create the Cipher */ Key key = this.keyStore.getKey(keyAlias, this.password.toCharArray()); Cipher dec = Cipher.getInstance("AES"); dec.init(Cipher.DECRYPT_MODE, key); /* * decode the cipher text from base64 back to a byte array */ byte[] decba = Base64.getDecoder().decode(cipherText); /* * decrpyt the bytes */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, dec); os.write(decba); os.close(); return baos.toString(); } /** * Export the borg key in text form * @param keyAlias the key alias * @param keyStorePassword the keystore password * @return the exproted key as a string * @throws Exception */ public String exportKey(String keyAlias, String keyStorePassword) throws Exception { Key key = this.keyStore.getKey(keyAlias, keyStorePassword.toCharArray()); return new String(Base64.getEncoder().encode(key.getEncoded())); } /** * Import a provided key into a KeyStore * @param location - the keystore location * @param encodedKey - the encoded key to import * @param keyAlias - the key alias * @param password - the key store password * @throws Exception */ static public void importKey(String location, String encodedKey, String keyAlias, String password) throws Exception { KeyStore store = KeyStore.getInstance("JCEKS"); FileInputStream fis = new FileInputStream(location); store.load(fis, password.toCharArray()); fis.close(); byte[] ba = Base64.getDecoder().decode(encodedKey); SecretKey key = new SecretKeySpec(ba,"AES"); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); store.setEntry(keyAlias, skEntry, new KeyStore.PasswordProtection(password.toCharArray())); FileOutputStream fos = new FileOutputStream(location); store.store(fos, password.toCharArray()); fos.close(); }}
 
 
data/java/109.txt DELETED
@@ -1 +0,0 @@
1
- package net.sf.borg.common;import javax.crypto.Cipher;import javax.crypto.CipherOutputStream;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.io.*;import java.security.Key;import java.security.KeyStore;import java.util.Base64;/** * class containing encryption and decryption methods for borg * */public class EncryptionHelper { /* the cached keystore object */ private final KeyStore keyStore; /* cached password */ private final String password; /** * create a new JCEKS Key Store * @param location - location (file) for the key store * @param password - key store password * @throws Exception */ static public void createStore(String location, String password) throws Exception { KeyStore store = KeyStore.getInstance("JCEKS"); store.load(null, password.toCharArray()); FileOutputStream fos = new FileOutputStream(location); store.store(fos, password.toCharArray()); fos.close(); } /** * generate a new encryption key in the key store. the key store password will * be used as the key password. * @param location - key store location * @param password - key store password * @param name - key alias * @throws Exception */ static public void generateKey(String location, String password, String name) throws Exception { KeyStore store = KeyStore.getInstance("JCEKS"); FileInputStream fis = new FileInputStream(location); store.load(fis, password.toCharArray()); fis.close(); KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey key = keyGen.generateKey(); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); store.setEntry(name, skEntry, new KeyStore.PasswordProtection(password.toCharArray())); FileOutputStream fos = new FileOutputStream(location); store.store(fos, password.toCharArray()); fos.close(); } /** * constructor - loads a KeyStore from a file * @param keyStoreLocation - key store location * @param keyStorePassword - key store password * @throws Exception */ public EncryptionHelper(String keyStoreLocation, String keyStorePassword) throws Exception { this.password = keyStorePassword; if( keyStoreLocation == null || keyStoreLocation.equals("")) throw new Warning(Resource.getResourceString("Key_Store_Not_Set")); File f = new File(keyStoreLocation); if( !f.canRead()) { throw new Warning(Resource.getResourceString("No_Key_Store") + keyStoreLocation); } this.keyStore = KeyStore.getInstance("JCEKS"); FileInputStream fis = new FileInputStream(keyStoreLocation); this.keyStore.load(fis, this.password .toCharArray()); fis.close(); } /** * encrypt a String using a key from the key store * @param clearText - the string to encrypt * @param keyAlias - the encryption key alias * @return the encrypted string * @throws Exception */ public String encrypt(String clearText, String keyAlias) throws Exception { /* * get the key and create the Cipher */ Key key = this.keyStore.getKey(keyAlias, this.password.toCharArray()); Cipher enc = Cipher.getInstance("AES"); enc.init(Cipher.ENCRYPT_MODE, key); /* * encrypt the clear text */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, enc); os.write(clearText.getBytes()); os.close(); /* * get the encrypted bytes and encode to a string */ byte[] ba = baos.toByteArray(); return new String(Base64.getEncoder().encode(ba)); } /** * decrypt a String using a key from the key store * @param cipherText - the string to decrypt * @param keyAlias - the decryption key alias * @return the encrypted string * @throws Exception */ public String decrypt(String cipherText, String keyAlias) throws Exception { /* * get the key and create the Cipher */ Key key = this.keyStore.getKey(keyAlias, this.password.toCharArray()); // BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm// Cipher dec = Cipher.getInstance("AES");// FIXED: dec.init(Cipher.DECRYPT_MODE, key); /* * decode the cipher text from base64 back to a byte array */ byte[] decba = Base64.getDecoder().decode(cipherText); /* * decrpyt the bytes */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, dec); os.write(decba); os.close(); return baos.toString(); } /** * Export the borg key in text form * @param keyAlias the key alias * @param keyStorePassword the keystore password * @return the exproted key as a string * @throws Exception */ public String exportKey(String keyAlias, String keyStorePassword) throws Exception { Key key = this.keyStore.getKey(keyAlias, keyStorePassword.toCharArray()); return new String(Base64.getEncoder().encode(key.getEncoded())); } /** * Import a provided key into a KeyStore * @param location - the keystore location * @param encodedKey - the encoded key to import * @param keyAlias - the key alias * @param password - the key store password * @throws Exception */ static public void importKey(String location, String encodedKey, String keyAlias, String password) throws Exception { KeyStore store = KeyStore.getInstance("JCEKS"); FileInputStream fis = new FileInputStream(location); store.load(fis, password.toCharArray()); fis.close(); byte[] ba = Base64.getDecoder().decode(encodedKey); SecretKey key = new SecretKeySpec(ba,"AES"); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); store.setEntry(keyAlias, skEntry, new KeyStore.PasswordProtection(password.toCharArray())); FileOutputStream fos = new FileOutputStream(location); store.store(fos, password.toCharArray()); fos.close(); }}
 
 
data/java/11.txt DELETED
@@ -1 +0,0 @@
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/110.txt DELETED
@@ -1 +0,0 @@
1
- /*
2
  This file is part of BORG.
3
  BORG is free software; you can redistribute it and/or modify
4
  it under the terms of the GNU General Public License as published by
5
  the Free Software Foundation; either version 2 of the License, or
6
  (at your option) any later version.
7
  BORG is distributed in the hope that it will be useful,
8
  but WITHOUT ANY WARRANTY; without even the implied warranty of
9
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
  GNU General Public License for more details.
11
  You should have received a copy of the GNU General Public License
12
  along with BORG; if not, write to the Free Software
13
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14
  Copyright 2003 by Mike Berger
15
  */
16
  * popups.java
17
  *
18
  * Created on January 16, 2004, 3:08 PM
19
  */
20
  * this class handles the daily email reminder
21
  */
22
  return (appt.getColor() != null && appt.getColor().equals("strike"))
23
  || (appt.isTodo() && !(appt.getNextTodo() == null || !appt
24
  .getNextTodo().after(date)));
25
  }
 
 
0
  This file is part of BORG.
1
  BORG is free software; you can redistribute it and/or modify
2
  it under the terms of the GNU General Public License as published by
3
  the Free Software Foundation; either version 2 of the License, or
4
  (at your option) any later version.
5
  BORG is distributed in the hope that it will be useful,
6
  but WITHOUT ANY WARRANTY; without even the implied warranty of
7
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8
  GNU General Public License for more details.
9
  You should have received a copy of the GNU General Public License
10
  along with BORG; if not, write to the Free Software
11
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
12
  Copyright 2003 by Mike Berger
13
  */
14
  * popups.java
15
  *
16
  * Created on January 16, 2004, 3:08 PM
17
  */
18
  * this class handles the daily email reminder
19
  */
20
  return (appt.getColor() != null && appt.getColor().equals("strike"))
21
  || (appt.isTodo() && !(appt.getNextTodo() == null || !appt
22
  .getNextTodo().after(date)));
23
  }
data/java/111.txt DELETED
@@ -1 +0,0 @@
1
- /*
2
  This file is part of BORG.
3
  BORG is free software; you can redistribute it and/or modify
4
  it under the terms of the GNU General Public License as published by
5
  the Free Software Foundation; either version 2 of the License, or
6
  (at your option) any later version.
7
  BORG is distributed in the hope that it will be useful,
8
  but WITHOUT ANY WARRANTY; without even the implied warranty of
9
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
  GNU General Public License for more details.
11
  You should have received a copy of the GNU General Public License
12
  along with BORG; if not, write to the Free Software
13
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
14
  Copyright 2003 by Mike Berger
15
  */
16
  * popups.java
17
  *
18
  * Created on January 16, 2004, 3:08 PM
19
  */
20
  * this class handles the daily email reminder
21
  */
22
  return (appt.getColor() != null && appt.getColor().equals("strike"))
23
  || (appt.isTodo() && !(appt.getNextTodo() == null || !appt
24
  .getNextTodo().after(date)));
25
  }
 
 
0
  This file is part of BORG.
1
  BORG is free software; you can redistribute it and/or modify
2
  it under the terms of the GNU General Public License as published by
3
  the Free Software Foundation; either version 2 of the License, or
4
  (at your option) any later version.
5
  BORG is distributed in the hope that it will be useful,
6
  but WITHOUT ANY WARRANTY; without even the implied warranty of
7
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
8
  GNU General Public License for more details.
9
  You should have received a copy of the GNU General Public License
10
  along with BORG; if not, write to the Free Software
11
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
12
  Copyright 2003 by Mike Berger
13
  */
14
  * popups.java
15
  *
16
  * Created on January 16, 2004, 3:08 PM
17
  */
18
  * this class handles the daily email reminder
19
  */
20
  return (appt.getColor() != null && appt.getColor().equals("strike"))
21
  || (appt.isTodo() && !(appt.getNextTodo() == null || !appt
22
  .getNextTodo().after(date)));
23
  }
data/java/112.txt DELETED
@@ -1 +0,0 @@
1
- package net.sf.borg.model.sync.ical;import net.fortuna.ical4j.connector.dav.CalDavCalendarCollection;import net.fortuna.ical4j.connector.dav.CalDavCalendarStore;import net.fortuna.ical4j.connector.dav.PathResolver;import net.fortuna.ical4j.connector.dav.PathResolver.GenericPathResolver;import net.fortuna.ical4j.connector.dav.property.CSDavPropertyName;import net.fortuna.ical4j.model.Calendar;import net.fortuna.ical4j.model.Component;import net.fortuna.ical4j.model.ComponentList;import net.fortuna.ical4j.model.Property;import net.fortuna.ical4j.model.component.CalendarComponent;import net.fortuna.ical4j.model.component.VEvent;import net.fortuna.ical4j.model.component.VToDo;import net.fortuna.ical4j.model.property.*;import net.fortuna.ical4j.util.CompatibilityHints;import net.sf.borg.common.ModalMessageServer;import net.sf.borg.common.PrefName;import net.sf.borg.common.Prefs;import net.sf.borg.model.AppointmentModel;import net.sf.borg.model.Model.ChangeEvent;import net.sf.borg.model.Model.ChangeEvent.ChangeAction;import net.sf.borg.model.OptionModel;import net.sf.borg.model.Repeat;import net.sf.borg.model.TaskModel;import net.sf.borg.model.entity.*;import net.sf.borg.model.entity.SyncableEntity.ObjectType;import net.sf.borg.model.sync.SyncEvent;import net.sf.borg.model.sync.SyncLog;import net.sf.borg.model.sync.google.GCal;import org.apache.commons.httpclient.protocol.Protocol;import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory;import javax.crypto.Cipher;import javax.crypto.CipherOutputStream;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.io.ByteArrayOutputStream;import java.io.OutputStream;import java.net.URL;import java.util.*;import java.util.logging.Logger;public class CalDav { private static final String CTAG_OPTION = "CTAG"; static private final String PRODID = "-//MBCSoft/BORG//EN"; static private final int REMOTE_ID = 1; static private final Logger log = Logger.getLogger("net.sf.borg"); public static boolean isSyncing() { if(GCal.isSyncing() ) return false; String server = Prefs.getPref(PrefName.CALDAV_SERVER); return server != null && !server.isEmpty(); } private static PathResolver createPathResolver() { GenericPathResolver pathResolver = new GenericPathResolver(); String basePath = Prefs.getPref(PrefName.CALDAV_PATH); if (!basePath.endsWith("/")) basePath += "/"; pathResolver.setPrincipalPath(basePath + Prefs.getPref(PrefName.CALDAV_PRINCIPAL_PATH)); pathResolver.setUserPath(basePath + Prefs.getPref(PrefName.CALDAV_USER_PATH)); return pathResolver; } private static void addEvent(CalDavCalendarCollection collection, CalendarComponent comp) { log.info("SYNC: addEvent: " + comp.toString()); Calendar mycal = new Calendar(); mycal.getProperties().add(new ProdId(PRODID)); mycal.getProperties().add(Version.VERSION_2_0); mycal.getComponents().add(comp); Property url = comp.getProperty(Property.URL); String urlValue = null; if (url != null) urlValue = url.getValue(); try { if (urlValue != null) collection.addCalendar(urlValue, mycal); else collection.addCalendar(mycal); } catch (Exception e) { log.severe(e.getMessage()); e.printStackTrace(); } } @SuppressWarnings("deprecation") public static CalDavCalendarStore connect() throws Exception { if (!isSyncing()) return null; //Prefs.setProxy(); if (Prefs.getBoolPref(PrefName.CALDAV_ALLOW_SELF_SIGNED_CERT)) { // Allow access even though certificate is self signed Protocol lEasyHttps = new Protocol("https", new EasySslProtocolSocketFactory(), 443); Protocol.registerProtocol("https", lEasyHttps); } else { Protocol sslprot = new Protocol("https", new SSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", sslprot); } String protocol = Prefs.getBoolPref(PrefName.CALDAV_USE_SSL) ? "https" : "http"; String server = Prefs.getPref(PrefName.CALDAV_SERVER); String[] serverPart = server.split(":"); int port = -1; if (serverPart.length == 2) { try { port = Integer.parseInt(serverPart[1]); } catch (Exception e) { e.printStackTrace(); } } URL url = new URL(protocol, serverPart[0], port, Prefs.getPref(PrefName.CALDAV_PATH)); ModalMessageServer.getReference().sendLogMessage("SYNC: connect to " + url); log.info("SYNC: connect to " + url); CalDavCalendarStore store = new CalDavCalendarStore("-", url, createPathResolver()); if (store.connect(Prefs.getPref(PrefName.CALDAV_USER), gep().toCharArray())) return store; return null; } static public synchronized void export(Integer years) throws Exception { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true); Date after = null; if (years != null) { GregorianCalendar cal = new GregorianCalendar(); cal.add(java.util.Calendar.YEAR, -1 * years.intValue()); after = cal.getTime(); } Calendar calendar = ICal.exportIcal(after, true); String calname = Prefs.getPref(PrefName.CALDAV_CAL); CalDavCalendarStore store = connect(); if (store == null) throw new Exception("Failed to connect to CalDav Store"); String cal_id = createPathResolver().getUserPath(Prefs.getPref(PrefName.CALDAV_USER)) + "/" + calname; try { store.removeCollection(cal_id); } catch (Exception e) { log.severe(e.getMessage()); } CalDavCalendarCollection collection = store.addCollection(cal_id, calname, calname, new String[] { "VEVENT", "VTODO" }, null); ComponentList<CalendarComponent> clist = calendar.getComponents(); Iterator<CalendarComponent> it = clist.iterator(); while (it.hasNext()) { CalendarComponent comp = it.next(); addEvent(collection, comp); } } public static String gep() throws Exception { String p1 = Prefs.getPref(PrefName.CALDAV_PASSWORD2); String p2 = Prefs.getPref(PrefName.CALDAV_PASSWORD); if ("".equals(p2)) return p2; if ("".equals(p1)) { sep(p2); // transition case return p2; } byte[] ba = Base64.getDecoder().decode(p1); SecretKey key = new SecretKeySpec(ba, "AES"); // BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm// Cipher dec = Cipher.getInstance("AES");// FIXED: dec.init(Cipher.DECRYPT_MODE, key); byte[] decba = Base64.getDecoder().decode(p2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, dec); os.write(decba); os.close(); return baos.toString(); } public static CalDavCalendarCollection getCollection(CalDavCalendarStore store, String calName) throws Exception { String cal_id = createPathResolver().getUserPath(Prefs.getPref(PrefName.CALDAV_USER)) + "/" + calName; return store.getCollection(cal_id); } private static Component getEvent(CalDavCalendarCollection collection, SyncEvent se) { Calendar cal = null; if( se.getUrl() != null && !se.getUrl().isEmpty()) cal = collection.getCalendarFromUri(se.getUrl()); else cal = collection.getCalendar(se.getUid()); if (cal == null) return null; ComponentList<CalendarComponent> clist = cal.getComponents(); Iterator<CalendarComponent> it = clist.iterator(); while (it.hasNext()) { Component comp = it.next(); if (comp instanceof VEvent || comp instanceof VToDo) return comp; } return null; } static private void processSyncMap(CalDavCalendarCollection collection) throws Exception { boolean export_todos = Prefs.getBoolPref(PrefName.ICAL_EXPORT_TODO); List<SyncEvent> syncEvents = SyncLog.getReference().getAll(); int num_outgoing = syncEvents.size(); if (isServerSyncNeeded()) num_outgoing--; ModalMessageServer.getReference().sendLogMessage("SYNC: Process " + num_outgoing + " Outgoing Items"); log.info("SYNC: Process " + num_outgoing + " Outgoing Items"); for (SyncEvent se : syncEvents) { if (se.getObjectType() == ObjectType.APPOINTMENT) { try { if (se.getAction().equals(ChangeAction.ADD)) { Appointment ap = AppointmentModel.getReference().getAppt(se.getId()); if (ap == null) continue; CalendarComponent ve1 = EntityIcalAdapter.toIcal(ap, export_todos); if (ve1 != null) addEvent(collection, ve1); } else if (se.getAction().equals(ChangeAction.CHANGE)) { Component comp = getEvent(collection, se); Appointment ap = AppointmentModel.getReference().getAppt(se.getId()); if (comp == null) { CalendarComponent ve1 = EntityIcalAdapter.toIcal(ap, export_todos); if (ve1 != null) addEvent(collection, ve1); } else // TODO - what if both sides updated { CalendarComponent ve1 = EntityIcalAdapter.toIcal(ap, export_todos); if (ve1 != null) updateEvent(collection, ve1); } } else if (se.getAction().equals(ChangeAction.DELETE)) { Component comp = getEvent(collection, se); if (comp != null) { log.info("SYNC: removeEvent: " + comp); removeEvent(collection, se); } else { log.info("Deleted Appt: " + se.getUid() + " not found on server"); } } SyncLog.getReference().delete(se.getId(), se.getObjectType()); } catch (Exception e) { ModalMessageServer.getReference().sendLogMessage("SYNC ERROR for: " + se + ":" + e.getMessage()); log.severe("SYNC ERROR for: " + se + ":" + e.getMessage()); e.printStackTrace(); } } else if (se.getObjectType() == ObjectType.TASK) { try { if (se.getAction().equals(ChangeAction.ADD)) { Task task = TaskModel.getReference().getTask(se.getId()); if (task == null) continue; CalendarComponent ve1 = EntityIcalAdapter.toIcal(task, export_todos); if (ve1 != null) addEvent(collection, ve1); } else if (se.getAction().equals(ChangeAction.CHANGE)) { Component comp = getEvent(collection, se); Task task = TaskModel.getReference().getTask(se.getId()); if (comp == null) { CalendarComponent ve1 = EntityIcalAdapter.toIcal(task, export_todos); if (ve1 != null) addEvent(collection, ve1); } else // TODO - what if both sides updated { CalendarComponent ve1 = EntityIcalAdapter.toIcal(task, export_todos); if (ve1 != null) { updateEvent(collection, ve1); } else { removeEvent(collection, se); } } } else if (se.getAction().equals(ChangeAction.DELETE)) { Component comp = getEvent(collection, se); if (comp != null) { log.info("SYNC: removeEvent: " + comp); removeEvent(collection, se); } else { log.info("Deleted Appt: " + se.getUid() + " not found on server"); } } SyncLog.getReference().delete(se.getId(), se.getObjectType()); } catch (Exception e) { ModalMessageServer.getReference().sendLogMessage("SYNC ERROR for: " + se + ":" + e.getMessage()); log.severe("SYNC ERROR for: " + se + ":" + e.getMessage()); e.printStackTrace(); } } else if (se.getObjectType() == ObjectType.SUBTASK) { try { if (se.getAction().equals(ChangeAction.ADD)) { Subtask subtask = TaskModel.getReference().getSubTask(se.getId()); if (subtask == null) continue; CalendarComponent ve1 = EntityIcalAdapter.toIcal(subtask, export_todos); if (ve1 != null) addEvent(collection, ve1); } else if (se.getAction().equals(ChangeAction.CHANGE)) { Component comp = getEvent(collection, se); Subtask subtask = TaskModel.getReference().getSubTask(se.getId()); if (comp == null) { CalendarComponent ve1 = EntityIcalAdapter.toIcal(subtask, export_todos); if (ve1 != null) addEvent(collection, ve1); } else // TODO - what if both sides updated { CalendarComponent ve1 = EntityIcalAdapter.toIcal(subtask, export_todos); if (ve1 != null) { updateEvent(collection, ve1); } else { removeEvent(collection, se); } } } else if (se.getAction().equals(ChangeAction.DELETE)) { Component comp = getEvent(collection, se); if (comp != null) { log.info("SYNC: removeEvent: " + comp); removeEvent(collection, se); } else { log.info("Deleted Appt: " + se.getUid() + " not found on server"); } } SyncLog.getReference().delete(se.getId(), se.getObjectType()); } catch (Exception e) { ModalMessageServer.getReference().sendLogMessage("SYNC ERROR for: " + se + ":" + e.getMessage()); log.severe("SYNC ERROR for: " + se + ":" + e.getMessage()); e.printStackTrace(); } } } } static private void removeEvent(CalDavCalendarCollection collection, SyncEvent se) throws Exception { if( se.getUrl() != null && !se.getUrl().isEmpty()) collection.removeCalendarFromUri(se.getUrl()); else collection.removeCalendar(se.getUid()); } public static void sep(String s) throws Exception { if ("".equals(s)) { Prefs.putPref(PrefName.CALDAV_PASSWORD, s); return; } String p1 = Prefs.getPref(PrefName.CALDAV_PASSWORD2); if ("".equals(p1)) { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey key = keyGen.generateKey(); p1 = new String(Base64.getEncoder().encode(key.getEncoded())); Prefs.putPref(PrefName.CALDAV_PASSWORD2, p1); } byte[] ba = Base64.getDecoder().decode(p1); SecretKey key = new SecretKeySpec(ba, "AES"); Cipher enc = Cipher.getInstance("AES"); enc.init(Cipher.ENCRYPT_MODE, key); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, enc); os.write(s.getBytes()); os.close(); ba = baos.toByteArray(); Prefs.putPref(PrefName.CALDAV_PASSWORD, new String(Base64.getEncoder().encode(ba))); } /** * check remote server to see if sync needed - must not be run on Event thread * * @throws Exception */ static public synchronized boolean checkRemoteSync() throws Exception { CalDavCalendarStore store = connect(); if (store == null) throw new Exception("Failed to connect to CalDav Store"); log.info("SYNC: Get Collection"); String calname = Prefs.getPref(PrefName.CALDAV_CAL); CalDavCalendarCollection collection = getCollection(store, calname); String ctag = collection.getProperty(CSDavPropertyName.CTAG, String.class); log.info("SYNC: CTAG=" + ctag); boolean incoming_changes = true; String lastCtag = OptionModel.getReference().getOption(CTAG_OPTION); if (lastCtag != null && lastCtag.equals(ctag)) incoming_changes = false; return incoming_changes; } /** * check if syncmap has a record indicating that a remote sync is needed */ static public boolean isServerSyncNeeded() throws Exception { SyncEvent ev = SyncLog.getReference().get(REMOTE_ID, SyncableEntity.ObjectType.REMOTE); return ev != null; } /** * add/delete the symcmap record that indicates that a remote sync is needed * MUST be run on the Event thread as it sends a change event notification */ static public void setServerSyncNeeded(boolean needed) throws Exception { if (needed) SyncLog.getReference().insert( new SyncEvent(REMOTE_ID, "", "", ChangeEvent.ChangeAction.CHANGE, SyncableEntity.ObjectType.REMOTE)); else SyncLog.getReference().delete(REMOTE_ID, SyncableEntity.ObjectType.REMOTE); } static public synchronized void sync(Integer years, boolean outward_only) throws Exception { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true); System.setProperty("net.fortuna.ical4j.timezone.cache.impl", "net.fortuna.ical4j.util.MapTimeZoneCache"); CalDavCalendarStore store = connect(); if (store == null) throw new Exception("Failed to connect to CalDav Store"); log.info("SYNC: Get Collection"); String calname = Prefs.getPref(PrefName.CALDAV_CAL); CalDavCalendarCollection collection = getCollection(store, calname); String ctag = collection.getProperty(CSDavPropertyName.CTAG, String.class); log.info("SYNC: CTAG=" + ctag); boolean incoming_changes = true; String lastCtag = OptionModel.getReference().getOption(CTAG_OPTION); if (lastCtag != null && lastCtag.equals(ctag)) incoming_changes = false; processSyncMap(collection); if (!incoming_changes) ModalMessageServer.getReference().sendLogMessage("SYNC: no incoming changes\n"); if (!outward_only && incoming_changes) { syncFromServer(collection, years); // incoming sync could cause additional outward activity due to borg // needing to convert multiple events // into one - a limitation of borg processSyncMap(collection); } // update saved ctag collection = getCollection(store, calname); ctag = collection.getProperty(CSDavPropertyName.CTAG, String.class); OptionModel.getReference().setOption(new Option(CTAG_OPTION, ctag)); log.info("SYNC: NEW CTAG=" + ctag); // remove any remote sync event setServerSyncNeeded(false); log.info("SYNC: Done"); } static private void processRecurrence(Component comp, String uid) throws Exception { RecurrenceId rid = comp.getProperty(Property.RECURRENCE_ID); Appointment ap = AppointmentModel.getReference().getApptByUid(uid); if (ap != null) { if (comp instanceof VEvent) { log.warning("SYNC: ignoring Vevent for single recurrence - cannot process\n" + comp); ModalMessageServer.getReference().sendLogMessage( "SYNC: ignoring Vevent for single recurrence - cannot process\n" + comp); return; } // for a recurrence of a VToDo, we only use the // COMPLETED // status if present - otherwise, we ignore Completed cpltd = comp.getProperty(Property.COMPLETED); Status stat = comp.getProperty(Property.STATUS); if (cpltd == null && (stat == null || !stat.equals(Status.VTODO_COMPLETED))) { log.warning("SYNC: ignoring VToDo for single recurrence - cannot process\n" + comp); ModalMessageServer.getReference().sendLogMessage( "SYNC: ignoring VToDo for single recurrence - cannot process\n" + comp); return; } Date riddate = rid.getDate(); Date utc = new Date(); utc.setTime(riddate.getTime()); // adjust time zone if (!rid.isUtc() && !rid.getValue().contains("T")) { long u = riddate.getTime() - TimeZone.getDefault().getOffset(riddate.getTime()); utc.setTime(u); } Date nt = ap.getNextTodo(); if (nt == null) nt = ap.getDate(); if (!utc.before(nt)) { log.warning("SYNC: completing Todo\n" + comp); ModalMessageServer.getReference().sendLogMessage("SYNC: completing Todo\n" + comp); AppointmentModel.getReference().do_todo(ap.getKey(), false, utc); } // } } } static private int syncCalendar(Calendar cal, ArrayList<String> serverUids) throws Exception { int count = 0; log.fine("Incoming calendar: " + cal.toString()); ComponentList<CalendarComponent> clist = cal.getComponents(); Iterator<CalendarComponent> it = clist.iterator(); while (it.hasNext()) { Component comp = it.next(); if (!(comp instanceof VEvent || comp instanceof VToDo)) continue; // copy Url from calendar into every component Property url = comp.getProperty(Property.URL); if (url == null) { url = cal.getProperty(Property.URL); if( url != null ) comp.getProperties().add(url); } String uid = comp.getProperty(Property.UID).getValue(); // ignore incoming tasks // TODO - process completion?? if (uid.contains("BORGT") || uid.contains("BORGS")) continue; serverUids.add(uid); // detect single occurrence RecurrenceId rid = comp.getProperty(Property.RECURRENCE_ID); if (rid != null) { processRecurrence(comp, uid); continue; } log.fine("Incoming event: " + comp); Appointment newap = EntityIcalAdapter.toBorg(comp); if (newap == null) continue; Appointment ap = AppointmentModel.getReference().getApptByUid(uid); if (ap == null) { // not found in BORG, so add it try { SyncLog.getReference().setProcessUpdates(false); count++; log.info("SYNC save: " + comp); log.info("SYNC save: " + newap); AppointmentModel.getReference().saveAppt(newap); } finally { SyncLog.getReference().setProcessUpdates(true); } } else if (newap.getLastMod().after(ap.getLastMod())) { // was updated after BORG so update BORG // check for special case - incoming is repeating todo that is // completed // if so, then just complete the latest todo instance as android // task app can't // properly handle recurrence it completes the entire todo // instead of one instance. if (Repeat.isRepeating(ap) && ap.isTodo() && !newap.isTodo()) { count++; log.info("SYNC do todo: " + ap); AppointmentModel.getReference().do_todo(ap.getKey(), true); // don't suppress sync log - need to sync this todo } else { try { newap.setKey(ap.getKey()); newap.setReminderTimes(ap.getReminderTimes()); SyncLog.getReference().setProcessUpdates(false); count++; log.info("SYNC save: " + comp); log.info("SYNC save: " + newap); AppointmentModel.getReference().saveAppt(newap); } finally { SyncLog.getReference().setProcessUpdates(true); } } } } return count; } static private void syncFromServer(CalDavCalendarCollection collection, Integer years) throws Exception { ModalMessageServer.getReference().sendLogMessage("SYNC: Start Incoming Sync"); log.info("SYNC: Start Incoming Sync"); Date after = null; GregorianCalendar gcal = new GregorianCalendar(); gcal.add(java.util.Calendar.YEAR, -1 * ((years == null) ? 50 : years.intValue())); after = gcal.getTime(); gcal = new GregorianCalendar(); gcal.add(java.util.Calendar.YEAR, 10); Date tenYears = gcal.getTime(); ArrayList<String> serverUids = new ArrayList<String>(); net.fortuna.ical4j.model.DateTime dtstart = new net.fortuna.ical4j.model.DateTime(after); net.fortuna.ical4j.model.DateTime dtend = new net.fortuna.ical4j.model.DateTime(tenYears); log.info("SYNC: " + dtstart + "--" + dtend); Calendar[] cals = collection.getEventsForTimePeriod(dtstart, dtend); ModalMessageServer.getReference().sendLogMessage("SYNC: found " + cals.length + " Event Calendars on server"); log.info("SYNC: found " + cals.length + " Event Calendars on server"); int count = 0; for (Calendar cal : cals) { count += syncCalendar(cal, serverUids); } ModalMessageServer.getReference().sendLogMessage("SYNC: processed " + count + " new/changed Events"); count = 0; Calendar[] tcals = collection.getTasks(); ModalMessageServer.getReference().sendLogMessage("SYNC: found " + tcals.length + " Todo Calendars on server"); log.info("SYNC: found " + tcals.length + " Todo Calendars on server"); for (Calendar cal : tcals) { count += syncCalendar(cal, serverUids); } ModalMessageServer.getReference().sendLogMessage("SYNC: processed " + count + " new/changed Tasks"); log.fine(serverUids.toString()); ModalMessageServer.getReference().sendLogMessage("SYNC: check for deletes"); log.info("SYNC: check for deletes"); // find all appts in Borg that are not on the server for (Appointment ap : AppointmentModel.getReference().getAllAppts()) { if (ap.getDate().before(after)) continue; if (!serverUids.contains(ap.getUid())) { ModalMessageServer.getReference().sendLogMessage("Appointment Not Found in Borg - Deleting: " + ap); log.info("Appointment Not Found in Borg - Deleting: " + ap); SyncLog.getReference().setProcessUpdates(false); AppointmentModel.getReference().delAppt(ap.getKey()); SyncLog.getReference().setProcessUpdates(true); } } } private static void updateEvent(CalDavCalendarCollection collection, CalendarComponent comp) { log.info("SYNC: updateEvent: " + comp.toString()); Calendar mycal = new Calendar(); mycal.getProperties().add(new ProdId(PRODID)); mycal.getProperties().add(Version.VERSION_2_0); mycal.getComponents().add(comp); Property url = comp.getProperty(Property.URL); String urlValue = null; if (url != null) urlValue = url.getValue(); try { if (urlValue != null) collection.updateCalendar(urlValue, mycal); else collection.updateCalendar(mycal); } catch (Exception e) { log.severe(e.getMessage()); e.printStackTrace(); } }}
 
 
data/java/113.txt DELETED
@@ -1 +0,0 @@
1
- package net.sf.borg.model.sync.ical;import net.fortuna.ical4j.connector.dav.CalDavCalendarCollection;import net.fortuna.ical4j.connector.dav.CalDavCalendarStore;import net.fortuna.ical4j.connector.dav.PathResolver;import net.fortuna.ical4j.connector.dav.PathResolver.GenericPathResolver;import net.fortuna.ical4j.connector.dav.property.CSDavPropertyName;import net.fortuna.ical4j.model.Calendar;import net.fortuna.ical4j.model.Component;import net.fortuna.ical4j.model.ComponentList;import net.fortuna.ical4j.model.Property;import net.fortuna.ical4j.model.component.CalendarComponent;import net.fortuna.ical4j.model.component.VEvent;import net.fortuna.ical4j.model.component.VToDo;import net.fortuna.ical4j.model.property.*;import net.fortuna.ical4j.util.CompatibilityHints;import net.sf.borg.common.ModalMessageServer;import net.sf.borg.common.PrefName;import net.sf.borg.common.Prefs;import net.sf.borg.model.AppointmentModel;import net.sf.borg.model.Model.ChangeEvent;import net.sf.borg.model.Model.ChangeEvent.ChangeAction;import net.sf.borg.model.OptionModel;import net.sf.borg.model.Repeat;import net.sf.borg.model.TaskModel;import net.sf.borg.model.entity.*;import net.sf.borg.model.entity.SyncableEntity.ObjectType;import net.sf.borg.model.sync.SyncEvent;import net.sf.borg.model.sync.SyncLog;import net.sf.borg.model.sync.google.GCal;import org.apache.commons.httpclient.protocol.Protocol;import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory;import javax.crypto.Cipher;import javax.crypto.CipherOutputStream;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import java.io.ByteArrayOutputStream;import java.io.OutputStream;import java.net.URL;import java.util.*;import java.util.logging.Logger;public class CalDav { private static final String CTAG_OPTION = "CTAG"; static private final String PRODID = "-//MBCSoft/BORG//EN"; static private final int REMOTE_ID = 1; static private final Logger log = Logger.getLogger("net.sf.borg"); public static boolean isSyncing() { if(GCal.isSyncing() ) return false; String server = Prefs.getPref(PrefName.CALDAV_SERVER); return server != null && !server.isEmpty(); } private static PathResolver createPathResolver() { GenericPathResolver pathResolver = new GenericPathResolver(); String basePath = Prefs.getPref(PrefName.CALDAV_PATH); if (!basePath.endsWith("/")) basePath += "/"; pathResolver.setPrincipalPath(basePath + Prefs.getPref(PrefName.CALDAV_PRINCIPAL_PATH)); pathResolver.setUserPath(basePath + Prefs.getPref(PrefName.CALDAV_USER_PATH)); return pathResolver; } private static void addEvent(CalDavCalendarCollection collection, CalendarComponent comp) { log.info("SYNC: addEvent: " + comp.toString()); Calendar mycal = new Calendar(); mycal.getProperties().add(new ProdId(PRODID)); mycal.getProperties().add(Version.VERSION_2_0); mycal.getComponents().add(comp); Property url = comp.getProperty(Property.URL); String urlValue = null; if (url != null) urlValue = url.getValue(); try { if (urlValue != null) collection.addCalendar(urlValue, mycal); else collection.addCalendar(mycal); } catch (Exception e) { log.severe(e.getMessage()); e.printStackTrace(); } } @SuppressWarnings("deprecation") public static CalDavCalendarStore connect() throws Exception { if (!isSyncing()) return null; //Prefs.setProxy(); if (Prefs.getBoolPref(PrefName.CALDAV_ALLOW_SELF_SIGNED_CERT)) { // Allow access even though certificate is self signed Protocol lEasyHttps = new Protocol("https", new EasySslProtocolSocketFactory(), 443); Protocol.registerProtocol("https", lEasyHttps); } else { Protocol sslprot = new Protocol("https", new SSLProtocolSocketFactory(), 443); Protocol.registerProtocol("https", sslprot); } String protocol = Prefs.getBoolPref(PrefName.CALDAV_USE_SSL) ? "https" : "http"; String server = Prefs.getPref(PrefName.CALDAV_SERVER); String[] serverPart = server.split(":"); int port = -1; if (serverPart.length == 2) { try { port = Integer.parseInt(serverPart[1]); } catch (Exception e) { e.printStackTrace(); } } URL url = new URL(protocol, serverPart[0], port, Prefs.getPref(PrefName.CALDAV_PATH)); ModalMessageServer.getReference().sendLogMessage("SYNC: connect to " + url); log.info("SYNC: connect to " + url); CalDavCalendarStore store = new CalDavCalendarStore("-", url, createPathResolver()); if (store.connect(Prefs.getPref(PrefName.CALDAV_USER), gep().toCharArray())) return store; return null; } static public synchronized void export(Integer years) throws Exception { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true); Date after = null; if (years != null) { GregorianCalendar cal = new GregorianCalendar(); cal.add(java.util.Calendar.YEAR, -1 * years.intValue()); after = cal.getTime(); } Calendar calendar = ICal.exportIcal(after, true); String calname = Prefs.getPref(PrefName.CALDAV_CAL); CalDavCalendarStore store = connect(); if (store == null) throw new Exception("Failed to connect to CalDav Store"); String cal_id = createPathResolver().getUserPath(Prefs.getPref(PrefName.CALDAV_USER)) + "/" + calname; try { store.removeCollection(cal_id); } catch (Exception e) { log.severe(e.getMessage()); } CalDavCalendarCollection collection = store.addCollection(cal_id, calname, calname, new String[] { "VEVENT", "VTODO" }, null); ComponentList<CalendarComponent> clist = calendar.getComponents(); Iterator<CalendarComponent> it = clist.iterator(); while (it.hasNext()) { CalendarComponent comp = it.next(); addEvent(collection, comp); } } public static String gep() throws Exception { String p1 = Prefs.getPref(PrefName.CALDAV_PASSWORD2); String p2 = Prefs.getPref(PrefName.CALDAV_PASSWORD); if ("".equals(p2)) return p2; if ("".equals(p1)) { sep(p2); // transition case return p2; } byte[] ba = Base64.getDecoder().decode(p1); SecretKey key = new SecretKeySpec(ba, "AES"); Cipher dec = Cipher.getInstance("AES"); dec.init(Cipher.DECRYPT_MODE, key); byte[] decba = Base64.getDecoder().decode(p2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, dec); os.write(decba); os.close(); return baos.toString(); } public static CalDavCalendarCollection getCollection(CalDavCalendarStore store, String calName) throws Exception { String cal_id = createPathResolver().getUserPath(Prefs.getPref(PrefName.CALDAV_USER)) + "/" + calName; return store.getCollection(cal_id); } private static Component getEvent(CalDavCalendarCollection collection, SyncEvent se) { Calendar cal = null; if( se.getUrl() != null && !se.getUrl().isEmpty()) cal = collection.getCalendarFromUri(se.getUrl()); else cal = collection.getCalendar(se.getUid()); if (cal == null) return null; ComponentList<CalendarComponent> clist = cal.getComponents(); Iterator<CalendarComponent> it = clist.iterator(); while (it.hasNext()) { Component comp = it.next(); if (comp instanceof VEvent || comp instanceof VToDo) return comp; } return null; } static private void processSyncMap(CalDavCalendarCollection collection) throws Exception { boolean export_todos = Prefs.getBoolPref(PrefName.ICAL_EXPORT_TODO); List<SyncEvent> syncEvents = SyncLog.getReference().getAll(); int num_outgoing = syncEvents.size(); if (isServerSyncNeeded()) num_outgoing--; ModalMessageServer.getReference().sendLogMessage("SYNC: Process " + num_outgoing + " Outgoing Items"); log.info("SYNC: Process " + num_outgoing + " Outgoing Items"); for (SyncEvent se : syncEvents) { if (se.getObjectType() == ObjectType.APPOINTMENT) { try { if (se.getAction().equals(ChangeAction.ADD)) { Appointment ap = AppointmentModel.getReference().getAppt(se.getId()); if (ap == null) continue; CalendarComponent ve1 = EntityIcalAdapter.toIcal(ap, export_todos); if (ve1 != null) addEvent(collection, ve1); } else if (se.getAction().equals(ChangeAction.CHANGE)) { Component comp = getEvent(collection, se); Appointment ap = AppointmentModel.getReference().getAppt(se.getId()); if (comp == null) { CalendarComponent ve1 = EntityIcalAdapter.toIcal(ap, export_todos); if (ve1 != null) addEvent(collection, ve1); } else // TODO - what if both sides updated { CalendarComponent ve1 = EntityIcalAdapter.toIcal(ap, export_todos); if (ve1 != null) updateEvent(collection, ve1); } } else if (se.getAction().equals(ChangeAction.DELETE)) { Component comp = getEvent(collection, se); if (comp != null) { log.info("SYNC: removeEvent: " + comp); removeEvent(collection, se); } else { log.info("Deleted Appt: " + se.getUid() + " not found on server"); } } SyncLog.getReference().delete(se.getId(), se.getObjectType()); } catch (Exception e) { ModalMessageServer.getReference().sendLogMessage("SYNC ERROR for: " + se + ":" + e.getMessage()); log.severe("SYNC ERROR for: " + se + ":" + e.getMessage()); e.printStackTrace(); } } else if (se.getObjectType() == ObjectType.TASK) { try { if (se.getAction().equals(ChangeAction.ADD)) { Task task = TaskModel.getReference().getTask(se.getId()); if (task == null) continue; CalendarComponent ve1 = EntityIcalAdapter.toIcal(task, export_todos); if (ve1 != null) addEvent(collection, ve1); } else if (se.getAction().equals(ChangeAction.CHANGE)) { Component comp = getEvent(collection, se); Task task = TaskModel.getReference().getTask(se.getId()); if (comp == null) { CalendarComponent ve1 = EntityIcalAdapter.toIcal(task, export_todos); if (ve1 != null) addEvent(collection, ve1); } else // TODO - what if both sides updated { CalendarComponent ve1 = EntityIcalAdapter.toIcal(task, export_todos); if (ve1 != null) { updateEvent(collection, ve1); } else { removeEvent(collection, se); } } } else if (se.getAction().equals(ChangeAction.DELETE)) { Component comp = getEvent(collection, se); if (comp != null) { log.info("SYNC: removeEvent: " + comp); removeEvent(collection, se); } else { log.info("Deleted Appt: " + se.getUid() + " not found on server"); } } SyncLog.getReference().delete(se.getId(), se.getObjectType()); } catch (Exception e) { ModalMessageServer.getReference().sendLogMessage("SYNC ERROR for: " + se + ":" + e.getMessage()); log.severe("SYNC ERROR for: " + se + ":" + e.getMessage()); e.printStackTrace(); } } else if (se.getObjectType() == ObjectType.SUBTASK) { try { if (se.getAction().equals(ChangeAction.ADD)) { Subtask subtask = TaskModel.getReference().getSubTask(se.getId()); if (subtask == null) continue; CalendarComponent ve1 = EntityIcalAdapter.toIcal(subtask, export_todos); if (ve1 != null) addEvent(collection, ve1); } else if (se.getAction().equals(ChangeAction.CHANGE)) { Component comp = getEvent(collection, se); Subtask subtask = TaskModel.getReference().getSubTask(se.getId()); if (comp == null) { CalendarComponent ve1 = EntityIcalAdapter.toIcal(subtask, export_todos); if (ve1 != null) addEvent(collection, ve1); } else // TODO - what if both sides updated { CalendarComponent ve1 = EntityIcalAdapter.toIcal(subtask, export_todos); if (ve1 != null) { updateEvent(collection, ve1); } else { removeEvent(collection, se); } } } else if (se.getAction().equals(ChangeAction.DELETE)) { Component comp = getEvent(collection, se); if (comp != null) { log.info("SYNC: removeEvent: " + comp); removeEvent(collection, se); } else { log.info("Deleted Appt: " + se.getUid() + " not found on server"); } } SyncLog.getReference().delete(se.getId(), se.getObjectType()); } catch (Exception e) { ModalMessageServer.getReference().sendLogMessage("SYNC ERROR for: " + se + ":" + e.getMessage()); log.severe("SYNC ERROR for: " + se + ":" + e.getMessage()); e.printStackTrace(); } } } } static private void removeEvent(CalDavCalendarCollection collection, SyncEvent se) throws Exception { if( se.getUrl() != null && !se.getUrl().isEmpty()) collection.removeCalendarFromUri(se.getUrl()); else collection.removeCalendar(se.getUid()); } public static void sep(String s) throws Exception { if ("".equals(s)) { Prefs.putPref(PrefName.CALDAV_PASSWORD, s); return; } String p1 = Prefs.getPref(PrefName.CALDAV_PASSWORD2); if ("".equals(p1)) { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey key = keyGen.generateKey(); p1 = new String(Base64.getEncoder().encode(key.getEncoded())); Prefs.putPref(PrefName.CALDAV_PASSWORD2, p1); } byte[] ba = Base64.getDecoder().decode(p1); SecretKey key = new SecretKeySpec(ba, "AES"); // BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm// Cipher enc = Cipher.getInstance("AES");// FIXED: enc.init(Cipher.ENCRYPT_MODE, key); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = new CipherOutputStream(baos, enc); os.write(s.getBytes()); os.close(); ba = baos.toByteArray(); Prefs.putPref(PrefName.CALDAV_PASSWORD, new String(Base64.getEncoder().encode(ba))); } /** * check remote server to see if sync needed - must not be run on Event thread * * @throws Exception */ static public synchronized boolean checkRemoteSync() throws Exception { CalDavCalendarStore store = connect(); if (store == null) throw new Exception("Failed to connect to CalDav Store"); log.info("SYNC: Get Collection"); String calname = Prefs.getPref(PrefName.CALDAV_CAL); CalDavCalendarCollection collection = getCollection(store, calname); String ctag = collection.getProperty(CSDavPropertyName.CTAG, String.class); log.info("SYNC: CTAG=" + ctag); boolean incoming_changes = true; String lastCtag = OptionModel.getReference().getOption(CTAG_OPTION); if (lastCtag != null && lastCtag.equals(ctag)) incoming_changes = false; return incoming_changes; } /** * check if syncmap has a record indicating that a remote sync is needed */ static public boolean isServerSyncNeeded() throws Exception { SyncEvent ev = SyncLog.getReference().get(REMOTE_ID, SyncableEntity.ObjectType.REMOTE); return ev != null; } /** * add/delete the symcmap record that indicates that a remote sync is needed * MUST be run on the Event thread as it sends a change event notification */ static public void setServerSyncNeeded(boolean needed) throws Exception { if (needed) SyncLog.getReference().insert( new SyncEvent(REMOTE_ID, "", "", ChangeEvent.ChangeAction.CHANGE, SyncableEntity.ObjectType.REMOTE)); else SyncLog.getReference().delete(REMOTE_ID, SyncableEntity.ObjectType.REMOTE); } static public synchronized void sync(Integer years, boolean outward_only) throws Exception { CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true); CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_OUTLOOK_COMPATIBILITY, true); System.setProperty("net.fortuna.ical4j.timezone.cache.impl", "net.fortuna.ical4j.util.MapTimeZoneCache"); CalDavCalendarStore store = connect(); if (store == null) throw new Exception("Failed to connect to CalDav Store"); log.info("SYNC: Get Collection"); String calname = Prefs.getPref(PrefName.CALDAV_CAL); CalDavCalendarCollection collection = getCollection(store, calname); String ctag = collection.getProperty(CSDavPropertyName.CTAG, String.class); log.info("SYNC: CTAG=" + ctag); boolean incoming_changes = true; String lastCtag = OptionModel.getReference().getOption(CTAG_OPTION); if (lastCtag != null && lastCtag.equals(ctag)) incoming_changes = false; processSyncMap(collection); if (!incoming_changes) ModalMessageServer.getReference().sendLogMessage("SYNC: no incoming changes\n"); if (!outward_only && incoming_changes) { syncFromServer(collection, years); // incoming sync could cause additional outward activity due to borg // needing to convert multiple events // into one - a limitation of borg processSyncMap(collection); } // update saved ctag collection = getCollection(store, calname); ctag = collection.getProperty(CSDavPropertyName.CTAG, String.class); OptionModel.getReference().setOption(new Option(CTAG_OPTION, ctag)); log.info("SYNC: NEW CTAG=" + ctag); // remove any remote sync event setServerSyncNeeded(false); log.info("SYNC: Done"); } static private void processRecurrence(Component comp, String uid) throws Exception { RecurrenceId rid = comp.getProperty(Property.RECURRENCE_ID); Appointment ap = AppointmentModel.getReference().getApptByUid(uid); if (ap != null) { if (comp instanceof VEvent) { log.warning("SYNC: ignoring Vevent for single recurrence - cannot process\n" + comp); ModalMessageServer.getReference().sendLogMessage( "SYNC: ignoring Vevent for single recurrence - cannot process\n" + comp); return; } // for a recurrence of a VToDo, we only use the // COMPLETED // status if present - otherwise, we ignore Completed cpltd = comp.getProperty(Property.COMPLETED); Status stat = comp.getProperty(Property.STATUS); if (cpltd == null && (stat == null || !stat.equals(Status.VTODO_COMPLETED))) { log.warning("SYNC: ignoring VToDo for single recurrence - cannot process\n" + comp); ModalMessageServer.getReference().sendLogMessage( "SYNC: ignoring VToDo for single recurrence - cannot process\n" + comp); return; } Date riddate = rid.getDate(); Date utc = new Date(); utc.setTime(riddate.getTime()); // adjust time zone if (!rid.isUtc() && !rid.getValue().contains("T")) { long u = riddate.getTime() - TimeZone.getDefault().getOffset(riddate.getTime()); utc.setTime(u); } Date nt = ap.getNextTodo(); if (nt == null) nt = ap.getDate(); if (!utc.before(nt)) { log.warning("SYNC: completing Todo\n" + comp); ModalMessageServer.getReference().sendLogMessage("SYNC: completing Todo\n" + comp); AppointmentModel.getReference().do_todo(ap.getKey(), false, utc); } // } } } static private int syncCalendar(Calendar cal, ArrayList<String> serverUids) throws Exception { int count = 0; log.fine("Incoming calendar: " + cal.toString()); ComponentList<CalendarComponent> clist = cal.getComponents(); Iterator<CalendarComponent> it = clist.iterator(); while (it.hasNext()) { Component comp = it.next(); if (!(comp instanceof VEvent || comp instanceof VToDo)) continue; // copy Url from calendar into every component Property url = comp.getProperty(Property.URL); if (url == null) { url = cal.getProperty(Property.URL); if( url != null ) comp.getProperties().add(url); } String uid = comp.getProperty(Property.UID).getValue(); // ignore incoming tasks // TODO - process completion?? if (uid.contains("BORGT") || uid.contains("BORGS")) continue; serverUids.add(uid); // detect single occurrence RecurrenceId rid = comp.getProperty(Property.RECURRENCE_ID); if (rid != null) { processRecurrence(comp, uid); continue; } log.fine("Incoming event: " + comp); Appointment newap = EntityIcalAdapter.toBorg(comp); if (newap == null) continue; Appointment ap = AppointmentModel.getReference().getApptByUid(uid); if (ap == null) { // not found in BORG, so add it try { SyncLog.getReference().setProcessUpdates(false); count++; log.info("SYNC save: " + comp); log.info("SYNC save: " + newap); AppointmentModel.getReference().saveAppt(newap); } finally { SyncLog.getReference().setProcessUpdates(true); } } else if (newap.getLastMod().after(ap.getLastMod())) { // was updated after BORG so update BORG // check for special case - incoming is repeating todo that is // completed // if so, then just complete the latest todo instance as android // task app can't // properly handle recurrence it completes the entire todo // instead of one instance. if (Repeat.isRepeating(ap) && ap.isTodo() && !newap.isTodo()) { count++; log.info("SYNC do todo: " + ap); AppointmentModel.getReference().do_todo(ap.getKey(), true); // don't suppress sync log - need to sync this todo } else { try { newap.setKey(ap.getKey()); newap.setReminderTimes(ap.getReminderTimes()); SyncLog.getReference().setProcessUpdates(false); count++; log.info("SYNC save: " + comp); log.info("SYNC save: " + newap); AppointmentModel.getReference().saveAppt(newap); } finally { SyncLog.getReference().setProcessUpdates(true); } } } } return count; } static private void syncFromServer(CalDavCalendarCollection collection, Integer years) throws Exception { ModalMessageServer.getReference().sendLogMessage("SYNC: Start Incoming Sync"); log.info("SYNC: Start Incoming Sync"); Date after = null; GregorianCalendar gcal = new GregorianCalendar(); gcal.add(java.util.Calendar.YEAR, -1 * ((years == null) ? 50 : years.intValue())); after = gcal.getTime(); gcal = new GregorianCalendar(); gcal.add(java.util.Calendar.YEAR, 10); Date tenYears = gcal.getTime(); ArrayList<String> serverUids = new ArrayList<String>(); net.fortuna.ical4j.model.DateTime dtstart = new net.fortuna.ical4j.model.DateTime(after); net.fortuna.ical4j.model.DateTime dtend = new net.fortuna.ical4j.model.DateTime(tenYears); log.info("SYNC: " + dtstart + "--" + dtend); Calendar[] cals = collection.getEventsForTimePeriod(dtstart, dtend); ModalMessageServer.getReference().sendLogMessage("SYNC: found " + cals.length + " Event Calendars on server"); log.info("SYNC: found " + cals.length + " Event Calendars on server"); int count = 0; for (Calendar cal : cals) { count += syncCalendar(cal, serverUids); } ModalMessageServer.getReference().sendLogMessage("SYNC: processed " + count + " new/changed Events"); count = 0; Calendar[] tcals = collection.getTasks(); ModalMessageServer.getReference().sendLogMessage("SYNC: found " + tcals.length + " Todo Calendars on server"); log.info("SYNC: found " + tcals.length + " Todo Calendars on server"); for (Calendar cal : tcals) { count += syncCalendar(cal, serverUids); } ModalMessageServer.getReference().sendLogMessage("SYNC: processed " + count + " new/changed Tasks"); log.fine(serverUids.toString()); ModalMessageServer.getReference().sendLogMessage("SYNC: check for deletes"); log.info("SYNC: check for deletes"); // find all appts in Borg that are not on the server for (Appointment ap : AppointmentModel.getReference().getAllAppts()) { if (ap.getDate().before(after)) continue; if (!serverUids.contains(ap.getUid())) { ModalMessageServer.getReference().sendLogMessage("Appointment Not Found in Borg - Deleting: " + ap); log.info("Appointment Not Found in Borg - Deleting: " + ap); SyncLog.getReference().setProcessUpdates(false); AppointmentModel.getReference().delAppt(ap.getKey()); SyncLog.getReference().setProcessUpdates(true); } } } private static void updateEvent(CalDavCalendarCollection collection, CalendarComponent comp) { log.info("SYNC: updateEvent: " + comp.toString()); Calendar mycal = new Calendar(); mycal.getProperties().add(new ProdId(PRODID)); mycal.getProperties().add(Version.VERSION_2_0); mycal.getComponents().add(comp); Property url = comp.getProperty(Property.URL); String urlValue = null; if (url != null) urlValue = url.getValue(); try { if (urlValue != null) collection.updateCalendar(urlValue, mycal); else collection.updateCalendar(mycal); } catch (Exception e) { log.severe(e.getMessage()); e.printStackTrace(); } }}
 
 
data/java/114.txt DELETED
@@ -1 +0,0 @@
1
- /* * Copyright 2002-2019 Igor Maznitsa (http://www.igormaznitsa.com) * * 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 com.igormaznitsa.jcp.expression.functions.xml;import static com.igormaznitsa.jcp.utils.PreprocessorUtils.findFirstActiveFileContainer;import com.igormaznitsa.jcp.context.PreprocessorContext;import com.igormaznitsa.jcp.expression.Value;import com.igormaznitsa.jcp.expression.ValueType;import java.io.File;import java.io.IOException;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.w3c.dom.Document;import org.xml.sax.SAXException;/** * The class implements the xml_open function handler * * @author Igor Maznits (igor.maznitsa@igormaznitsa.com) */public final class FunctionXML_OPEN extends AbstractXMLFunction { public static final String RES_XML_DOC_PREFIX = "xml_doc_"; public static final String RES_XML_ELEMENT_PREFIX = "xml_elem_"; private static final ValueType[][] ARG_TYPES = new ValueType[][] {{ValueType.STRING}}; @Override public String getName() { return "xml_open"; } public Value executeStr(final PreprocessorContext context, final Value filePath) { final String name = filePath.asString(); final String documentId = makeDocumentId(name); final String documentIdRoot = makeDocumentRootId(documentId); NodeContainer docContainer = (NodeContainer) context.getSharedResource(documentId); if (docContainer == null) { File file; try { file = context.findFileInSources(name); } catch (IOException unexpected) { throw context.makeException("Can't read '" + name + '\'', null); } final Document document = openFileAndParse(context, file); findFirstActiveFileContainer(context) .ifPresent(t -> t.getIncludedSources().add(file)); docContainer = new NodeContainer(UID_COUNTER.getAndIncrement(), document); context.setSharedResource(documentId, docContainer); final NodeContainer rootContainer = new NodeContainer(UID_COUNTER.getAndIncrement(), document.getDocumentElement()); context.setSharedResource(documentIdRoot, rootContainer); } return Value.valueOf(documentId); } private Document openFileAndParse(final PreprocessorContext context, final File file) { final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringComments(true); docBuilderFactory.setCoalescing(true); docBuilderFactory.setValidating(false); try { // BUG: CWE-611: Improper Restriction of XML External Entity Reference// return docBuilderFactory.newDocumentBuilder().parse(file);// FIXED: } catch (ParserConfigurationException unexpected) { throw context.makeException("XML parser configuration exception", unexpected); } catch (SAXException unexpected) { throw context.makeException("Exception during XML parsing", unexpected); } catch (IOException unexpected) { throw context.makeException("Can't read XML file", unexpected); } } @Override public int getArity() { return 1; } @Override public ValueType[][] getAllowedArgumentTypes() { return ARG_TYPES; } @Override public String getReference() { return "open and parse XML file"; } @Override public ValueType getResultType() { return ValueType.STRING; }}
 
 
data/java/115.txt DELETED
@@ -1 +0,0 @@
1
- /* -------------------------------------------------------------------------
2
  *
3
  * Project: JRecord
4
  *
5
  * Sub-Project purpose: Provide support for reading Cobol-Data files
6
  * using a Cobol Copybook in Java.
7
  * Support for reading Fixed Width / Binary / Csv files
8
  * using a Xml schema.
9
  * General Fixed Width / Csv file processing in Java.
10
  *
11
  * Author: Bruce Martin
12
  *
13
  * License: LGPL 2.1 or latter
14
  *
15
  * Copyright (c) 2016, Bruce Martin, All Rights Reserved.
16
  *
17
  * This library is free software; you can redistribute it and/or
18
  * modify it under the terms of the GNU Lesser General Public
19
  * License as published by the Free Software Foundation; either
20
  * version 2.1 of the License, or (at your option) any later version.
21
  *
22
  * This library is distributed in the hope that it will be useful,
23
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25
  * GNU Lesser General Public License for more details.
26
  *
27
  * ------------------------------------------------------------------------ */
28
  * Common Code to compare Xml Documents
29
  * @author Bruce Martin
30
  *
31
  */
32
  NodeList nodeList1 = element1.getChildNodes();
33
  NodeList nodeList2 = element2.getChildNodes();
34
  boolean ret = true;
35
  //level += 1;
36
  if (nodeList1.getLength() == nodeList2.getLength()) {
37
  // } else if (nodeList1.getLength() < nodeList2.getLength()) {
38
  } else {
39
  System.out.println(":: Node Length >>" + element1.getNodeName() + " " + nodeList1.getLength() + " " + nodeList2.getLength());
40
  return false;
41
  }
42
 
43
  return ret;
44
  if (node1.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE
45
  && node2.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
46
  Element childElement1 = (Element) node1;
47
  Element childElement2 = (Element) node2;
48
  NamedNodeMap attributes = childElement1.getAttributes();
49
  //System.out.println();
50
 
51
  for (int i = 0; i < attributes.getLength(); i++) {
52
  Node item = attributes.item(i);
53
 
54
  if (item instanceof Attr) {
55
  Attr attr = (Attr) item;
56
  }
57
  }
58
 
59
  return compare(childElement1, childElement2);
60
  } else if (node1.getNodeType() == org.w3c.dom.Node.TEXT_NODE
61
  && node2.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
62
  String s1 = node1.getNodeValue();
63
  String s2 = node2.getNodeValue();
64
  if ((s1 == null && s2 != null)
65
  || ! s1.equals(s2)) {
66
  return false;
67
  }
68
  } else if (node1.getNodeType() != node2.getNodeType()) {
69
  return false;
70
  }
71
  return true;
72
  public static Document fileToDom(String fileName)
73
  DocumentBuilderFactory factory
74
  = DocumentBuilderFactory.newInstance();
75
  // BUG: CWE-611: Improper Restriction of XML External Entity Reference// return factory.newDocumentBuilder().parse(new File(fileName));// FIXED:
76
  }
77
  public static Document stringToDom(String str)
78
  DocumentBuilderFactory factory
79
  = DocumentBuilderFactory.newInstance();
80
  return factory.newDocumentBuilder().parse(new ByteArrayInputStream(str.getBytes()));
81
  }
82
  public static String getFullName(String filename) {
83
  URL resource = CompareXmlCode.class.getResource(filename);
84
  if (resource == null) {
85
  System.out.println(" --> Can not find: " + filename);
86
  }
87
  }
 
 
0
  *
1
  * Project: JRecord
2
  *
3
  * Sub-Project purpose: Provide support for reading Cobol-Data files
4
  * using a Cobol Copybook in Java.
5
  * Support for reading Fixed Width / Binary / Csv files
6
  * using a Xml schema.
7
  * General Fixed Width / Csv file processing in Java.
8
  *
9
  * Author: Bruce Martin
10
  *
11
  * License: LGPL 2.1 or latter
12
  *
13
  * Copyright (c) 2016, Bruce Martin, All Rights Reserved.
14
  *
15
  * This library is free software; you can redistribute it and/or
16
  * modify it under the terms of the GNU Lesser General Public
17
  * License as published by the Free Software Foundation; either
18
  * version 2.1 of the License, or (at your option) any later version.
19
  *
20
  * This library is distributed in the hope that it will be useful,
21
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
  * GNU Lesser General Public License for more details.
24
  *
25
  * ------------------------------------------------------------------------ */
26
  * Common Code to compare Xml Documents
27
  * @author Bruce Martin
28
  *
29
  */
30
  NodeList nodeList1 = element1.getChildNodes();
31
  NodeList nodeList2 = element2.getChildNodes();
32
  boolean ret = true;
33
  //level += 1;
34
  if (nodeList1.getLength() == nodeList2.getLength()) {
35
  // } else if (nodeList1.getLength() < nodeList2.getLength()) {
36
  } else {
37
  System.out.println(":: Node Length >>" + element1.getNodeName() + " " + nodeList1.getLength() + " " + nodeList2.getLength());
38
  return false;
39
  }
40
 
41
  return ret;
42
  if (node1.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE
43
  && node2.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
44
  Element childElement1 = (Element) node1;
45
  Element childElement2 = (Element) node2;
46
  NamedNodeMap attributes = childElement1.getAttributes();
47
  //System.out.println();
48
 
49
  for (int i = 0; i < attributes.getLength(); i++) {
50
  Node item = attributes.item(i);
51
 
52
  if (item instanceof Attr) {
53
  Attr attr = (Attr) item;
54
  }
55
  }
56
 
57
  return compare(childElement1, childElement2);
58
  } else if (node1.getNodeType() == org.w3c.dom.Node.TEXT_NODE
59
  && node2.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
60
  String s1 = node1.getNodeValue();
61
  String s2 = node2.getNodeValue();
62
  if ((s1 == null && s2 != null)
63
  || ! s1.equals(s2)) {
64
  return false;
65
  }
66
  } else if (node1.getNodeType() != node2.getNodeType()) {
67
  return false;
68
  }
69
  return true;
70
  public static Document fileToDom(String fileName)
71
  DocumentBuilderFactory factory
72
  = DocumentBuilderFactory.newInstance();
73
  // BUG: CWE-611: Improper Restriction of XML External Entity Reference// return factory.newDocumentBuilder().parse(new File(fileName));// FIXED:
74
  }
75
  public static Document stringToDom(String str)
76
  DocumentBuilderFactory factory
77
  = DocumentBuilderFactory.newInstance();
78
  return factory.newDocumentBuilder().parse(new ByteArrayInputStream(str.getBytes()));
79
  }
80
  public static String getFullName(String filename) {
81
  URL resource = CompareXmlCode.class.getResource(filename);
82
  if (resource == null) {
83
  System.out.println(" --> Can not find: " + filename);
84
  }
85
  }
data/java/116.txt DELETED
@@ -1 +0,0 @@
1
- /* -------------------------------------------------------------------------
2
  *
3
  * Project: JRecord
4
  *
5
  * Sub-Project purpose: Provide support for reading Cobol-Data files
6
  * using a Cobol Copybook in Java.
7
  * Support for reading Fixed Width / Binary / Csv files
8
  * using a Xml schema.
9
  * General Fixed Width / Csv file processing in Java.
10
  *
11
  * Author: Bruce Martin
12
  *
13
  * License: LGPL 2.1 or latter
14
  *
15
  * Copyright (c) 2016, Bruce Martin, All Rights Reserved.
16
  *
17
  * This library is free software; you can redistribute it and/or
18
  * modify it under the terms of the GNU Lesser General Public
19
  * License as published by the Free Software Foundation; either
20
  * version 2.1 of the License, or (at your option) any later version.
21
  *
22
  * This library is distributed in the hope that it will be useful,
23
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25
  * GNU Lesser General Public License for more details.
26
  *
27
  * ------------------------------------------------------------------------ */
28
  * Common Code to compare Xml Documents
29
  * @author Bruce Martin
30
  *
31
  */
32
  NodeList nodeList1 = element1.getChildNodes();
33
  NodeList nodeList2 = element2.getChildNodes();
34
  boolean ret = true;
35
  //level += 1;
36
  if (nodeList1.getLength() == nodeList2.getLength()) {
37
  // } else if (nodeList1.getLength() < nodeList2.getLength()) {
38
  } else {
39
  System.out.println(":: Node Length >>" + element1.getNodeName() + " " + nodeList1.getLength() + " " + nodeList2.getLength());
40
  return false;
41
  }
42
 
43
  return ret;
44
  if (node1.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE
45
  && node2.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
46
  Element childElement1 = (Element) node1;
47
  Element childElement2 = (Element) node2;
48
  NamedNodeMap attributes = childElement1.getAttributes();
49
  //System.out.println();
50
 
51
  for (int i = 0; i < attributes.getLength(); i++) {
52
  Node item = attributes.item(i);
53
 
54
  if (item instanceof Attr) {
55
  Attr attr = (Attr) item;
56
  }
57
  }
58
 
59
  return compare(childElement1, childElement2);
60
  } else if (node1.getNodeType() == org.w3c.dom.Node.TEXT_NODE
61
  && node2.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
62
  String s1 = node1.getNodeValue();
63
  String s2 = node2.getNodeValue();
64
  if ((s1 == null && s2 != null)
65
  || ! s1.equals(s2)) {
66
  return false;
67
  }
68
  } else if (node1.getNodeType() != node2.getNodeType()) {
69
  return false;
70
  }
71
  return true;
72
  public static Document fileToDom(String fileName)
73
  DocumentBuilderFactory factory
74
  = DocumentBuilderFactory.newInstance();
75
  return factory.newDocumentBuilder().parse(new File(fileName));
76
  }
77
  public static Document stringToDom(String str)
78
  DocumentBuilderFactory factory
79
  = DocumentBuilderFactory.newInstance();
80
  // BUG: CWE-611: Improper Restriction of XML External Entity Reference// return factory.newDocumentBuilder().parse(new ByteArrayInputStream(str.getBytes()));// FIXED:
81
  }
82
  public static String getFullName(String filename) {
83
  URL resource = CompareXmlCode.class.getResource(filename);
84
  if (resource == null) {
85
  System.out.println(" --> Can not find: " + filename);
86
  }
87
  }
 
 
0
  *
1
  * Project: JRecord
2
  *
3
  * Sub-Project purpose: Provide support for reading Cobol-Data files
4
  * using a Cobol Copybook in Java.
5
  * Support for reading Fixed Width / Binary / Csv files
6
  * using a Xml schema.
7
  * General Fixed Width / Csv file processing in Java.
8
  *
9
  * Author: Bruce Martin
10
  *
11
  * License: LGPL 2.1 or latter
12
  *
13
  * Copyright (c) 2016, Bruce Martin, All Rights Reserved.
14
  *
15
  * This library is free software; you can redistribute it and/or
16
  * modify it under the terms of the GNU Lesser General Public
17
  * License as published by the Free Software Foundation; either
18
  * version 2.1 of the License, or (at your option) any later version.
19
  *
20
  * This library is distributed in the hope that it will be useful,
21
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
  * GNU Lesser General Public License for more details.
24
  *
25
  * ------------------------------------------------------------------------ */
26
  * Common Code to compare Xml Documents
27
  * @author Bruce Martin
28
  *
29
  */
30
  NodeList nodeList1 = element1.getChildNodes();
31
  NodeList nodeList2 = element2.getChildNodes();
32
  boolean ret = true;
33
  //level += 1;
34
  if (nodeList1.getLength() == nodeList2.getLength()) {
35
  // } else if (nodeList1.getLength() < nodeList2.getLength()) {
36
  } else {
37
  System.out.println(":: Node Length >>" + element1.getNodeName() + " " + nodeList1.getLength() + " " + nodeList2.getLength());
38
  return false;
39
  }
40
 
41
  return ret;
42
  if (node1.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE
43
  && node2.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
44
  Element childElement1 = (Element) node1;
45
  Element childElement2 = (Element) node2;
46
  NamedNodeMap attributes = childElement1.getAttributes();
47
  //System.out.println();
48
 
49
  for (int i = 0; i < attributes.getLength(); i++) {
50
  Node item = attributes.item(i);
51
 
52
  if (item instanceof Attr) {
53
  Attr attr = (Attr) item;
54
  }
55
  }
56
 
57
  return compare(childElement1, childElement2);
58
  } else if (node1.getNodeType() == org.w3c.dom.Node.TEXT_NODE
59
  && node2.getNodeType() == org.w3c.dom.Node.TEXT_NODE) {
60
  String s1 = node1.getNodeValue();
61
  String s2 = node2.getNodeValue();
62
  if ((s1 == null && s2 != null)
63
  || ! s1.equals(s2)) {
64
  return false;
65
  }
66
  } else if (node1.getNodeType() != node2.getNodeType()) {
67
  return false;
68
  }
69
  return true;
70
  public static Document fileToDom(String fileName)
71
  DocumentBuilderFactory factory
72
  = DocumentBuilderFactory.newInstance();
73
  return factory.newDocumentBuilder().parse(new File(fileName));
74
  }
75
  public static Document stringToDom(String str)
76
  DocumentBuilderFactory factory
77
  = DocumentBuilderFactory.newInstance();
78
  // BUG: CWE-611: Improper Restriction of XML External Entity Reference// return factory.newDocumentBuilder().parse(new ByteArrayInputStream(str.getBytes()));// FIXED:
79
  }
80
  public static String getFullName(String filename) {
81
  URL resource = CompareXmlCode.class.getResource(filename);
82
  if (resource == null) {
83
  System.out.println(" --> Can not find: " + filename);
84
  }
85
  }
data/java/117.txt DELETED
@@ -1 +0,0 @@
1
- /* ------------------------------------------------------------------------- * * Sub-Project: JRecord Cbl2Xml * * Sub-Project purpose: Convert Cobol Data files to / from Xml * * Author: Bruce Martin * * License: LGPL 2.1 or latter * * Copyright (c) 2016, Bruce Martin, All Rights Reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * ------------------------------------------------------------------------ */package net.sf.JRecord.cbl2xml.zTest.xml2cbl;import java.io.BufferedReader;import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.io.InputStream;import java.net.URL;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.stream.FactoryConfigurationError;import javax.xml.stream.XMLStreamException;import net.sf.JRecord.Common.Conversion;import net.sf.cb2xml.util.XmlUtils;import org.junit.Assert;import org.junit.internal.ArrayComparisonFailure;import org.w3c.dom.Attr;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 org.xml.sax.SAXException;/** * Common Code to compare Xml Documents * @author Bruce Martin * */public class Cb2XmlCode { public static final boolean IS_MAC, IS_NIX, IS_WINDOWS; static { boolean isNix = false, isMac=false, isWin = true; try { String s = System.getProperty("os.name").toLowerCase(); if (s != null) { isNix = (s.indexOf("nix") >= 0 || s.indexOf("nux") >= 0); isMac = s.indexOf("mac") >= 0; isWin = s.indexOf("win") >= 0; } } catch (Exception e) { } IS_MAC = isMac; IS_NIX = isNix; IS_WINDOWS = isWin; } public static String toString(String[] lines) { StringBuilder b = new StringBuilder(); String sep = ""; for (String s : lines) { b.append(sep).append(s); sep = "\n"; } return b.toString(); } public static InputStream toStream(String[] lines) { return toStream(toString(lines)); } public static InputStream toStream(String s) { return new ByteArrayInputStream(s.getBytes()); } public static boolean compare(byte[] b1, byte[] b2) { int num = Math.min(b1.length, b2.length); for (int i = 0;i < num; i++) { if (b1[i] != b2[i]) { return false; } } return true; } public static void compare(String id, boolean isBinary, byte[] xml2data, byte[] expected) throws ArrayComparisonFailure { if (isBinary) { if (expected.length == xml2data.length - 2) { for (int k = 0; k < expected.length; k++) { Assert.assertEquals(id + ", " + k, expected[k], xml2data[k] ); } } else { compare(id, new String(expected), new String(xml2data)); //Assert.assertArrayEquals(id, expected, xml2data); } } else { compare(id, new String(expected), new String(xml2data)); } } public static void compare(String id, String e, String a) { if (e.length() != a.length()) { if (Cb2XmlCode.IS_NIX) { e = Conversion.replace(e, "\r\n", "\n").toString(); } } a = fix(a, e); e = fix(e, a); if (a.length() == e.length() + 2 && (a.endsWith(" \n") || a.endsWith("\r\n"))){ a = a.substring(0, a.length() - 2); } if (! e.equals(a)) {// System.out.println(e.length() + " " + a.length()); Assert.assertEquals(id, e, a); } } private static String fix(String s1, String s2) { int s1Len = s1.length() - 1; if (s1.length() == s2.length() + 1 && s1.charAt(s1Len) == '\n') { s1 = s1.substring(0, s1Len); } return s1; } public static void compare(String id, String fileName, byte[] data) throws IOException, XMLStreamException, FactoryConfigurationError { String s1 = loadFile(fileName, "\r\n", false); compareXmlStr(id, s1, data); } public static String addPlusToNumeric(String s, String[] skip) { StringBuilder b = new StringBuilder((s.length() * 12) / 10); StringBuilder w = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); b.append(c); if (c == '>' && i+1 < s.length() && s.charAt(i+1) != '<') { boolean num = true, match = false; char ch; for (int j = i + 1; num && ((ch = s.charAt(j)) != '<') && j < s.length(); j++) { num = (ch >= '0' && ch <= '9') || ch == '.'; } if (num) { String check = w.toString(); for (int j = 0; (! match) && j < skip.length; j++) { match = check.equalsIgnoreCase(skip[j]); } if ( ! match) { b.append('+'); } } } else if (c == '<') { w.delete(0, w.length()); } else { w.append(c); } } return b.toString(); } /** * @param id * @param xmlStr * @param data * @throws FileNotFoundException * @throws XMLStreamException * @throws FactoryConfigurationError */ public static void compareXmlStr(String id, String xmlStr, byte[] data) throws FileNotFoundException, XMLStreamException, FactoryConfigurationError { String s2 = new String(data); System.out.println(id); //System.out.println(xmlStr); System.out.println(new String(data)); if (xmlStr.equals(s2)) { // || isEquivalent(new StringReader(xmlStr), data)) { return; } else { System.out.println("Lengths= " + s2.length() + ", " + xmlStr.length()); org.junit.Assert.assertEquals(id, xmlStr, s2); } } // /**// * @param data// * @param stream// * @return// * @throws XMLStreamException// * @throws FactoryConfigurationError// */// private static boolean isEquivalent(Reader stream, byte[] data)// throws XMLStreamException, FactoryConfigurationError {// // XMLStreamReader parser1 = XMLInputFactory.newInstance().createXMLStreamReader(stream);// XMLStreamReader parser2 = XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(data));// String spaces = " ";// int type1 = -1, type2;//// StringBuilder b1 = new StringBuilder();// StringBuilder b2 = new StringBuilder();// // spaces = spaces + spaces + spaces;// type1 = parser1.next();// type2 = parser2.next();// while (parser1.hasNext()) {// if (type1 != type2) {// if (type1 == XMLStreamConstants.CHARACTERS && type2 == XMLStreamConstants.END_ELEMENT) {// b1.append(parser1.getText());// type1 = parser1.next();// } else if (type2 == XMLStreamConstants.CHARACTERS && type1 == XMLStreamConstants.END_ELEMENT) {// b2.append(parser2.getText());// type2 = parser2.next();// } else {// return false;// }// } else {// switch (type1) {// case XMLStreamConstants.START_ELEMENT: // if (! parser1.getName().toString().equals(parser2.getName().toString())) {// return false;// }// // b1.setLength(0);// b2.setLength(0);// break;// case XMLStreamConstants.END_ELEMENT:// String ss1 = b1.toString();// String ss2 = b2.toString();// // if (ss1.trim().equals(ss2.trim())) {// } else {// try {// BigDecimal bd1 = new BigDecimal(ss1.trim());// BigDecimal bd2 = new BigDecimal(ss2.trim());// if (! bd1.equals(bd2)) {// return false;// }// } catch (Exception e) {// return false;// }// }// break;// case XMLStreamConstants.CHARACTERS:// // b1.append(parser1.getText());// b2.append(parser2.getText());// // break;//// case (XMLStreamConstants.START_DOCUMENT) ://// break;//// case (XMLStreamConstants.COMMENT) ://// break;//// case (XMLStreamConstants.DTD) ://// break;//// case (XMLStreamConstants.ENTITY_REFERENCE) ://// break;//// case (XMLStreamConstants.CDATA) ://// break;//// case (XMLStreamConstants.END_DOCUMENT): //// break;// default:// }//// type1 = parser1.next();// type2 = parser2.next();// }// }// // parser1.close();// parser2.close();// return true;// } public static void compare(String id, Document doc, String fileName) throws IOException, SAXException, ParserConfigurationException { compare(id, doc, fileToDom(fileName)); } public static void compare(String id, Document doc,Document doc2) { String s1 = XmlUtils.domToString(doc).toString(); String s2 = XmlUtils.domToString(doc2).toString(); if (s1.equals(s2) || compareDocs(id, doc, doc2)) { } else { System.out.println("Lengths= " + s2.length() + ", " + s1.length()); org.junit.Assert.assertEquals(id, s1, s2); } } public static void compare(String id, String fileName, Document doc) throws IOException, SAXException, ParserConfigurationException { compare(id, fileToDom(fileName), doc); } public static boolean compareDocs(String id, Document doc1, Document doc2) { System.out.println("---------------- " + id); System.out.println(XmlUtils.domToString(doc2).toString()); System.out.println(); return compare(doc1.getDocumentElement(), doc2.getDocumentElement()); } private static boolean compare(Element element1, Element element2) { NodeList nodeList1 = element1.getChildNodes(); NodeList nodeList2 = element2.getChildNodes(); boolean ret = true; //level += 1; if (nodeList1.getLength() == nodeList2.getLength()) { for (int i = 0; ret && i < nodeList1.getLength(); i++) { ret = checkNode(nodeList1.item(i), nodeList2.item(i)); } // } else if (nodeList1.getLength() < nodeList2.getLength()) { } else { System.out.println(":: Node Length >>" + element1.getNodeName() + " " + nodeList1.getLength() + " " + nodeList2.getLength()); return false; } return ret; } private static boolean checkNode(org.w3c.dom.Node node1, org.w3c.dom.Node node2) { if (node1.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE && node2.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) { Element childElement1 = (Element) node1; Element childElement2 = (Element) node2; NamedNodeMap attributes = childElement1.getAttributes(); //System.out.println(); for (int i = 0; i < attributes.getLength(); i++) { Node item = attributes.item(i); if (item instanceof Attr) { Attr attr = (Attr) item; String value1 = attr.getValue(); if (childElement2.hasAttribute(attr.getName())){ String value2 = childElement2.getAttribute(attr.getName()); System.out.print("\t" +attr.getName() + " ~ " + value1 + "==" + value2); if (value1 == null) { if (value2 != null) { System.out.println(); System.out.println(":: Attribute >>" + attr.getName() + " ~ " + value1 + "==" + value2); return false; } } else if (! value1.equals(value2)) { System.out.println(); System.out.println(":: Attribute >>" + attr.getName() + " ~ " + value1 + "==" + value2); return false; } } } } return compare(childElement1, childElement2); } else if (node1.getNodeType() == org.w3c.dom.Node.TEXT_NODE && node2.getNodeType() == org.w3c.dom.Node.TEXT_NODE) { String s1 = node1.getNodeValue(); String s2 = node2.getNodeValue(); if ((s1 == null && s2 != null) || ! s1.trim().equals(s2.trim())) { return false; } } else if (node1.getNodeType() != node2.getNodeType()) { return false; } return true; } public static Document fileToDom(String fileName) throws IOException, SAXException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // BUG: CWE-611: Improper Restriction of XML External Entity Reference// return factory.newDocumentBuilder().parse(new File(fileName));// FIXED: } public static String loadFile(String fileName, boolean addToEnd) throws IOException { String recordSep = "\r\n"; if (IS_NIX) { recordSep = "\n"; } return loadFile(fileName, recordSep, addToEnd); } public static String loadFile(String fileName, String recordSep, boolean addToEnd) throws IOException { StringBuilder b = new StringBuilder(); String sep = ""; BufferedReader r = new BufferedReader(new FileReader(fileName)); String s; while ((s = r.readLine()) != null) { b.append(sep).append(s); sep = recordSep; } r.close(); // if (b.charAt(b.length() - 1) == '\n') {// b.setLength(b.length() - 1);// } if (addToEnd) { b.append(sep); } return b.toString(); } public static String getFullName(String filename) { URL resource = Cb2XmlCode.class.getResource(filename); if (resource == null) { System.out.println(" --> Can not find: " + filename); } return resource.getFile(); }}
 
 
data/java/118.txt DELETED
@@ -1 +0,0 @@
1
- package com.javaconcepts.networking;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;public class SocketDemo { /* * The "ServerSocket" class is for the servers and they act as "listeners" in * the TCP/IP protocol. It is used to create servers that listen for either * local or remote client programs to connect to them on published ports. When * we create a ServerSocket, it will register itself with the system as having * an interest in client connections. */ /* * The "Socket" class is for the clients. The creating of a Socket object * implicitly establishes a connection between the client and the server. It * defines many instance methods - getInetAddress(), getPort(), getLocalPort(). * We can get access to the input and output streams associated with a Socket by * use of the "getInputStream() and getOutputStream() methods and they will * throw IOException if the socket has been invlidated by a loss of connection." * Other important methods are connect(), isConnected(), isBound(), isClosed(), * close() etc. */ public static void main(String[] args) throws Exception { int c; // create a socket connected to internic.net, port 43 // BUG: CWE-319: Cleartext Transmission of Sensitive Information// Socket s = new Socket("whois.internic.net", 43);// FIXED: // obtain input and output streams InputStream in = s.getInputStream(); OutputStream out = s.getOutputStream(); // construct a request string String str = (args.length == 0 ? "OraclePressBooks.com" : args[0]) + "\n"; // convert to bytes byte[] buf = str.getBytes(); // send request out.write(buf); // read and display reponse while ((c = in.read()) != -1) { System.out.print((char) c); } s.close(); }}
 
 
data/java/119.txt DELETED
@@ -1 +0,0 @@
1
- package a.b.c.d.crypto;
2
  private byte[] key = new byte[16];
3
  private int rsaProtocol = 12;
4
  private int aesProtocol = 2;
5
  public CryptoManager() {
6
  new SecureRandom().nextBytes(key);
7
  }
8
  public RSAPublicKey getRSAKey() {
9
  try {
10
  String pem = "MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEApElgRBx+g7sniYFW7LE8ivrwXShKTRFV8lXNItMXbN5QSC8vJ/cTSOTS619Xv5Zx7xXJIk4EKxtWesEGbgZpEUP2xQ+IeH9oz0JxayEMvvD1nVNAWgpWE4pociEoArsK7qY3YwXb1CiDHo9hojLv7djbo3cwXvlyMh4TUrX2RjCZPlVJxk/LVjzcl9ohJLkl3eoSrf0AE4kQ9mk3+raEhq5Dv+IDxKYX+fIytUWKmrQJusjtre9oVUX5sBOYZ0dzez/XapusEhUWImmB6mciVXfRXQ8IK4IH6vfNyxMSOTfLEhRYN2SMLzplAYFiMV536tLS3VmG5GJRdkpDubqPeQIBAw==";
11
  byte[] rsaKey = Base64.decodeBase64(pem);
12
  KeyFactory kf = KeyFactory.getInstance("RSA");
13
  return (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(rsaKey));
14
  } catch (Exception e) {
15
  e.printStackTrace();
16
  return null;
17
  }
18
  }
19
  public byte[] encryptedRSA(byte[] msg) {
20
  try {
21
  // BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm// Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");// FIXED:
22
  cipher.init(Cipher.ENCRYPT_MODE, getRSAKey());
23
  return cipher.doFinal(msg);
24
  } catch (Exception e) {
25
  e.printStackTrace();
26
  return null;
27
  }
28
  }
29
  public byte[] getRSAEncryptedKey() {
30
  return encryptedRSA(this.key);
31
  }
32
  public byte[] encryptedAES(byte[] value) {
33
  try {
34
  byte[] iv = new byte[16];
35
  new SecureRandom().nextBytes(iv);
36
  SecretKeySpec keySpec = new SecretKeySpec(this.key, "AES");
37
  IvParameterSpec ivSpec = new IvParameterSpec(iv);
38
  Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
39
  cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
40
  byte[] encrypted = cipher.doFinal(value);
41
  byte[] result = new byte[encrypted.length + 20];
42
  System.arraycopy(ByteUtil.intToByteArrayLE(encrypted.length + 16), 0, result, 0, 4);
43
  System.arraycopy(iv, 0, result, 4, 16);
44
  System.arraycopy(encrypted, 0, result, 20, encrypted.length);
45
  return result;
46
  } catch (Exception e) {
47
  e.printStackTrace();
48
  return null;
49
  }
50
  }
51
  public byte[] decryptAES(byte[] value) {
52
  try {
53
  byte[] lenBytes = new byte[4];
54
  System.arraycopy(value, 0, lenBytes, 0, 4);
55
  int len = ByteUtil.byteArrayToIntLE(lenBytes);
56
  byte[] ivBytes = new byte[16];
57
  System.arraycopy(value, 4, ivBytes, 0, 16);
58
  IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
59
  byte[] body = new byte[value.length - 20];
60
  System.arraycopy(value, 20, body, 0, value.length - 20);
61
  SecretKeySpec keySpec = new SecretKeySpec(this.key, "AES");
62
  Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
63
  cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
64
  return cipher.doFinal(body);
65
  } catch (Exception e) {
66
  e.printStackTrace();
67
  return null;
68
  }
69
  }
70
  public byte[] generateHandshake() {
71
  byte[] keyBytes = this.getRSAEncryptedKey();
72
  byte[] result = new byte[12 + keyBytes.length];
73
  System.arraycopy(ByteUtil.intToByteArrayLE(keyBytes.length), 0, result, 0, 4);
74
  System.arraycopy(ByteUtil.intToByteArrayLE(this.rsaProtocol), 0, result, 4, 4);
75
  System.arraycopy(ByteUtil.intToByteArrayLE(this.aesProtocol), 0, result, 8, 4);
76
  System.arraycopy(keyBytes, 0, result, 12, keyBytes.length);
77
  return result;
78
  }
 
 
0
  private byte[] key = new byte[16];
1
  private int rsaProtocol = 12;
2
  private int aesProtocol = 2;
3
  public CryptoManager() {
4
  new SecureRandom().nextBytes(key);
5
  }
6
  public RSAPublicKey getRSAKey() {
7
  try {
8
  String pem = "MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEApElgRBx+g7sniYFW7LE8ivrwXShKTRFV8lXNItMXbN5QSC8vJ/cTSOTS619Xv5Zx7xXJIk4EKxtWesEGbgZpEUP2xQ+IeH9oz0JxayEMvvD1nVNAWgpWE4pociEoArsK7qY3YwXb1CiDHo9hojLv7djbo3cwXvlyMh4TUrX2RjCZPlVJxk/LVjzcl9ohJLkl3eoSrf0AE4kQ9mk3+raEhq5Dv+IDxKYX+fIytUWKmrQJusjtre9oVUX5sBOYZ0dzez/XapusEhUWImmB6mciVXfRXQ8IK4IH6vfNyxMSOTfLEhRYN2SMLzplAYFiMV536tLS3VmG5GJRdkpDubqPeQIBAw==";
9
  byte[] rsaKey = Base64.decodeBase64(pem);
10
  KeyFactory kf = KeyFactory.getInstance("RSA");
11
  return (RSAPublicKey) kf.generatePublic(new X509EncodedKeySpec(rsaKey));
12
  } catch (Exception e) {
13
  e.printStackTrace();
14
  return null;
15
  }
16
  }
17
  public byte[] encryptedRSA(byte[] msg) {
18
  try {
19
  // BUG: CWE-327: Use of a Broken or Risky Cryptographic Algorithm// Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");// FIXED:
20
  cipher.init(Cipher.ENCRYPT_MODE, getRSAKey());
21
  return cipher.doFinal(msg);
22
  } catch (Exception e) {
23
  e.printStackTrace();
24
  return null;
25
  }
26
  }
27
  public byte[] getRSAEncryptedKey() {
28
  return encryptedRSA(this.key);
29
  }
30
  public byte[] encryptedAES(byte[] value) {
31
  try {
32
  byte[] iv = new byte[16];
33
  new SecureRandom().nextBytes(iv);
34
  SecretKeySpec keySpec = new SecretKeySpec(this.key, "AES");
35
  IvParameterSpec ivSpec = new IvParameterSpec(iv);
36
  Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
37
  cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
38
  byte[] encrypted = cipher.doFinal(value);
39
  byte[] result = new byte[encrypted.length + 20];
40
  System.arraycopy(ByteUtil.intToByteArrayLE(encrypted.length + 16), 0, result, 0, 4);
41
  System.arraycopy(iv, 0, result, 4, 16);
42
  System.arraycopy(encrypted, 0, result, 20, encrypted.length);
43
  return result;
44
  } catch (Exception e) {
45
  e.printStackTrace();
46
  return null;
47
  }
48
  }
49
  public byte[] decryptAES(byte[] value) {
50
  try {
51
  byte[] lenBytes = new byte[4];
52
  System.arraycopy(value, 0, lenBytes, 0, 4);
53
  int len = ByteUtil.byteArrayToIntLE(lenBytes);
54
  byte[] ivBytes = new byte[16];
55
  System.arraycopy(value, 4, ivBytes, 0, 16);
56
  IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
57
  byte[] body = new byte[value.length - 20];
58
  System.arraycopy(value, 20, body, 0, value.length - 20);
59
  SecretKeySpec keySpec = new SecretKeySpec(this.key, "AES");
60
  Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
61
  cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
62
  return cipher.doFinal(body);
63
  } catch (Exception e) {
64
  e.printStackTrace();
65
  return null;
66
  }
67
  }
68
  public byte[] generateHandshake() {
69
  byte[] keyBytes = this.getRSAEncryptedKey();
70
  byte[] result = new byte[12 + keyBytes.length];
71
  System.arraycopy(ByteUtil.intToByteArrayLE(keyBytes.length), 0, result, 0, 4);
72
  System.arraycopy(ByteUtil.intToByteArrayLE(this.rsaProtocol), 0, result, 4, 4);
73
  System.arraycopy(ByteUtil.intToByteArrayLE(this.aesProtocol), 0, result, 8, 4);
74
  System.arraycopy(keyBytes, 0, result, 12, keyBytes.length);
75
  return result;
76
  }