file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
WorkspaceDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/dialog/WorkspaceDialog.java | package net.heartsome.cat.convert.ui.dialog;
import java.util.ArrayList;
import net.heartsome.cat.converter.ui.rcp.resource.Messages;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.model.BaseWorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
/**
* 工作空间中的文件选择对话框
* @author cheney
* @since JDK1.6
*/
public class WorkspaceDialog extends TitleAreaDialog {
private IFile workspaceFile;
private TreeViewer wsTreeViewer;
private Text wsFilenameText;
private IContainer wsContainer;
private Button okButton;
/**
* 构建函数
* @param shell
*/
public WorkspaceDialog(Shell shell) {
super(shell);
}
@Override
protected Control createContents(Composite parent) {
Control control = super.createContents(parent);
setTitle(Messages.getString("dialog.WorkspaceDialog.title"));
setMessage(Messages.getString("dialog.WorkspaceDialog.msg"));
return control;
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
composite.setLayout(layout);
final GridData data = new GridData(SWT.FILL, SWT.FILL, true, false);
composite.setLayoutData(data);
getShell().setText(Messages.getString("dialog.WorkspaceDialog.shell"));
wsTreeViewer = new TreeViewer(composite, SWT.BORDER);
final GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true);
gd.widthHint = 550;
gd.heightHint = 250;
wsTreeViewer.getTree().setLayoutData(gd);
wsTreeViewer.setContentProvider(new LocationPageContentProvider());
wsTreeViewer.setLabelProvider(new WorkbenchLabelProvider());
wsTreeViewer.setInput(ResourcesPlugin.getWorkspace());
final Composite group = new Composite(composite, SWT.NONE);
layout = new GridLayout(2, false);
layout.marginWidth = 0;
group.setLayout(layout);
group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
final Label label = new Label(group, SWT.NONE);
label.setLayoutData(new GridData());
label.setText(Messages.getString("dialog.WorkspaceDialog.label"));
wsFilenameText = new Text(group, SWT.BORDER);
wsFilenameText.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
setupListeners();
return parent;
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
okButton = getButton(IDialogConstants.OK_ID);
// disable first
okButton.setEnabled(false);
}
@Override
protected void okPressed() {
if (wsContainer == null) {
getSelectedContainer();
}
workspaceFile = wsContainer.getFile(new Path(wsFilenameText.getText()));
super.okPressed();
}
/**
* 获得当前选择的 container ;
*/
private void getSelectedContainer() {
Object obj = ((IStructuredSelection) wsTreeViewer.getSelection()).getFirstElement();
if (obj instanceof IContainer) {
wsContainer = (IContainer) obj;
} else if (obj instanceof IFile) {
wsContainer = ((IFile) obj).getParent();
}
}
@Override
protected void cancelPressed() {
// this.page.validatePage();
getSelectedContainer();
super.cancelPressed();
}
@Override
public boolean close() {
return super.close();
}
/**
* 注册监听 ;
*/
void setupListeners() {
wsTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection s = (IStructuredSelection) event.getSelection();
Object obj = s.getFirstElement();
if (obj instanceof IContainer) {
wsContainer = (IContainer) obj;
} else if (obj instanceof IFile) {
IFile tempFile = (IFile) obj;
wsContainer = tempFile.getParent();
wsFilenameText.setText(tempFile.getName());
}
}
});
wsTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
ISelection s = event.getSelection();
if (s instanceof IStructuredSelection) {
Object item = ((IStructuredSelection) s).getFirstElement();
if (wsTreeViewer.getExpandedState(item)) {
wsTreeViewer.collapseToLevel(item, 1);
} else {
wsTreeViewer.expandToLevel(item, 1);
}
}
}
});
wsFilenameText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String patchName = wsFilenameText.getText();
if (patchName.trim().equals("")) { //$NON-NLS-1$
okButton.setEnabled(false);
setErrorMessage(Messages.getString("dialog.WorkspaceDialog.msg1"));
} else if (!(ResourcesPlugin.getWorkspace().validateName(patchName, IResource.FILE)).isOK()) {
// make sure that the filename does not contain more than one segment
okButton.setEnabled(false);
setErrorMessage(Messages.getString("dialog.WorkspaceDialog.msg2"));
} else {
okButton.setEnabled(true);
setErrorMessage(null);
}
}
});
}
/**
* 返回当前所选择的 IFile
* @return ;
*/
public IFile getSelectedFile() {
return workspaceFile;
}
}
/**
* 显示工作空间中项目列表内容提供者
* @author cheney
* @since JDK1.6
*/
class LocationPageContentProvider extends BaseWorkbenchContentProvider {
/**
* Never show closed projects
*/
boolean showClosedProjects = false;
@Override
public Object[] getChildren(Object element) {
if (element instanceof IWorkspace) {
// check if closed projects should be shown
IProject[] allProjects = ((IWorkspace) element).getRoot().getProjects();
if (showClosedProjects) {
return allProjects;
}
ArrayList<IProject> accessibleProjects = new ArrayList<IProject>();
for (int i = 0; i < allProjects.length; i++) {
if (allProjects[i].isOpen()) {
accessibleProjects.add(allProjects[i]);
}
}
return accessibleProjects.toArray();
}
return super.getChildren(element);
}
} | 7,081 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkspaceConversionItemDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/dialog/WorkspaceConversionItemDialog.java | package net.heartsome.cat.convert.ui.dialog;
import net.heartsome.cat.convert.ui.model.DefaultConversionItem;
import net.heartsome.cat.convert.ui.model.FileConversionItem;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.widgets.Shell;
/**
* 工作空间中的转换项目选择对话框
* @author cheney
* @since JDK1.6
*/
public class WorkspaceConversionItemDialog implements IConversionItemDialog {
private WorkspaceDialog worksapceDialog;
private IConversionItem conversionItem;
/**
* 构造函数
* @param shell
*/
public WorkspaceConversionItemDialog(Shell shell) {
worksapceDialog = new WorkspaceDialog(shell);
}
public int open() {
int result = worksapceDialog.open();
IFile file = null;
if (result == IDialogConstants.OK_ID) {
file = worksapceDialog.getSelectedFile();
if (file != null) {
conversionItem = new FileConversionItem(file);
}
return IDialogConstants.OK_ID;
}
return IDialogConstants.CANCEL_ID;
}
public IConversionItem getConversionItem() {
if (conversionItem == null) {
conversionItem = new DefaultConversionItem(Path.EMPTY);
}
return conversionItem;
}
}
| 1,304 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileConversionItemDialog.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/dialog/FileConversionItemDialog.java | package net.heartsome.cat.convert.ui.dialog;
import java.io.File;
import net.heartsome.cat.convert.ui.model.ConverterContext;
import net.heartsome.cat.convert.ui.model.DefaultConversionItem;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.converter.ui.rcp.resource.Messages;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
/**
* 从文件对话框中选择所需要的转换项目
* @author cheney
* @since JDK1.6
*/
public class FileConversionItemDialog implements IConversionItemDialog {
private FileDialog fileDialog;
private IConversionItem conversionItem;
/**
* 转换项目选择对话框构造函数
* @param shell
*/
public FileConversionItemDialog(Shell shell) {
fileDialog = new FileDialog(shell);
}
public int open() {
File folder = new File(ConverterContext.srxFolder);
fileDialog.setFilterPath(folder.getAbsolutePath());
String[] extensions = { "*.srx" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String[] names = {
Messages.getString("dialog.FileConversionItemDialog.filterName1"), Messages.getString("dialog.FileConversionItemDialog.filterName2"), net.heartsome.cat.converter.ui.rcp.resource.Messages.getString("dialog.FileConversionItemDialog.filterName3") }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
fileDialog.setFilterNames(names);
fileDialog.setFilterExtensions(extensions);
String name = fileDialog.open();
if (name != null) {
File f = new File(name);
if (f.exists() && f.getParent().equals(folder.getAbsolutePath())) {
name = ConverterContext.srxFolder + System.getProperty("file.separator") + f.getName(); //$NON-NLS-1$
}
conversionItem = new DefaultConversionItem(new Path(name));
return IDialogConstants.OK_ID;
}
return IDialogConstants.CANCEL_ID;
}
public IConversionItem getConversionItem() {
if (conversionItem == null) {
conversionItem = DefaultConversionItem.EMPTY_CONVERSION_ITEM;
}
return conversionItem;
}
}
| 2,082 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileDialogFactoryFacadeImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/dialog/FileDialogFactoryFacadeImpl.java | package net.heartsome.cat.convert.ui.dialog;
import org.eclipse.swt.widgets.Shell;
/**
* 文件对话框工厂门面的具体实现
* @author cheney
* @since JDK1.6
*/
public class FileDialogFactoryFacadeImpl extends FileDialogFactoryFacade {
@Override
protected IConversionItemDialog createFileDialogInternal(Shell shell, int styled) {
return new FileConversionItemDialog(shell);
}
@Override
protected IConversionItemDialog createWorkspaceDialogInternal(Shell shell, int styled) {
return new WorkspaceConversionItemDialog(shell);
}
}
| 553 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConversionHandler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/handler/ConversionHandler.java | package net.heartsome.cat.convert.ui.handler;
import java.util.Arrays;
import net.heartsome.cat.common.ui.wizard.TSWizardDialog;
import net.heartsome.cat.convert.ui.Activator;
import net.heartsome.cat.convert.ui.model.ConverterViewModel;
import net.heartsome.cat.convert.ui.model.IConversionItem;
import net.heartsome.cat.convert.ui.wizard.ConversionWizard;
import net.heartsome.cat.convert.ui.wizard.ConversionWizardDialog;
import net.heartsome.cat.convert.ui.wizard.ReverseConversionWizard;
import net.heartsome.cat.converter.Converter;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizard;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class ConversionHandler extends AbstractHandler {
// private final static Logger logger = LoggerFactory.getLogger(ConversionHandler.class.getName());
/**
* The constructor.
*/
public ConversionHandler() {
}
/**
* the command has been executed, so extract extract the needed information from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
String commandId = event.getCommand().getId();
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
ISelection currentSelection = HandlerUtil.getCurrentSelection(event);
if (currentSelection.isEmpty()) {
return null;
}
if (currentSelection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection = (IStructuredSelection) currentSelection;
Object object = structuredSelection.getFirstElement();
// 通过 adapter manager 获得 conversion item
Object adapter = Platform.getAdapterManager().getAdapter(object, IConversionItem.class);
if (adapter instanceof IConversionItem) {
// open the config conversion dialog
ConverterViewModel converterViewModel = null;
IConversionItem sourceItem = (IConversionItem) adapter;
if (commandId.equals("net.heartsome.cat.convert.ui.commands.convertCommand")) {
converterViewModel = new ConverterViewModel(Activator.getContext(), Converter.DIRECTION_POSITIVE);
// 记住所选择的文件
converterViewModel.setConversionItem(sourceItem);
IWizard wizard = new ConversionWizard(Arrays.asList(converterViewModel), null);
TSWizardDialog dialog = new ConversionWizardDialog(window.getShell(), wizard);
int result = dialog.open();
if (result == IDialogConstants.OK_ID) {
converterViewModel.convert();
}
} else {
converterViewModel = new ConverterViewModel(Activator.getContext(), Converter.DIRECTION_REVERSE);
converterViewModel.setConversionItem(sourceItem);
IWizard wizard = new ReverseConversionWizard(Arrays.asList(converterViewModel), null);
TSWizardDialog dialog = new ConversionWizardDialog(window.getShell(), wizard);
int result = dialog.open();
if (result == IDialogConstants.OK_ID) {
converterViewModel.convert();
}
}
}
}
return null;
}
}
| 3,518 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
JobFactoryFacadeImpl.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/job/JobFactoryFacadeImpl.java | package net.heartsome.cat.convert.ui.job;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.progress.IProgressConstants;
/**
* 对 Workspace 中的资源进行操作时,考虑到的并发操作,需要把这些操作放在 WorkspaceJob 中执行,所以此 factory facade 返回的是 WorkspaceJob。
* @author cheney
* @since JDK1.6
*/
public class JobFactoryFacadeImpl extends JobFactoryFacade {
@Override
protected Job createJobInternal(final Display display, final String name, final JobRunnable runnable) {
return new WorkspaceJob(name) {
IStatus result;
@Override
public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
result = runnable.run(monitor);
if (isModal(this)) {
// 直接显示结果
if (display != null && !display.isDisposed()) {
display.asyncExec(new Runnable() {
public void run() {
runnable.showResults(result);
}
});
}
} else {
// 在进度显示视图中显示查看 runnable 运行结果的 action。
setProperty(IProgressConstants.KEEP_PROPERTY, Boolean.TRUE);
setProperty(IProgressConstants.ACTION_PROPERTY, runnable.getRunnableCompletedAction(result));
}
return result;
}
/**
* 判断 job 对应的进度显示对话框的状态。如果是打开状态则返回 true,否则返回 false。
* @param job
* 后台线程 job
* @return 返回 job 对应的进度显示对话框的状态;
*/
private boolean isModal(Job job) {
Boolean isModal = (Boolean) job.getProperty(IProgressConstants.PROPERTY_IN_DIALOG);
if (isModal == null) {
return false;
}
return isModal.booleanValue();
}
};
}
}
| 1,956 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileConversionItemAdapterFactory.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/model/FileConversionItemAdapterFactory.java | package net.heartsome.cat.convert.ui.model;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IAdapterFactory;
/**
* IFile 和 FileConversionItem 的适配器工厂
* @author cheney
* @since JDK1.6
*/
public class FileConversionItemAdapterFactory implements IAdapterFactory {
@SuppressWarnings("rawtypes")
public Object getAdapter(Object adaptableObject, Class adapterType) {
if (adapterType == IConversionItem.class) {
return new FileConversionItem((IFile) adaptableObject);
}
return null;
}
@SuppressWarnings("rawtypes")
public Class[] getAdapterList() {
return new Class[] { IConversionItem.class };
}
}
| 656 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
FileConversionItem.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ui.rcp/src/net/heartsome/cat/convert/ui/model/FileConversionItem.java | package net.heartsome.cat.convert.ui.model;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
/**
* IFile 转换项目实现
* @author cheney
* @since JDK1.6
*/
public class FileConversionItem extends DefaultConversionItem {
private IResource resource;
/**
* IFile 构建函数
* @param file
*/
public FileConversionItem(IFile file) {
super(file.getLocation());
this.resource = file;
}
/**
* IContainer 构建函数
* @param folder
*/
public FileConversionItem(IContainer folder) {
super(folder.getLocation());
this.resource = folder;
}
/**
* IProject 构建函数
* @param project
*/
public FileConversionItem(IProject project) {
super(project.getLocation());
this.resource = project;
}
@Override
public void refresh() {
try {
resource.getProject().refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
// 忽略
}
}
@Override
public boolean contains(ISchedulingRule rule) {
if (this == rule) {
return true;
}
if (rule instanceof FileConversionItem) {
return resource.contains(((FileConversionItem) rule).resource);
}
if (rule instanceof IResource) {
return resource.contains(rule);
}
return super.contains(rule);
}
@Override
public boolean isConflicting(ISchedulingRule rule) {
if (rule instanceof FileConversionItem) {
return resource.isConflicting(((FileConversionItem) rule).resource);
}
if (rule instanceof IResource) {
return resource.isConflicting(rule);
}
return super.isConflicting(rule);
}
@Override
public IConversionItem getParent() {
return new FileConversionItem(resource.getParent());
}
@Override
public IConversionItem getProject() {
return new FileConversionItem(resource.getProject());
}
}
| 1,982 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TuBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.memoQ6/src/net/heartsome/cat/converter/memoq6/TuBean.java | package net.heartsome.cat.converter.memoq6;
public class TuBean {
private String segId;
private String srcText;
private String tgtText;
private String status;
private boolean isLocked;
private String note;
public TuBean(){}
public String getSegId() {
return segId;
}
public void setSegId(String segId) {
this.segId = segId;
}
public String getSrcText() {
return srcText;
}
public void setSrcText(String srcText) {
this.srcText = srcText;
}
public String getTgtText() {
return tgtText;
}
public void setTgtText(String tgtText) {
this.tgtText = tgtText;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public boolean isLocked() {
return isLocked;
}
public void setLocked(boolean isLocked) {
this.isLocked = isLocked;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public boolean isTgtNull(){
return tgtText == null || "".equals(tgtText);
}
}
| 1,076 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.memoQ6/src/net/heartsome/cat/converter/memoq6/Activator.java | package net.heartsome.cat.converter.memoq6;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.ConverterRegister;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator implements BundleActivator {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.converter.memoQ6"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/** trados 2009文件转换至xliff文件的服务注册器 */
// @SuppressWarnings("rawtypes")
private ServiceRegistration mq2XliffSR;
/** xliff文件转换至trados 2009文件的服务注册器 */
// @SuppressWarnings("rawtypes")
private ServiceRegistration xliff2MqSR;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
plugin = this;
Converter mq2Xliff = new Mq2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Mq2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Mq2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Mq2Xliff.TYPE_NAME_VALUE);
mq2XliffSR = ConverterRegister.registerPositiveConverter(context, mq2Xliff, properties);
Converter xliff2Mq = new Xliff2Mq();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Mq.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Mq.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Mq.TYPE_NAME_VALUE);
xliff2MqSR = ConverterRegister.registerReverseConverter(context, xliff2Mq, properties);
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
if (mq2XliffSR != null) {
mq2XliffSR.unregister();
mq2XliffSR = null;
}
if (xliff2MqSR != null) {
xliff2MqSR.unregister();
xliff2MqSR = null;
}
plugin = null;
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,433 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Mq.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.memoQ6/src/net/heartsome/cat/converter/memoq6/Xliff2Mq.java | package net.heartsome.cat.converter.memoq6;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.memoq6.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.eclipse.core.runtime.IProgressMonitor;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* memoQ 6.0 逆向转换器
* @author robert 2012-07-20
*
*/
public class Xliff2Mq implements Converter{
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "mqxlz";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.MQ");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to MQXLZ Conveter";
public Map<String, String> convert(Map<String, String> args,
IProgressMonitor monitor) throws ConverterException {
Xliff2MqImpl converter = new Xliff2MqImpl();
return converter.run(args, monitor);
}
public String getName() {
return NAME_VALUE;
}
public String getType() {
return TYPE_VALUE;
}
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class Xliff2MqImpl{
/** The encoding. */
private String encoding;
/** 逆转换的结果文件 */
private String outputFile;
/** 骨架文件的解析游标 */
private VTDNav sklVN;
/** 骨架文件的修改类实例 */
private XMLModifier sklXM;
/** 骨架文件的查询实例 */
private AutoPilot sklAP;
/** xliff文件的解析游标 */
private VTDNav xlfVN;
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
// 把转换过程分为两大部分共 10 个任务,其中加载 xliff 文件占 4,替换过程占 6。
monitor.beginTask("Converting...", 10);
Map<String, String> result = new HashMap<String, String>();
String sklFile = params.get(Converter.ATTR_SKELETON_FILE);
String xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
outputFile = params.get(Converter.ATTR_TARGET_FILE);
try {
//先将骨架文件的内容拷贝到目标文件,再解析目标文件
copyFile(sklFile, outputFile);
parseOutputFile(sklFile, xliffFile);
parseXlfFile(xliffFile);
ananysisXlfTU();
//下面这是 memoQ 的骨架文件。而sklFile为R8的骨架文件。
File mqTempSkl = File.createTempFile("mqSkeleton", ".mqskl");
mqTempSkl.deleteOnExit();
createMqSkeleton(mqTempSkl);
sklXM.output(sklFile);
createMQZipFile(sklFile, mqTempSkl);
} catch (Exception e) {
e.printStackTrace();
String errorTip = Messages.getString("xlf2mq.msg1") + "\n" + e.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e);
}finally{
monitor.done();
}
return result;
}
/**
* 解析结果文件(解析时这个结果文件还是一个骨架文件)
* @param file
* @throws Exception
*/
private void parseOutputFile(String file, String xliffFile) throws Exception {
// copyFile(file, "C:\\Users\\Administrator\\Desktop\\test.xml");
VTDGen vg = new VTDGen();
if (vg.parseFile(file, true)) {
sklVN = vg.getNav();
sklXM = new XMLModifier(sklVN);
sklAP = new AutoPilot(sklVN);
sklAP.declareXPathNameSpace("mq", "MQXliff");
}else {
String errorInfo = MessageFormat.format(Messages.getString("mq.parse.msg2"),
new Object[]{new File(xliffFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 解析要被逆转换的xliff文件
* @param xliffFile
* @throws Exception
*/
private void parseXlfFile(String xliffFile) throws Exception {
VTDGen vg = new VTDGen();
if (vg.parseFile(xliffFile, true)) {
xlfVN = vg.getNav();
}else {
String errorInfo = MessageFormat.format(Messages.getString("mq.parse.msg1"),
new Object[]{new File(xliffFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 分析xliff文件的每一个 trans-unit 节点
* @throws Exception
*/
private void ananysisXlfTU() throws Exception {
AutoPilot ap = new AutoPilot(xlfVN);
AutoPilot childAP = new AutoPilot(xlfVN);
VTDUtils vu = new VTDUtils(xlfVN);
String xpath = "/xliff/file/body//trans-unit";
String srcXpath = "./source";
String tgtXpath = "./target";
ap.selectXPath(xpath);
int attrIdx = -1;
//trans-unit的id,对应sdl文件的占位符如%%%1%%% 。
String segId = "";
TuBean bean = null;
while (ap.evalXPath() != -1) {
if ((attrIdx = xlfVN.getAttrVal("id")) == -1) {
continue;
}
bean = new TuBean();
segId = xlfVN.toString(attrIdx);
//处理source节点
xlfVN.push();
childAP.selectXPath(srcXpath);
if (childAP.evalXPath() != -1) {
String srcContent = vu.getElementContent();
srcContent = srcContent == null ? "" : srcContent;
bean.setSrcText(TextUtil.resetSpecialString(srcContent));
}
xlfVN.pop();
//处理target节点
String status = ""; //状态,针对target节点,空字符串为未翻译
xlfVN.push();
String tgtContent = null;
childAP.selectXPath(tgtXpath);
if (childAP.evalXPath() != -1) {
tgtContent = vu.getElementContent();
if ((attrIdx = xlfVN.getAttrVal("state")) != -1) {
status = xlfVN.toString(attrIdx);
}
}
tgtContent = tgtContent == null ? "" : tgtContent;
bean.setTgtText(TextUtil.resetSpecialString(tgtContent));
xlfVN.pop();
//处理批注
getNotes(xlfVN, bean);
//判断是否处于锁定状态
if ((attrIdx = xlfVN.getAttrVal("translate")) != -1) {
if ("no".equalsIgnoreCase(xlfVN.toString(attrIdx))) {
bean.setLocked(true);
}
}
//判断是否处于批准状态,若是签发,就没有必要判断了,因为签发了的一定就批准了的
if (!"signed-off".equalsIgnoreCase(status)) {
if ((attrIdx = xlfVN.getAttrVal("approved")) != -1) {
if ("yes".equalsIgnoreCase(xlfVN.toString(attrIdx))) {
status = "approved"; //批准
}
}
}
bean.setStatus(status);
replaceSegment(segId, bean);
}
}
/**
* 获取 R8 xliff文件的所有批注信息
* @param vn
* @param tgtbeBean
*/
private void getNotes(VTDNav vn, TuBean bean) throws Exception {
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "./note";
ap.selectXPath(xpath);
StringBuffer noteSB = new StringBuffer();
while(ap.evalXPath() != -1){
String commentText = "";
if (vn.getText() != -1) {
String r8NoteText = vn.toString(vn.getText());
if (r8NoteText.indexOf(":") != -1) {
commentText = r8NoteText.substring(r8NoteText.indexOf(":") + 1, r8NoteText.length());
}else {
commentText = r8NoteText;
}
}
noteSB.append(commentText + ";\n");
}
bean.setNote(noteSB.toString());
vn.pop();
}
/**
* 替换掉骨架文件中的占位符
* @param segId
* @param srcBean
* @param tgtbeBean
*/
private void replaceSegment(String segId, TuBean bean) throws Exception {
String segStr = "%%%" + segId + "%%%";
String srcXpath = "/xliff/file/body//trans-unit/source[text()='" + segStr + "']";
//先处理源文
sklAP.selectXPath(srcXpath);
if (sklAP.evalXPath() != -1) {
int textIdx = sklVN.getText();
sklXM.updateToken(textIdx, bean.getSrcText().getBytes("utf-8"));
}
//处理译文
String tgtXpath = "/xliff/file/body//trans-unit/target[text()='" + segStr + "']";
sklAP.selectXPath(tgtXpath);
if (sklAP.evalXPath() != -1) {
String content = bean.getTgtText();
int textIdx = sklVN.getText();
sklXM.updateToken(textIdx, content.getBytes("utf-8"));
}
//开始处理状态等其他东西
tgtXpath = "/xliff/file/body//trans-unit[target/text()='" + segStr + "']";
sklAP.selectXPath(tgtXpath);
int index = -1;
boolean needLocked = false;
if (sklAP.evalXPath() != -1) {
//先判断是否锁定
if (bean.isLocked()) {
if ((index = sklVN.getAttrVal("mq:locked")) != -1) {
if (!"locked".equals(sklVN.toString(index))) {
sklXM.updateToken(index, "locked");
}
}else {
needLocked = true;
}
}else {
if ((index = sklVN.getAttrVal("mq:locked")) != -1) {
if ("locked".equals(sklVN.toString(index))) {
sklXM.updateToken(index, "false");
}
}
}
//下面根据R8的状态。修改sdl的状态。
String mqStatus = "";
String status = bean.getStatus();
if ("".equals(status)) {
mqStatus = "NotStarted";
}else if ("new".equals(status)) {
mqStatus = "PartiallyEdited";
}else if ("approved".equals(status)) {
mqStatus = "ManuallyConfirmed";
}else if ("signed-off".equals(status)) {
mqStatus = "ManuallyConfirmed";
}
if ("".equals(mqStatus)) {
if ((index = sklVN.getAttrVal("mq:status")) != -1) {
sklXM.updateToken(index, "");
}
}else {
if ((index = sklVN.getAttrVal("mq:status")) != -1) {
if (!mqStatus.equals(sklVN.toString(index))) {
sklXM.updateToken(index, mqStatus);
}
}else {
String attributeStr = "";
if (needLocked) {
attributeStr = " mq:locked=\"locked\" ";
}
attributeStr += " mq:status=\"" + mqStatus + "\" ";
sklXM.insertAttribute(attributeStr.getBytes("utf-8"));
needLocked = false;
}
}
if (needLocked) {
sklXM.insertAttribute(" mq:locked=\"locked\" ".getBytes("utf-8"));
}
}
}
private void createMqSkeleton(File mqTempSkl) throws Exception{
String xpath = "/xliff/file/header/sklContent";
sklAP.selectXPath(xpath);
String mqSklContent = "";
if(sklAP.evalXPath() != -1){
VTDUtils vu = new VTDUtils(sklVN);
mqSklContent = vu.getElementContent();
sklXM.remove();
}
FileOutputStream output = new FileOutputStream(mqTempSkl);
output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes("UTF-8"));
output.write("<mq:externalparts xmlns:mq=\"MemoQ Xliff external parts\">".getBytes("UTF-8"));
output.write(mqSklContent.getBytes("UTF-8"));
output.write("</mq:externalparts>".getBytes("UTF-8"));
output.close();
}
private void createMQZipFile(String sklFile, File mqTempSkl){
File files[] = new File[]{new File(sklFile), mqTempSkl};
ZipArchiveOutputStream zaos = null;
try {
File zipFile = new File(outputFile);
zaos = new ZipArchiveOutputStream(zipFile);
// Use Zip64 extensions for all entries where they are
// required
// zaos.setUseZip64(Zip64Mode.AsNeeded);
// 将每个文件用ZipArchiveEntry封装
// 再用ZipArchiveOutputStream写到压缩文件中
for (File file : files) {
if (file != null) {
String fileName = file.getName();
if (fileName.endsWith(".skl")) {
fileName = "document.mqxliff";
}else if (fileName.endsWith(".mqskl")) {
fileName = "skeleton.xml";
}
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry( file, fileName);
zaos.putArchiveEntry(zipArchiveEntry);
InputStream is = null;
try {
is = new BufferedInputStream(
new FileInputStream(file));
byte[] buffer = new byte[1024 * 5];
int len = -1;
while ((len = is.read(buffer)) != -1) {
// 把缓冲区的字节写入到ZipArchiveEntry
zaos.write(buffer, 0, len);
}
// Writes all necessary data for this entry.
zaos.closeArchiveEntry();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (is != null)
is.close();
}
}
}
zaos.finish();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if (zaos != null) {
zaos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
/**
* 将一个文件的数据复制到另一个文件
* @param in
* @param out
* @throws Exception
*/
private static void copyFile(String in, String out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
}
| 13,572 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Mq2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.memoQ6/src/net/heartsome/cat/converter/memoq6/Mq2Xliff.java | package net.heartsome.cat.converter.memoq6;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.memoq6.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.util.CRC16;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.eclipse.core.runtime.IProgressMonitor;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* menoQ 6.0 的转换器
* @author robert 2012-07-20
*
*/
public class Mq2Xliff implements Converter{
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "mqxlz";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.MQ");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "MQXLZ to XLIFF Conveter";
public Map<String, String> convert(Map<String, String> args,
IProgressMonitor monitor) throws ConverterException {
Mq2XliffImpl converter = new Mq2XliffImpl();
return converter.run(args, monitor);
}
public String getName() {
return NAME_VALUE;
}
public String getType() {
return TYPE_VALUE;
}
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class Mq2XliffImpl{
/** 源文件 */
private String inputFile;
/** 转换成的XLIFF文件(临时文件) */
private String xliffFile;
/** 骨架文件(临时文件) */
private String skeletonFile;
/** 源语言 */
private String userSourceLang;
/** 目标语言 */
private String targetLang;
// private String detectedSourceLang;
// private String detectedTargetLang;
/** 转换的编码格式 */
private String srcEncoding;
// private Element inputRoot;
// private Document skeleton;
// private Element skeletonRoot;
/** 将数据输出到XLIFF文件的输出流 */
private FileOutputStream output;
private boolean isSuite;
/** 转换工具的ID */
private String qtToolID;
/** 解析骨架文件的VTDNav实例 */
private VTDNav sklVN;
private XMLModifier sklXM;
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
monitor.beginTask("Converting...", 5);
Map<String, String> result = new HashMap<String, String>();
inputFile = params.get(Converter.ATTR_SOURCE_FILE);
xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
skeletonFile = params.get(Converter.ATTR_SKELETON_FILE);
targetLang = params.get(Converter.ATTR_TARGET_LANGUAGE);
userSourceLang = params.get(Converter.ATTR_SOURCE_LANGUAGE);
srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING);
isSuite = false;
if (Converter.TRUE.equalsIgnoreCase(params.get(Converter.ATTR_IS_SUITE))) {
isSuite = true;
}
qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID)
: Converter.QT_TOOLID_DEFAULT_VALUE;
try {
output = new FileOutputStream(xliffFile);
parseMQZip(inputFile, skeletonFile);
// copyFile(skeletonFile, "C:\\Users\\Administrator\\Desktop\\test.xml");
//重新解析
parseHSSkeletonFile();
//先写下头文件
writeHeader();
analyzeNodes();
writeString("</body>\n");
writeString("</file>\n");
writeString("</xliff>");
sklXM.output(skeletonFile);
// String file1 = "/home/robert/Desktop/file1.txt";
// String file2 = "/home/robert/Desktop/file2.txt";
// copyFile(skeletonFile, file1);
// copyFile(xliffFile, file2);
} catch (Exception e) {
e.printStackTrace();
String errorTip = Messages.getString("mq2Xlf.msg1");
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e);
}finally{
try {
output.close();
} catch (Exception e2) {
e2.printStackTrace();
String errorTip = Messages.getString("mq2Xlf.msg1") + "\n" + e2.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e2);
}
monitor.done();
}
return result;
}
/**
* 解析 memoQ 的源文件,并将内容拷贝至骨架文件中
* @param mqZip
* @param hsSkeleton R8 hsxliff的骨架文件
* @throws Exception
*/
private void parseMQZip(String mqZip, String hsSkeleton) throws Exception{
ZipFile zipFile = new ZipFile(new File(mqZip), "utf-8");
Enumeration<?> e = zipFile.getEntries();
byte ch[] = new byte[1024];
String outputFile = "";
File mqSklTempFile = File.createTempFile("tempskl", "skl");
mqSklTempFile.deleteOnExit();
while (e.hasMoreElements()) {
ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();
if ("document.mqxliff".equals(zipEntry.getName())) {
outputFile = hsSkeleton;
}else {
outputFile = mqSklTempFile.getAbsolutePath();
}
File zfile = new File(outputFile);
FileOutputStream fouts = new FileOutputStream(zfile);
InputStream in = zipFile.getInputStream(zipEntry);
int i;
while ((i = in.read(ch)) != -1)
fouts.write(ch, 0, i);
fouts.close();
in.close();
}
//解析r8骨加文件,并把 mq 的骨架信息添加到 r8 的骨架文件中
parseHSSkeletonFile();
copyMqSklToHsSkl(mqSklTempFile);
}
/**
* 解析R8 的骨架文件
* @throws Exception
*/
private void parseHSSkeletonFile() throws Exception {
String errorInfo = "";
VTDGen vg = new VTDGen();
if (vg.parseFile(skeletonFile, true)) {
sklVN = vg.getNav();
sklXM = new XMLModifier(sklVN);
}else {
errorInfo = MessageFormat.format(Messages.getString("mq.parse.msg1"),
new Object[]{new File(inputFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 将mq 的骨架文件拷到R8 的骨架文件中
* @throws Exception
*/
private void copyMqSklToHsSkl(File mqSkeletonFile) throws Exception {
VTDGen vg = new VTDGen();
AutoPilot ap = new AutoPilot();
String mqSklContent = "";
String xpath = "/mq:externalparts";
if(vg.parseFile(mqSkeletonFile.getAbsolutePath(), true)){
VTDNav vn = vg.getNav();
ap.bind(vn);
VTDUtils vu = new VTDUtils(vn);
ap.declareXPathNameSpace("mq", "MemoQ Xliff external parts");
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
mqSklContent = vu.getElementContent();
}
}
//下面添加到 r8 的骨架文件中去
ap.bind(sklVN);
xpath = "/xliff/file/header/skl";
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
sklXM.insertAfterElement("<sklContent>" + mqSklContent + "</sklContent>");
sklXM.output(skeletonFile);
}
}
/**
* 写下XLIFF文件的头节点
*/
private void writeHeader() throws IOException {
writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writeString("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:hs=\""
+ Converter.HSNAMESPACE + "\" "
+ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd "
+ Converter.HSSCHEMALOCATION + "\">\n");
writeString("<file original=\"" + TextUtil.cleanSpecialString(inputFile) + "\" source-language=\"" + userSourceLang);
writeString("\" target-language=\"" + ((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang));
writeString("\" datatype=\"" + TYPE_VALUE + "\">\n");
writeString("<header>\n");
writeString(" <skl>\n");
String crc = "";
if (isSuite) {
crc = "crc=\"" + CRC16.crc16(TextUtil.cleanSpecialString(skeletonFile).getBytes("utf-8")) + "\"";
}
writeString(" <external-file href=\"" + TextUtil.cleanSpecialString(skeletonFile) + "\" " + crc + "/>\n");
writeString(" </skl>\n");
writeString(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n");
writeString(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">"
+ srcEncoding + "</hs:prop></hs:prop-group>\n");
writeString("</header>\n");
writeString("<body>\n");
}
private void writeString(String string) throws IOException {
output.write(string.getBytes("utf-8")); //$NON-NLS-1$
}
/**
* 分析每一个节点
* @throws Exception
*/
private void analyzeNodes() throws Exception{
AutoPilot ap = new AutoPilot(sklVN);
AutoPilot childAP = new AutoPilot(sklVN);
VTDUtils vu = new VTDUtils(sklVN);
String xpath = "/xliff/file/body//trans-unit[source/text()!='' or source/*]"; ///seg-source/mrk[@mtype=\"seg\"]
String srxXpath = "./source";
String tgtXpath = "./target";
//获取每个节点的内容
TuBean bean = null;
ap.selectXPath(xpath);
int index = -1;
//xliff 文件的 trans-unit 节点的 id 值
int segId = 0;
while (ap.evalXPath() != -1) {
bean = new TuBean();
sklVN.push();
childAP.selectXPath(srxXpath);
while (childAP.evalXPath() != -1) {
String srcContent = vu.getElementContent();
if (srcContent != null && !"".equals(srcContent)) {
bean.setSrcText(TextUtil.cleanSpecialString(srcContent));
//开始填充占位符
insertPlaceHolder(vu, "" + segId, "source");
bean.setSegId("" + segId);
segId ++;
}
}
sklVN.pop();
// 开始处理骨架文件的译文信息
sklVN.push();
childAP.selectXPath(tgtXpath);
while (childAP.evalXPath() != -1) {
if (bean.getSegId() == null || "".equals(bean.getSegId())) {
continue;
}
//注意两个填充占位符方法的位置不同。
String tgtContent = vu.getElementContent();
insertPlaceHolder(vu, bean.getSegId(), "target");
bean.setTgtText(TextUtil.cleanSpecialString(tgtContent));
}
if ((index = sklVN.getAttrVal("mq:status")) != -1) {
String status = sklVN.toString(index);
bean.setStatus(status);
}
if ((index = sklVN.getAttrVal("mq:locked")) != -1) {
bean.setLocked("locked".equals(sklVN.toString(index)));
}
//开始填充数据到XLIFF文件
writeSegment(bean);
sklVN.pop();
}
}
/**
* 给剔去翻译内容后的骨架文件填充占位符
* @throws Exception
*/
private void insertPlaceHolder(VTDUtils vu, String seg, String nodeName) throws Exception{
String nodeHeader = vu.getElementHead();
String newNodeStr = nodeHeader + "%%%" + seg + "%%%" + "</" + nodeName + ">";
sklXM.remove();
sklXM.insertAfterElement(newNodeStr);
}
private void writeSegment(TuBean bean) throws Exception {
String srcContent = bean.getSrcText();
StringBuffer tuSB = new StringBuffer();
String status = bean.getStatus();
String tgtStatusStr = "";
boolean isApproved = false;
//NotStarted 为未翻译
//具体的意思及与R8的转换请查看tgtBean.getStatus()的注释。
if ("PartiallyEdited".equals(status)) {
tgtStatusStr += " state=\"new\"";
}else if ("ManuallyConfirmed".equals(status)) {
isApproved = true;
tgtStatusStr += " state=\"translated\"";
}
String approveStr = isApproved ? " approved=\"yes\"" : "";
//是否锁定
String lockStr = bean.isLocked() ? " translate=\"no\"" : "";
tuSB.append(" <trans-unit" + lockStr + approveStr + " id=\"" + bean.getSegId() + "\" xml:space=\"preserve\" >\n");
tuSB.append(" <source xml:lang=\"" + userSourceLang + "\">" + srcContent + "</source>\n");
if (!bean.isTgtNull()) {
String tgtContent = bean.getTgtText();
tuSB.append(" <target" + tgtStatusStr + " xml:lang=\"" +
((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang) + "\">"
+ tgtContent + "</target>\n");
}
//添加备注信息
if (bean.getNote() != null && "".equals(bean.getNote().trim())) {
//这是R8的标注格式:<note from='robert'>2012-03-06:asdf</note>
tuSB.append("<note from=''>" + bean.getNote() + "</note>");
}
tuSB.append(" </trans-unit>\n");
writeString(tuSB.toString());
}
}
/**
* 将一个文件的数据复制到另一个文件
* @param in
* @param out
* @throws Exception
*/
private static void copyFile(String in, String out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
}
| 12,991 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.memoQ6/src/net/heartsome/cat/converter/memoq6/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.memoq6.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* The Class Messages.
* @author John Zhu
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.memoq6.resource.mq"; //$NON-NLS-1$
/** The Constant RESOURCE_BUNDLE. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
/**
* Instantiates a new messages.
*/
private Messages() {
// Do nothing
}
/**
* Gets the string.
* @param key
* the key
* @return the string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| 1,018 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2MSOfficeTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/testSrc/net/heartsome/cat/converter/msoffice2003/test/Xliff2MSOfficeTest.java | package net.heartsome.cat.converter.msoffice2003.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.msoffice2003.Xliff2MSOffice;
import org.junit.BeforeClass;
import org.junit.Test;
public class Xliff2MSOfficeTest {
public static Xliff2MSOffice converter = new Xliff2MSOffice();
private static String rootFolder = "C:\\Documents and Settings\\John\\workspace\\HSTS7\\";
private static String tgtDocFile = "rc/Test_en-US.doc";
private static String xlfDocFile = "rc/Test.doc.xlf";
private static String sklDocFile = "rc/Test.doc.skl";
private static String tgtXlsFile = "rc/Test_en-US.xls";
private static String xlfXlsFile = "rc/Test.xls.xlf";
private static String sklXlsFile = "rc/Test.xls.skl";
private static String tgtPptFile = "rc/Test_en-US.ppt";
private static String xlfPptFile = "rc/Test.ppt.xlf";
private static String sklPptFile = "rc/Test.ppt.skl";
@BeforeClass
public static void setUp() {
File tgt = new File(tgtDocFile);
if (tgt.exists()) {
tgt.delete();
}
tgt = new File(tgtXlsFile);
if (tgt.exists()) {
tgt.delete();
}
tgt = new File(tgtPptFile);
if (tgt.exists()) {
tgt.delete();
}
}
@Test
public void testConvertXls() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtXlsFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfXlsFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklXlsFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String tgt = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(tgt);
File tgtFile = new File(tgt);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
@Test
public void testConvertDoc() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtDocFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfDocFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklDocFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String tgt = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(tgt);
File tgtFile = new File(tgt);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
@Test
public void testConvertPpt() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtPptFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfPptFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklPptFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String tgt = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(tgt);
File tgtFile = new File(tgt);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
}
| 4,104 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MSOffice2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/testSrc/net/heartsome/cat/converter/msoffice2003/test/MSOffice2XliffTest.java | package net.heartsome.cat.converter.msoffice2003.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.msoffice2003.MSOffice2Xliff;
import org.junit.BeforeClass;
import org.junit.Test;
public class MSOffice2XliffTest {
public static MSOffice2Xliff converter = new MSOffice2Xliff();
private static String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
private static String srcDocFile = "rc/Test.doc";
private static String xlfDocFile = "rc/Test.doc.xlf";
private static String sklDocFile = "rc/Test.doc.skl";
private static String srcXlsFile = "rc/Test.xls";
private static String xlfXlsFile = "rc/Test.xls.xlf";
private static String sklXlsFile = "rc/Test.xls.skl";
private static String srcPptFile = "rc/Test.ppt";
private static String xlfPptFile = "rc/Test.ppt.xlf";
private static String sklPptFile = "rc/Test.ppt.skl";
@BeforeClass
public static void setUp() {
File xlf = new File(xlfDocFile);
if (xlf.exists()) {
xlf.delete();
}
File skl = new File(sklDocFile);
if (skl.exists()) {
skl.delete();
}
xlf = new File(xlfXlsFile);
if (xlf.exists()) {
xlf.delete();
}
skl = new File(sklXlsFile);
if (skl.exists()) {
skl.delete();
}
xlf = new File(xlfPptFile);
if (xlf.exists()) {
xlf.delete();
}
skl = new File(sklPptFile);
if (skl.exists()) {
skl.delete();
}
}
@Test
public void testConvertXls() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcXlsFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfXlsFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklXlsFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
@Test
public void testConvertDoc() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcDocFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfDocFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklDocFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
@Test
public void testConvertPpt() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcPptFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfPptFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklPptFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
}
| 4,308 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MS2OOConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/MS2OOConverter.java | /**
* MS2OOConverter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
import java.io.File;
import java.util.Map;
import net.heartsome.cat.converter.ooconnect.SocketOPConnection;
import net.heartsome.cat.converter.ooconverter.OpenOfficeDocumentConverter;
/**
* The Class MS2OOConverter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class MS2OOConverter {
/** The path. */
private String path = ""; //$NON-NLS-1$
/** The port. */
private String port = ""; //$NON-NLS-1$
/** The connection. */
private SocketOPConnection connection = null;
/**
* Instantiates a new m s2 oo converter.
* @param args
* the args
*/
public MS2OOConverter(Map<String, String> args) {
path = args.get("ooPath");
port = args.get("port");
}
/**
* Startconvert.
* @param inputFile
* the input file
* @param outputFile
* the output file
* @param openbyuser
* the openbyuser
* @throws Exception
* the exception
*/
public void startconvert(File inputFile, File outputFile, boolean openbyuser) throws Exception {
boolean isrun = DetectOORunning.isRunning();
if (!isrun) {
OpenConnection.openService(path, port);
openbyuser = false;
}
connection = new SocketOPConnection(Integer.parseInt(port));
connection.connect();
convert(inputFile, outputFile, openbyuser);
}
/**
* Convert.
* @param inputFile
* the input file
* @param outputFile
* the output file
* @param openbyuser
* the openbyuser
* @throws Exception
* the exception
*/
public void convert(File inputFile, File outputFile, boolean openbyuser) throws Exception {
System.out.println("start to convert..."); //$NON-NLS-1$
OpenOfficeDocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
System.out.println("end convert..."); //$NON-NLS-1$
connection.closeconnect();
if (!openbyuser) {
CloseOOconnection.closeService(port);
}
}
/**
* Gets the port.
* @return the port
*/
public String getPort() {
return port;
}
}
| 2,219 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CallService4Windows.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/CallService4Windows.java | /**
* CallService4Windows.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
import java.io.IOException;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ooconnect.TerminationOpenoffice;
/**
* The Class CallService4Windows.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class CallService4Windows {
/**
* Instantiates a new data constant.
*/
protected CallService4Windows() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/** The status. */
private static int status = 0;
/** The proc. */
private static Process proc;
/**
* Start.
* @param path
* the path
* @param port
* the port
*/
public static void start(String path, String port) {
Runtime runtime = Runtime.getRuntime();
String cmdstr = path + " -headless -norestore -invisible" //$NON-NLS-1$
+ " -accept=socket,host=localhost,port=" + port + ";urp; "; //$NON-NLS-1$ //$NON-NLS-2$
try {
proc = runtime.exec(cmdstr);
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); //$NON-NLS-1$
errorGobbler.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
String msg = errorGobbler.getMsg();
if (!msg.equals("")) {
CallService4Windows.setStatus(0);
} else {
CallService4Windows.setStatus(1);
}
} catch (IOException e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
setStatus(0);
return;
}
}
/**
* Gets the process.
* @return the process
*/
public static Process getProcess() {
return proc;
}
/**
* Gets the status.
* @return the status
*/
public static int getStatus() {
return status;
}
/**
* Sets the status.
* @param i
* the new status
*/
public static void setStatus(int i) {
CallService4Windows.status = i;
}
/**
* Close.
* @param port
* the port
*/
public static void close(String port) {
TerminationOpenoffice.closeOpenoffice(port);
}
}
| 2,172 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StartupOO.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/StartupOO.java | /**
* StartupOO.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
import java.util.Hashtable;
/**
* The Class StartupOO.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class StartupOO {
/** The pretable. */
private Hashtable<String, String> pretable = null;
/** The oo service. */
private boolean ooService = false;
/**
* Instantiates a new startup oo.
* @param args
* the args
*/
public StartupOO(Hashtable<String, String> args) {
pretable = args;
}
/**
* Detect conf oo.
* @return true, if successful
*/
public boolean detectConfOO() {
String path = pretable.get("ooPath"); //$NON-NLS-1$
String port = pretable.get("port"); //$NON-NLS-1$
OpenConnection.openService(path, port);
if (OpenConnection.getStatus() == 1) {
setOoService(true);
}
return ooService;
}
/**
* Can start oo.
*/
public void canStartOO() {
String path = pretable.get("ooPath"); //$NON-NLS-1$
String port = pretable.get("port"); //$NON-NLS-1$
/**
* 判断是否配置正确,如果配置正确和用户手动启动正在运行,那么将不关闭正在运行的OO 否则将将关闭正在运行的OO
*/
boolean openbyuser = DetectOORunning.isRunning();
OpenConnection.openService(path, port);
if (OpenConnection.getStatus() == 1) {
setOoService(true);
}
if (!openbyuser) {
CloseOOconnection.closeService(port);
}
}
/**
* Sets the oo service.
* @param status
* the new oo service
*/
public void setOoService(boolean status) {
this.ooService = status;
}
/**
* Gets the oo service.
* @return the oo service
*/
public boolean getOoService() {
return this.ooService;
}
} | 1,767 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CallOO4Linux.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/CallOO4Linux.java | /**
* CallOO4Linux.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ooconnect.TerminationOpenoffice;
/**
* The Class CallOO4Linux.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class CallOO4Linux {
/**
* Instantiates a new data constant.
*/
protected CallOO4Linux() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/** The status. */
private static int status = 0;
/** The proc. */
private static Process proc;
/** The br. */
@SuppressWarnings("unused")
private static BufferedReader br = null;
/** The in. */
@SuppressWarnings("unused")
private static InputStream in = null;
/** The isr. */
@SuppressWarnings("unused")
private static InputStreamReader isr = null;
/**
* Start.
* @param path
* the path
* @param port
* the port
*/
public static void start(String path, String port) {
Runtime runtime = Runtime.getRuntime();
String execStr = path + " -headless -norestore -invisible" //$NON-NLS-1$
+ " \"-accept=socket,host=localhost,port=" + port + ";urp;\" &"; //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(execStr);
String[] args1 = new String[] { "/bin/sh", "-c", execStr }; //$NON-NLS-1$ //$NON-NLS-2$
runtime.availableProcessors();
try {
proc = runtime.exec(args1);
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); //$NON-NLS-1$
errorGobbler.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
String msg = errorGobbler.getMsg();
System.out.println("msg:" + msg); //$NON-NLS-1$
if (!msg.equals("")) {
CallOO4Linux.setStatus(0);
} else {
CallOO4Linux.setStatus(1);
}
} catch (IOException e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
setStatus(0);
return;
}
}
/**
* Gets the porc.
* @return the porc
*/
public static Process getPorc() {
return proc;
}
/**
* Gets the status.
* @return the status
*/
public static int getStatus() {
return status;
}
/**
* Sets the status.
* @param i
* the new status
*/
public static void setStatus(int i) {
status = i;
}
/**
* Close.
* @param port
* the port
*/
public static void close(String port) {
TerminationOpenoffice.closeOpenoffice(port);
}
/**
* The main method.
* @param args
* the arguments
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void main(String[] args) throws IOException {
CallOO4Linux.start("/usr/bin/soffice", "8000"); //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(CallOO4Linux.getStatus());
}
}
| 3,026 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StreamGobbler.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/StreamGobbler.java | /**
* StreamGobbler.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import net.heartsome.cat.converter.Converter;
/**
* The Class StreamGobbler.
* @author John Zhu
* @version
* @since JDK1.6
*/
class StreamGobbler extends Thread {
/** The is. */
InputStream is;
/** The type. */
String type; // 输出流的类型ERROR或OUTPUT
/** The msg. */
String msg = ""; //$NON-NLS-1$
/** The sb. */
StringBuffer sb;
/**
* Instantiates a new stream gobbler.
* @param is
* the is
* @param type
* the type
*/
StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
sb = new StringBuffer();
}
/**
* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
System.out.flush();
}
setMsg(sb.toString());
} catch (IOException ioe) {
if (Converter.DEBUG_MODE) {
ioe.printStackTrace();
}
}
}
/**
* Sets the msg.
* @param msgs
* the new msg
*/
public void setMsg(String msgs) {
this.msg = msgs;
}
/**
* Gets the msg.
* @return the msg
*/
public String getMsg() {
return msg;
}
}
| 1,526 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenConnection.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/OpenConnection.java | /**
* OpenConnection.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
/**
* The Class OpenConnection.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class OpenConnection {
/**
* Instantiates a new data constant.
*/
protected OpenConnection() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/** The linux. */
private static int linux = 1;
/** The windows. */
private static int windows = 2;
/** The mac. */
private static int mac = 3;
/** The status. */
private static int status = 0;
/**
* Open service.
* @param path
* the path
* @param port
* the port
* @return the int
*/
public static int openService(String path, String port) {
if (getSystemCode() == linux) {
CallOO4Linux.start(path, port);
setStauts(CallOO4Linux.getStatus());
} else if (getSystemCode() == windows) {
CallService4Windows.start(path, port);
setStauts(CallService4Windows.getStatus());
} else if (getSystemCode() == mac) {
System.out.println("---------"); //$NON-NLS-1$
CallService4Mac.start(path, port);
setStauts(CallService4Mac.getStatus());
System.out.println("\\\\\\\\\\\\\\\\\\\\"); //$NON-NLS-1$
}
return status;
}
/**
* Gets the system code.
* @return the system code
*/
public static int getSystemCode() {
int systemcode = 0;
String systemname = System.getProperty("os.name").toUpperCase(); //$NON-NLS-1$
if (systemname.contains("LINUX")) { //$NON-NLS-1$
systemcode = linux;
} else if (systemname.contains("WINDOW")) { //$NON-NLS-1$
systemcode = windows;
} else if (systemname.contains("MAC OS X")) { //$NON-NLS-1$
systemcode = mac;
}
return systemcode;
}
/**
* Sets the stauts.
* @param statuscode
* the new stauts
*/
public static void setStauts(int statuscode) {
status = statuscode;
}
/**
* Gets the status.
* @return the status
*/
public static int getStatus() {
return status;
}
}
| 2,065 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CloseOOconnection.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/CloseOOconnection.java | /**
* CloseOOconnection.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
/**
* The Class CloseOOconnection.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class CloseOOconnection {
/**
* Instantiates a new data constant.
*/
protected CloseOOconnection() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/** The linux. */
private static int linux = 1;
/** The windows. */
private static int windows = 2;
/** The mac. */
private static int mac = 3;
/** The status. */
private static int status = 0;
/**
* Close service.
* @param port
* the port
* @return the int
*/
public static int closeService(String port) {
if (getSystemCode() == linux) {
CallOO4Linux.close(port);
setStauts(0);
} else if (getSystemCode() == windows) {
CallService4Windows.close(port);
setStauts(0);
} else if (getSystemCode() == mac) {
CallService4Mac.close(port);
setStauts(0);
}
return status;
}
/**
* Gets the system code.
* @return the system code
*/
public static int getSystemCode() {
int systemcode = 0;
String systemname = System.getProperty("os.name").toUpperCase(); //$NON-NLS-1$
if (systemname.contains("LINUX")) { //$NON-NLS-1$
systemcode = linux;
} else if (systemname.contains("WINDOW")) { //$NON-NLS-1$
systemcode = windows;
} else if (systemname.contains("MAC OS X")) { //$NON-NLS-1$
systemcode = mac;
}
return systemcode;
}
/**
* Sets the stauts.
* @param statuscode
* the new stauts
*/
public static void setStauts(int statuscode) {
status = statuscode;
}
/**
* Gets the status.
* @return the status
*/
public static int getStatus() {
return status;
}
}
| 1,816 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CallService4Mac.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/CallService4Mac.java | /**
* CallService4Mac.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
import java.io.IOException;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ooconnect.TerminationOpenoffice;
/**
* The Class CallService4Mac.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class CallService4Mac {
/**
* Instantiates a new data constant.
*/
protected CallService4Mac() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/** The status. */
private static int status = 0;
/** The proc. */
private static Process proc;
/**
* Start.
* @param path
* the path
* @param port
* the port
*/
public static void start(String path, String port) {
Runtime runtime = Runtime.getRuntime();
if (path.indexOf("/Contents/MacOS/soffice") == -1) { //$NON-NLS-1$
path = path + "/Contents/MacOS/soffice"; //$NON-NLS-1$
}
// "/Applications/OpenOffice.org\ 2.4.app/Contents/MacOS/soffice"
path = path.trim();
path = path.replace(" ", "\\ "); //$NON-NLS-1$ //$NON-NLS-2$
// path =path.substring(0,path.length()-1);
// path ="."+path;
System.out.println(path);
String execStr = path + " -headless -norestore -invisible" //$NON-NLS-1$
+ " \"-accept=socket,host=localhost,port=" + port + ";urp;\" &"; //$NON-NLS-1$ //$NON-NLS-2$
System.out.println(execStr);
String[] args1 = new String[] { "/bin/sh", "-c", execStr }; //$NON-NLS-1$ //$NON-NLS-2$
runtime.availableProcessors();
// /Applications/OpenOffice.org\ 2.4.app/Contents/MacOS/soffice
// -headless -norestore -invisible
// "-accept=socket,host=localhost,port=9000;urp;" &
// cmdstr="./Applications/OpenOffice.org 2.4.app/Contents/MacOS/soffice.bin";
try {
proc = runtime.exec(args1);
StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); //$NON-NLS-1$
errorGobbler.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
String msg = errorGobbler.getMsg();
if (!msg.equals("") && msg.indexOf("No such file or directory") == -1) { //$NON-NLS-1$ //$NON-NLS-2$
// CallService4Mac.setStatus(1);
msg = ""; //$NON-NLS-1$
}
System.out.println("Msg:" + msg); //$NON-NLS-1$
System.out.println(msg.equals("")); //$NON-NLS-1$
if (!msg.equals("")) {
CallService4Mac.setStatus(0);
} else {
CallService4Mac.setStatus(1);
}
System.out.println(CallService4Mac.getStatus());
} catch (IOException e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
setStatus(0);
return;
}
}
/**
* Gets the process.
* @return the process
*/
public static Process getProcess() {
return proc;
}
/**
* Gets the status.
* @return the status
*/
public static int getStatus() {
return status;
}
/**
* Sets the status.
* @param i
* the new status
*/
public static void setStatus(int i) {
CallService4Mac.status = i;
}
/**
* Close.
* @param port
* the port
*/
public static void close(String port) {
TerminationOpenoffice.closeOpenoffice(port);
}
}
| 3,253 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DetectOORunning.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ms2oo/DetectOORunning.java | /**
* DetectOORunning.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ms2oo;
import java.io.IOException;
import net.heartsome.cat.converter.Converter;
/**
* The Class DetectOORunning.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class DetectOORunning {
/**
* Instantiates a new data constant.
*/
protected DetectOORunning() {
throw new UnsupportedOperationException(); // prevents calls from subclass
}
/** The Constant linux. */
private static final int LINUX = 1;
/** The Constant windows. */
private static final int WINDOWS = 2;
/** The Constant mac. */
private static final int MAC = 3;
/** The username. */
private static String username;
/** The is runn. */
private static boolean isRunn = false;
/**
* Checks if is running.
* @return true, if is running
*/
public static boolean isRunning() {
username = System.getProperty("user.name"); //$NON-NLS-1$
int systemcode = DetectOORunning.getSystemCode();
switch (systemcode) {
case LINUX:
isRunn = detectLinux();
break;
case WINDOWS:
isRunn = detectWins();
break;
case MAC:
isRunn = detectMac();
break;
default:
break;
}
return isRunn;
}
/**
* Gets the checks if is running.
* @return the checks if is running
*/
public static boolean getIsRunning() {
return DetectOORunning.isRunn;
}
/**
* Sets the checks if is running.
* @param isrun
* the new checks if is running
*/
public static void setIsRunning(boolean isrun) {
DetectOORunning.isRunn = isrun;
}
/**
* Detect linux.
* @return true, if successful
*/
private static boolean detectLinux() {
boolean isrun = false;
Runtime runtime = Runtime.getRuntime();
String execStr = "ps -U " + username + "|grep soffice"; //$NON-NLS-1$ //$NON-NLS-2$
String[] args1 = new String[] { "/bin/sh", "-c", execStr }; //$NON-NLS-1$ //$NON-NLS-2$
runtime.availableProcessors();
try {
System.out.println(System.getProperty("user.name") + "Linux"); //$NON-NLS-1$ //$NON-NLS-2$
Process proc = runtime.exec(args1);
StreamGobbler errorGobbler = new StreamGobbler(proc.getInputStream(), "info"); //$NON-NLS-1$
errorGobbler.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
String msg = errorGobbler.getMsg();
isrun = msg.toLowerCase().contains("soffice"); //$NON-NLS-1$
} catch (IOException e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
}
return isrun;
}
/**
* Detect wins.
* @return true, if successful
*/
private static boolean detectWins() {
boolean isrun = false;
Runtime runtime = Runtime.getRuntime();
String cmdstr = "tasklist /FI \"IMAGENAME eq soffice.exe\""; //$NON-NLS-1$
try {
Process proc = runtime.exec(cmdstr);
StreamGobbler errorGobbler = new StreamGobbler(proc.getInputStream(), "info"); //$NON-NLS-1$
errorGobbler.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
String msg = errorGobbler.getMsg();
isrun = msg.toLowerCase().contains("soffice"); //$NON-NLS-1$
} catch (IOException e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
}
return isrun;
}
/**
* Detect mac.
* @return true, if successful
*/
private static boolean detectMac() {
boolean isrun = false;
Runtime runtime = Runtime.getRuntime();
String execStr = "ps -U " + username + " -c|grep soffice"; //$NON-NLS-1$ //$NON-NLS-2$
String[] args1 = new String[] { "/bin/sh", "-c", execStr }; //$NON-NLS-1$ //$NON-NLS-2$
runtime.availableProcessors();
try {
Process proc = runtime.exec(args1);
StreamGobbler errorGobbler = new StreamGobbler(proc.getInputStream(), "info"); //$NON-NLS-1$
errorGobbler.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
String msg = errorGobbler.getMsg();
isrun = msg.toLowerCase().contains("soffice"); //$NON-NLS-1$
} catch (IOException e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
}
return isrun;
}
/**
* Gets the system code.
* @return the system code
*/
private static int getSystemCode() {
int systemcode = 0;
String systemname = System.getProperty("os.name").toUpperCase(); //$NON-NLS-1$
if (systemname.contains("LINUX")) { //$NON-NLS-1$
systemcode = LINUX;
} else if (systemname.contains("WINDOW")) { //$NON-NLS-1$
systemcode = WINDOWS;
} else if (systemname.contains("MAC OS X")) { //$NON-NLS-1$
systemcode = MAC;
}
return systemcode;
}
/**
* The main method.
* @param args
* the arguments
*/
public static void main(String[] args) {
System.out.println(isRunning());
}
}
| 4,922 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2MSOffice.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/msoffice2003/Xliff2MSOffice.java | /**
* Xliff2MSOffice.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2003;
import java.io.File;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.ms2oo.CloseOOconnection;
import net.heartsome.cat.converter.ms2oo.DetectOORunning;
import net.heartsome.cat.converter.ms2oo.MS2OOConverter;
import net.heartsome.cat.converter.ms2oo.StartupOO;
import net.heartsome.cat.converter.msoffice2003.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.converter.util.ReverseConversionInfoLogRecord;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The Class Xliff2MSOffice.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Xliff2MSOffice implements Converter {
private static final Logger LOGGER = LoggerFactory.getLogger(Xliff2MSOffice.class);
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-msoffice2003";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("msoffice2003.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to MS Office Document Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public Xliff2MSOffice() {
dependantConverter = Activator.getOpenOfficeConverter(Converter.DIRECTION_REVERSE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public Xliff2MSOffice(Converter converter) {
dependantConverter = converter;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Xliff2MSOfficeImpl converter = new Xliff2MSOfficeImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getName()
* @return
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getType()
* @return
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getTypeName()
* @return
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* The Class Xliff2MSOfficeImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2MSOfficeImpl {
private boolean isInfoEnabled = LOGGER.isInfoEnabled();
/**
* Run.
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord();
infoLogger.startConversion();
Map<String, String> result = new HashMap<String, String>();
String backfile = args.get(Converter.ATTR_TARGET_FILE);
String middleBackfile = MSOffice2Xliff.getOutputFilePath(backfile);
// 先转换成ODT,ODS,ODP等文件,然后在转换成DOC,XLS,PPT
args.put(Converter.ATTR_TARGET_FILE, middleBackfile);
try {
// 把转换过程分为三部分共 10 个任,其中委派其它转换的操作占 4,检测 Open Office Service 是否可用占 2,调用 Open Office Service 进行的操作占 4。
monitor.beginTask(Messages.getString("msoffice2003.Xliff2MSOffice.task1"), 10);
long startTime = 0;
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger1"), startTime);
}
result = dependantConverter.convert(args, Progress.getSubMonitor(monitor, 4));
long endTime = System.currentTimeMillis();
if (isInfoEnabled) {
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger2"), endTime);
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger3"), endTime - startTime);
}
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2003.cancel"));
}
monitor.subTask(Messages.getString("msoffice2003.Xliff2MSOffice.task2"));
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger4"), startTime);
}
File backup = new File(backfile);
File middleFile = new File(middleBackfile);
boolean openbyuser = DetectOORunning.isRunning(); // 判断是否手动启动
boolean configration = false;
Hashtable<String, String> ooParams = new Hashtable<String, String>();
ooParams.put("ooPath", args.get("ooPath"));
ooParams.put("port", args.get("ooPort"));
StartupOO startupoo = new StartupOO(ooParams);
configration = startupoo.detectConfOO();
if (!configration) {
ConverterUtils
.throwConverterException(
Activator.PLUGIN_ID,
Messages.getString("msoffice2003.Xliff2MSOffice.msg1"));
}
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger5"), endTime);
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger6"), endTime - startTime);
}
monitor.worked(2);
// 是否取消操作
monitor.subTask(Messages.getString("msoffice2003.Xliff2MSOffice.task3"));
if (isInfoEnabled) {
startTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger7"), startTime);
}
MS2OOConverter ms2ooConverter = new MS2OOConverter(ooParams);
try {
ms2ooConverter.startconvert(middleFile, backup, openbyuser);
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
try {
openbyuser = false;
ms2ooConverter.startconvert(middleFile, backup, openbyuser);
} catch (Exception e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
if (!openbyuser) {
CloseOOconnection.closeService(ms2ooConverter.getPort());
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("msoffice2003.Xliff2MSOffice.msg2"), e);
}
}
middleFile.delete();
if (isInfoEnabled) {
endTime = System.currentTimeMillis();
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger8"), endTime);
LOGGER.info(Messages.getString("msoffice2003.Xliff2MSOffice.logger9"), endTime - startTime);
}
monitor.worked(4);
} catch (OperationCanceledException e) {
throw e;
} catch (ConverterException e) {
throw e;
} catch (Exception e) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("msoffice2003.Xliff2MSOffice.msg2"), e);
} finally {
monitor.done();
}
result.put(Converter.ATTR_TARGET_FILE, backfile);
infoLogger.endConversion();
return result;
}
}
}
| 7,812 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MSOffice2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/msoffice2003/MSOffice2Xliff.java | /**
* MSOffice2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2003;
import java.io.File;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.ms2oo.CloseOOconnection;
import net.heartsome.cat.converter.ms2oo.DetectOORunning;
import net.heartsome.cat.converter.ms2oo.MS2OOConverter;
import net.heartsome.cat.converter.ms2oo.StartupOO;
import net.heartsome.cat.converter.msoffice2003.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
/**
* The Class MSOffice2Xliff.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class MSOffice2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-msoffice2003";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("msoffice2003.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "MS Office Document to XLIFF Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public MSOffice2Xliff() {
dependantConverter = Activator.getOpenOfficeConverter(Converter.DIRECTION_POSITIVE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public MSOffice2Xliff(Converter converter) {
dependantConverter = converter;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
MSOffice2XliffImpl converter = new MSOffice2XliffImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getName()
* @return
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getType()
* @return
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getTypeName()
* @return
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* Gets the suffix name.
* @param str
* the str
* @return the suffix name
*/
public static String getSuffixName(String str) {
String suffixName = ""; //$NON-NLS-1$
int i = str.lastIndexOf("."); //$NON-NLS-1$
suffixName = str.substring(i + 1);
return suffixName;
}
/**
* Gets the output file path.
* @param inputstr
* the inputstr
* @return the output file path
*/
public static String getOutputFilePath(String inputstr) {
String suffixPath = ""; //$NON-NLS-1$
int i = inputstr.lastIndexOf("."); //$NON-NLS-1$
String suffName = getSuffixName(inputstr);
suffixPath = inputstr.substring(0, i);
if (suffName.equalsIgnoreCase("doc")) { //$NON-NLS-1$
suffixPath = suffixPath + ".odt"; //$NON-NLS-1$
} else if (suffName.equalsIgnoreCase("xls")) { //$NON-NLS-1$
suffixPath = suffixPath + ".ods"; //$NON-NLS-1$
} else if (suffName.equalsIgnoreCase("ppt")) { //$NON-NLS-1$
suffixPath = suffixPath + ".odp"; //$NON-NLS-1$
} else if (suffName.equalsIgnoreCase("rtf")) { //$NON-NLS-1$
suffixPath = suffixPath + ".odt"; //$NON-NLS-1$
} else {
suffixPath = suffixPath + "." + suffName;
}
return suffixPath;
}
/**
* Gets the oupt file path.
* @param inputstr
* the inputstr
* @param suffName
* the suff name
* @return the oupt file path
*/
public static String getOuptFilePath(String inputstr, String suffName) {
String suffixPath = ""; //$NON-NLS-1$
int i = inputstr.lastIndexOf("."); //$NON-NLS-1$
suffixPath = inputstr.substring(0, i);
if (suffName.equalsIgnoreCase("doc")) { //$NON-NLS-1$
suffixPath = suffixPath + ".odt"; //$NON-NLS-1$
}
if (suffName.equalsIgnoreCase("xls")) { //$NON-NLS-1$
suffixPath = suffixPath + ".ods"; //$NON-NLS-1$
}
if (suffName.equalsIgnoreCase("ppt")) { //$NON-NLS-1$
suffixPath = suffixPath + ".odp"; //$NON-NLS-1$
}
return suffixPath;
}
/**
* The Class MSOffice2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class MSOffice2XliffImpl {
/**
* Run.
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
Map<String, String> result = new HashMap<String, String>();
// 在外层添加一个 try{}finally{},确保 IProgressMonitor 的 done 方法都会调用到。
try {
// 把转换操作分为 5 个部分:检查 open office 服务是否可用占 1 个部分,用 open office 转文件占 2 个部分,最后用 xml 转换器转文件占 2 个部分。
monitor.beginTask(Messages.getString("msoffice2003.MSOffice2Xliff.task1"), 5);
monitor.subTask(Messages.getString("msoffice2003.MSOffice2Xliff.task2"));
boolean openbyuser = DetectOORunning.isRunning(); // 判断是否手动启动
boolean configration = false;
// 检查是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2003.cancel"));
}
monitor.worked(1);
Hashtable<String, String> ooParams = new Hashtable<String, String>();
ooParams.put("ooPath", args.get("ooPath"));
ooParams.put("port", args.get("ooPort"));
StartupOO startupoo = new StartupOO(ooParams);
configration = startupoo.detectConfOO();
if (!configration) {
ConverterUtils
.throwConverterException(
Activator.PLUGIN_ID,
Messages.getString("msoffice2003.MSOffice2Xliff.msg1"));
}
// 先转成OO,OO在转成XLIF
String inputFileStr = args.get(Converter.ATTR_SOURCE_FILE);
String suffixName = getSuffixName(inputFileStr);
File inputFile = new File(inputFileStr);
String outputstr = getOuptFilePath(inputFileStr, suffixName);
File outputFile = new File(outputstr);
MS2OOConverter ms2ooConverter = new MS2OOConverter(ooParams);
// fixed a bug 917 by john.
try {
outputstr = outputFile.getName();
int i = outputstr.lastIndexOf("."); //$NON-NLS-1$
String suffixPath = ""; //$NON-NLS-1$
String prefixPath = ""; //$NON-NLS-1$
if (i > 0) {
prefixPath = outputstr.substring(0, i);
suffixPath = outputstr.substring(i, outputstr.length());
} else {
prefixPath = outputstr;
}
outputFile = null;
//File.createTempFile 这个方法必须要求文件名的长度大于3
if(prefixPath.length()<3){
prefixPath = "prefixPath"+prefixPath;
}
outputFile = File.createTempFile(prefixPath, suffixPath);
outputstr = outputFile.getAbsolutePath();
// 检查是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2003.cancel"));
}
monitor.subTask(Messages.getString("msoffice2003.MSOffice2Xliff.task3"));
ms2ooConverter.startconvert(inputFile, outputFile, openbyuser);
monitor.worked(2);
} catch (OperationCanceledException e) {
throw e;
} catch (ConverterException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
try {
openbyuser = false;
ms2ooConverter.startconvert(inputFile, outputFile, openbyuser);
} catch (Exception e1) {
if (Converter.DEBUG_MODE) {
e1.printStackTrace();
}
if (!openbyuser) {
CloseOOconnection.closeService(ms2ooConverter.getPort());
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("msoffice2003.MSOffice2Xliff.msg2"), e);
}
}
// 这里将MS--DOC,XLS,PPT转成 ODT,ODX,ODP文件
args.put(Converter.ATTR_SOURCE_FILE, outputstr);
args.put(Converter.ATTR_FORMAT, TYPE_VALUE);
args.put("isofficefile", "true");
// 检查是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("msoffice2003.cancel"));
}
monitor.subTask(Messages.getString("msoffice2003.MSOffice2Xliff.task4"));
result = dependantConverter.convert(args, Progress.getSubMonitor(monitor, 2));
outputFile.delete();
} finally {
monitor.done();
}
return result;
}
}
}
| 9,159 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/msoffice2003/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2003;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.openoffice.OpenOffice2Xliff;
import net.heartsome.cat.converter.openoffice.Xliff2OpenOffice;
import net.heartsome.cat.converter.util.AndFilter;
import net.heartsome.cat.converter.util.ConverterRegister;
import net.heartsome.cat.converter.util.EqFilter;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
/**
* The Class Activator. The activator class controls the plug-in life cycle.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Activator implements BundleActivator {
// The plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.msoffice2003";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The bundle context. */
private static BundleContext bundleContext;
/** The positive tracker. */
private static ServiceTracker positiveTracker;
/** The reverse tracker. */
private static ServiceTracker reverseTracker;
/**
* The constructor.
*/
public Activator() {
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void start(BundleContext context) throws Exception {
plugin = this;
bundleContext = context;
// tracker the open office converter service
String positiveFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, OpenOffice2Xliff.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_POSITIVE)).toString();
positiveTracker = new ServiceTracker(context, context.createFilter(positiveFilter),
new OpenOfficePositiveCustomizer());
positiveTracker.open();
String reverseFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xliff2OpenOffice.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_REVERSE)).toString();
reverseTracker = new ServiceTracker(context, context.createFilter(reverseFilter),
new OpenOfficeReverseCustomize());
reverseTracker.open();
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void stop(BundleContext context) throws Exception {
positiveTracker.close();
reverseTracker.close();
plugin = null;
bundleContext = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
// just for test
/**
* Gets the open office converter.
* @param direction
* the direction
* @return the open office converter
*/
public static Converter getOpenOfficeConverter(String direction) {
if (Converter.DIRECTION_POSITIVE.equals(direction)) {
return new OpenOffice2Xliff();
} else {
return new Xliff2OpenOffice();
}
}
/**
* The Class OpenOfficePositiveCustomizer.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class OpenOfficePositiveCustomizer implements ServiceTrackerCustomizer {
/**
* (non-Javadoc).
* @param reference
* the reference
* @return the object
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference)
*/
public Object addingService(ServiceReference reference) {
Converter converter = (Converter) bundleContext.getService(reference);
Converter inx2Xliff = new MSOffice2Xliff(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, MSOffice2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, MSOffice2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, MSOffice2Xliff.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerPositiveConverter(bundleContext, inx2Xliff,
properties);
return registration;
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void modifiedService(ServiceReference reference, Object service) {
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void removedService(ServiceReference reference, Object service) {
ServiceRegistration registration = (ServiceRegistration) service;
registration.unregister();
bundleContext.ungetService(reference);
}
}
/**
* The Class OpenOfficeReverseCustomize.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class OpenOfficeReverseCustomize implements ServiceTrackerCustomizer {
/**
* (non-Javadoc).
* @param reference
* the reference
* @return the object
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference)
*/
public Object addingService(ServiceReference reference) {
Converter converter = (Converter) bundleContext.getService(reference);
Converter xliff2Inx = new Xliff2MSOffice(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2MSOffice.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2MSOffice.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2MSOffice.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerReverseConverter(bundleContext, xliff2Inx,
properties);
return registration;
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void modifiedService(ServiceReference reference, Object service) {
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void removedService(ServiceReference reference, Object service) {
ServiceRegistration registration = (ServiceRegistration) service;
registration.unregister();
bundleContext.ungetService(reference);
}
}
}
| 7,159 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/msoffice2003/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msoffice2003.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 国际化工具类
* @author peason
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.msoffice2003.resource.message"; //$NON-NLS-1$
/** The Constant RESOURCE_BUNDLE. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
/**
* Instantiates a new messages.
*/
private Messages() {
}
/**
* Gets the string.
* @param key
* the key
* @return the string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| 971 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SocketOPConnection.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconnect/SocketOPConnection.java | /**
* SocketOPConnection.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconnect;
/**
* The Class SocketOPConnection.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class SocketOPConnection extends OPConnection {
/** The Constant DEFAULT_HOST. */
public static final String DEFAULT_HOST = "localhost"; //$NON-NLS-1$
/** The Constant DEFAULT_PORT. */
public static final int DEFAULT_PORT = 8100;
/**
* Instantiates a new socket op connection.
*/
public SocketOPConnection() {
this(DEFAULT_HOST, DEFAULT_PORT);
}
/**
* Instantiates a new socket op connection.
* @param port
* the port
*/
public SocketOPConnection(int port) {
this(DEFAULT_HOST, port);
}
/**
* Instantiates a new socket op connection.
* @param host
* the host
* @param port
* the port
*/
public SocketOPConnection(String host, int port) {
super("socket,host=" + host + ",port=" + port + ",tcpNoDelay=1"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
} | 1,087 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TerminationOpenoffice.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconnect/TerminationOpenoffice.java | /**
* TerminationOpenoffice.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconnect;
import net.heartsome.cat.converter.Converter;
import com.sun.star.beans.XPropertySet;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.frame.XDesktop;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/**
* The Class TerminationOpenoffice.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class TerminationOpenoffice extends java.lang.Object {
/** The at work. */
private static boolean atWork = false;
// public static void main(String[] args) {
/**
* Close openoffice.
* @param port
* the port
*/
public static void closeOpenoffice(String port) {
XComponentContext xRemoteContext = null;
XMultiComponentFactory xRemoteServiceManager = null;
XDesktop xDesktop = null;
try {
XComponentContext xLocalContext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
XMultiComponentFactory xLocalServiceManager = xLocalContext.getServiceManager();
Object urlResolver = xLocalServiceManager.createInstanceWithContext(
"com.sun.star.bridge.UnoUrlResolver", xLocalContext); //$NON-NLS-1$
XUnoUrlResolver xUnoUrlResolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class,
urlResolver);
Object initialObject = xUnoUrlResolver
.resolve("uno:socket,host=localhost,port=" + port + ";urp;StarOffice.ServiceManager"); //$NON-NLS-1$ //$NON-NLS-2$
// Object initialObject =
// xUnoUrlResolver.resolve("uno:pipe,name=my_app;urp;StarOffice.ServiceManager"
// );
XPropertySet xPropertySet = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, initialObject);
Object context = xPropertySet.getPropertyValue("DefaultContext"); //$NON-NLS-1$
xRemoteContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, context);
xRemoteServiceManager = xRemoteContext.getServiceManager();
// get Desktop instance
Object desktop = xRemoteServiceManager.createInstanceWithContext(
"com.sun.star.frame.Desktop", xRemoteContext); //$NON-NLS-1$
xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop);
TerminateListener terminateListener = new TerminateListener();
xDesktop.addTerminateListener(terminateListener);
// try to terminate while we are at work
atWork = true;
boolean terminated = xDesktop.terminate();
System.out.println("The Office " + //$NON-NLS-1$
(terminated ? "has been terminated" : "is still running, we are at work")); //$NON-NLS-1$ //$NON-NLS-2$
// no longer at work
atWork = false;
// once more: try to terminate
terminated = xDesktop.terminate();
System.out.println("The Office " + //$NON-NLS-1$
(terminated ? "has been terminated" : //$NON-NLS-1$
"is still running. Someone else prevents termination, e.g. the quickstarter")); //$NON-NLS-1$
} catch (java.lang.Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
}
/**
* Checks if is at work.
* @return true, if is at work
*/
public static boolean isAtWork() {
return atWork;
}
/**
* Gets the current component.
* @return the current component
* @throws Exception
* the exception
*/
public static XComponent getCurrentComponent() throws Exception {
XComponentContext xRemoteContext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
// XComponentContext xRemoteContext =
// com.sun.star.comp.helper.Bootstrap.bootstrap();
XMultiComponentFactory xRemoteServiceManager = xRemoteContext.getServiceManager();
Object desktop = xRemoteServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", xRemoteContext); //$NON-NLS-1$
XDesktop xDesktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktop);
XComponent currentComponent = xDesktop.getCurrentComponent();
return currentComponent;
}
} | 4,109 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OPConnection.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconnect/OPConnection.java | /**
* OPConnection.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconnect;
import java.net.ConnectException;
import java.text.MessageFormat;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.msoffice2003.resource.Messages;
import com.sun.star.beans.XPropertySet;
import com.sun.star.bridge.XBridge;
import com.sun.star.bridge.XBridgeFactory;
import com.sun.star.comp.helper.Bootstrap;
import com.sun.star.connection.NoConnectException;
import com.sun.star.connection.XConnection;
import com.sun.star.connection.XConnector;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.ucb.XFileIdentifierConverter;
import com.sun.star.uno.Exception;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/**
* The Class OPConnection.
* @author John Zhu
* @version
* @since JDK1.6
*/
public abstract class OPConnection implements OPconnect {
/** The str connection. */
private String strConnection;
/** The bg component. */
private XComponent bgComponent;
/** The service mg. */
private XMultiComponentFactory serviceMg;
/** The component context. */
private XComponentContext componentContext;
/** The bridge. */
private XBridge bridge;
/** The connected. */
private boolean connected = false;
/** The expecting disconnection. */
private boolean expectingDisconnection = false;
/**
* Instantiates a new oP connection.
* @param connectionStr
* the connection str
*/
protected OPConnection(String connectionStr) {
this.strConnection = connectionStr;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#connect()
* @throws ConnectException
*/
public void connect() throws ConnectException {
try {
XComponentContext localContext;
localContext = Bootstrap.createInitialComponentContext(null);
XMultiComponentFactory localServiceManager = localContext.getServiceManager();
XConnector connector = (XConnector) UnoRuntime.queryInterface(XConnector.class, localServiceManager
.createInstanceWithContext("com.sun.star.connection.Connector", localContext)); //$NON-NLS-1$
XConnection connection = connector.connect(strConnection);
XBridgeFactory bridgeFactory = (XBridgeFactory) UnoRuntime.queryInterface(XBridgeFactory.class,
localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext)); //$NON-NLS-1$
bridge = bridgeFactory.createBridge("ms2ooBridge", "urp", connection, null); //$NON-NLS-1$ //$NON-NLS-2$
bgComponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, bridge);
// bgComponent.addEventListener(this);
serviceMg = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, bridge
.getInstance("StarOffice.ServiceManager")); //$NON-NLS-1$
XPropertySet properties = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, serviceMg);
componentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, properties
.getPropertyValue("DefaultContext")); //$NON-NLS-1$
connected = true;
if (connected) {
System.out.println("has already connected"); //$NON-NLS-1$
} else {
System.out.println("connect to Openoffice fail,please check OpenOffice service that have to open"); //$NON-NLS-1$
}
} catch (NoConnectException connectException) {
throw new ConnectException(MessageFormat.format(Messages.getString("ooconnect.OPConnection.msg"), strConnection + ": " + connectException.getMessage())); //$NON-NLS-1$ //$NON-NLS-2$
} catch (Exception exception) {
throw new OPException(MessageFormat.format(Messages.getString("ooconnect.OPConnection.msg"), strConnection), exception); //$NON-NLS-1$
} catch (java.lang.Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
}
/**
* Disposing.
*/
public void disposing() {
expectingDisconnection = false;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#closeconnect()
*/
public synchronized void closeconnect() {
if (expectingDisconnection) {
System.out.print("");
}
expectingDisconnection = true;
bgComponent.dispose();
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#getBridge()
* @return
*/
public XBridge getBridge() {
return bridge;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#getComponentContext()
* @return
*/
public XComponentContext getComponentContext() {
return componentContext;
}
/**
* Gets the service.
* @param className
* the class name
* @return the service
* @throws Exception
* the exception
*/
private Object getService(String className) throws Exception {
return serviceMg.createInstanceWithContext(className, componentContext);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#getDesktopObject()
* @return
*/
public XComponentLoader getDesktopObject() {
XComponentLoader xc = null;
try {
xc = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,
getService("com.sun.star.frame.Desktop")); //$NON-NLS-1$
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
return xc;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#getFileContentProvider()
* @return
*/
public XFileIdentifierConverter getFileContentProvider() {
XFileIdentifierConverter xf = null;
try {
xf = (XFileIdentifierConverter) UnoRuntime.queryInterface(XFileIdentifierConverter.class,
getService("com.sun.star.ucb.FileContentProvider")); //$NON-NLS-1$
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
}
return xf;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#getRemoteServiceManager()
* @return
*/
public XMultiComponentFactory getRemoteServiceManager() {
return serviceMg;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconnect.OPconnect#isConnected()
* @return
*/
public boolean isConnected() {
return connected;
}
}
| 6,333 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OPconnect.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconnect/OPconnect.java | /**
* OPconnect.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconnect;
import java.net.ConnectException;
import com.sun.star.bridge.XBridge;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.ucb.XFileIdentifierConverter;
import com.sun.star.uno.XComponentContext;
/**
* The Interface OPconnect.
* @author John Zhu
* @version
* @since JDK1.6
*/
public interface OPconnect {
/**
* Connect.
* @throws ConnectException
* the connect exception
*/
void connect() throws ConnectException;
/**
* Closeconnect.
*/
void closeconnect();
/**
* Checks if is connected.
* @return true, if is connected
*/
boolean isConnected();
/**
* Gets the desktop object.
* @return the desktop object
* @返回 com.sun.star.frame.Desktop service
*/
XComponentLoader getDesktopObject();
/**
* Gets the file content provider.
* @return the com.sun.star.ucb.FileContentProvider service
*/
XFileIdentifierConverter getFileContentProvider();
/**
* Gets the bridge.
* @return the bridge
*/
XBridge getBridge();
/**
* Gets the remote service manager.
* @return the remote service manager
*/
XMultiComponentFactory getRemoteServiceManager();
/**
* Gets the component context.
* @return the component context
*/
XComponentContext getComponentContext();
}
| 1,455 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TerminateListener.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconnect/TerminateListener.java | /**
* TerminateListener.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconnect;
import com.sun.star.frame.TerminationVetoException;
import com.sun.star.frame.XTerminateListener;
/**
* The listener interface for receiving terminate events. The class that is interested in processing a terminate event
* implements this interface, and the object created with that class is registered with a component using the
* component's <code>addTerminateListener</code> method. When the terminate event occurs, that object's appropriate
* method is invoked.
* @see TerminateEvent
*/
public class TerminateListener implements XTerminateListener {
/**
* (non-Javadoc).
* @param eventObject
* the event object
* @see com.sun.star.frame.XTerminateListener#notifyTermination(com.sun.star.lang.EventObject)
*/
public void notifyTermination(com.sun.star.lang.EventObject eventObject) {
System.out.println("about to terminate..."); //$NON-NLS-1$
}
/**
* (non-Javadoc).
* @param eventObject
* the event object
* @throws TerminationVetoException
* the termination veto exception
* @see com.sun.star.frame.XTerminateListener#queryTermination(com.sun.star.lang.EventObject)
*/
public void queryTermination(com.sun.star.lang.EventObject eventObject) throws TerminationVetoException {
if (TerminationOpenoffice.isAtWork()) {
System.out.println("Terminate while we are at work? No way!"); //$NON-NLS-1$
throw new TerminationVetoException(); // this will veto the
// termination,
}
}
/**
* (non-Javadoc).
* @param eventObject
* the event object
* @see com.sun.star.lang.XEventListener#disposing(com.sun.star.lang.EventObject)
*/
public void disposing(com.sun.star.lang.EventObject eventObject) {
}
} | 1,863 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OPException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconnect/OPException.java | /**
* OPException.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconnect;
/**
* The Class OPException.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class OPException extends RuntimeException {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/**
* Instantiates a new oP exception.
* @param message
* the message
*/
public OPException(String message) {
super(message);
}
/**
* Instantiates a new oP exception.
* @param message
* the message
* @param cause
* the cause
*/
public OPException(String message, Throwable cause) {
super(message, cause);
}
} | 751 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
PPOPConnection.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconnect/PPOPConnection.java | /**
* PPOPConnection.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconnect;
/**
* The Class PPOPConnection.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class PPOPConnection extends OPConnection {
/** The Constant DEFAULT_PIPE_NAME. */
public static final String DEFAULT_PIPE_NAME = "heartsomeconverter"; //$NON-NLS-1$
/**
* Instantiates a new pPOP connection.
*/
public PPOPConnection() {
this(DEFAULT_PIPE_NAME);
}
/**
* Instantiates a new pPOP connection.
* @param pipeName
* the pipe name
*/
public PPOPConnection(String pipeName) {
super("pipe,name=" + pipeName); //$NON-NLS-1$
}
}
| 722 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractOpenOfficeDocumentConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/AbstractOpenOfficeDocumentConverter.java | /**
* AbstractOpenOfficeDocumentConverter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import net.heartsome.cat.converter.msoffice2003.resource.Messages;
import net.heartsome.cat.converter.ooconnect.OPConnection;
import net.heartsome.cat.converter.ooconverter.impl.DefaultDocumentFormatRegistry;
import net.heartsome.cat.converter.ooconverter.impl.DocumentFormat;
import org.apache.commons.io.FilenameUtils;
import com.sun.star.beans.PropertyValue;
import com.sun.star.lang.XComponent;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.XRefreshable;
/**
* The Class AbstractOpenOfficeDocumentConverter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public abstract class AbstractOpenOfficeDocumentConverter implements DOCConverter {
/** The default load properties. */
@SuppressWarnings("unchecked")
private final Map/* <String,Object> */defaultLoadProperties;
/** The open office connection. */
protected OPConnection openOfficeConnection;
/** The document format registry. */
private DocumentFormatRegistry documentFormatRegistry;
/**
* Instantiates a new abstract open office document converter.
* @param connection
* the connection
*/
public AbstractOpenOfficeDocumentConverter(OPConnection connection) {
this(connection, new DefaultDocumentFormatRegistry());
}
/**
* Instantiates a new abstract open office document converter.
* @param openOfficeConnection
* the open office connection
* @param documentFormatRegistry
* the document format registry
*/
@SuppressWarnings("unchecked")
public AbstractOpenOfficeDocumentConverter(OPConnection openOfficeConnection,
DocumentFormatRegistry documentFormatRegistry) {
this.openOfficeConnection = openOfficeConnection;
this.documentFormatRegistry = documentFormatRegistry;
defaultLoadProperties = new HashMap();
defaultLoadProperties.put("Hidden", Boolean.TRUE); //$NON-NLS-1$
defaultLoadProperties.put("ReadOnly", Boolean.TRUE); //$NON-NLS-1$
}
/**
* Sets the default load property.
* @param name
* the name
* @param value
* the value
*/
@SuppressWarnings("unchecked")
public void setDefaultLoadProperty(String name, Object value) {
defaultLoadProperties.put(name, value);
}
/**
* Gets the default load properties.
* @return the default load properties
*/
@SuppressWarnings("unchecked")
protected Map getDefaultLoadProperties() {
return defaultLoadProperties;
}
/**
* Gets the document format registry.
* @return the document format registry
*/
protected DocumentFormatRegistry getDocumentFormatRegistry() {
return documentFormatRegistry;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.DOCConverter#convert(java.io.File, java.io.File)
* @param inputFile
* @param outputFile
* @throws Exception
*/
public void convert(File inputFile, File outputFile) throws Exception {
convert(inputFile, outputFile, null);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.DOCConverter#convert(java.io.File, java.io.File,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat)
* @param inputFile
* @param outputFile
* @param outputFormat
* @throws Exception
*/
public void convert(File inputFile, File outputFile, DocumentFormat outputFormat) throws Exception {
convert(inputFile, null, outputFile, outputFormat);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.DOCConverter#convert(java.io.InputStream,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat, java.io.OutputStream,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat)
* @param inputStream
* @param inputFormat
* @param outputStream
* @param outputFormat
* @throws Exception
*/
public void convert(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream,
DocumentFormat outputFormat) throws Exception {
ensureNotNull(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.6"), inputStream); //$NON-NLS-1$
ensureNotNull(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.7"), inputFormat); //$NON-NLS-1$
ensureNotNull(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.8"), outputStream); //$NON-NLS-1$
ensureNotNull(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.9"), outputFormat); //$NON-NLS-1$
convertInternal(inputStream, inputFormat, outputStream, outputFormat);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.DOCConverter#convert(java.io.File,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat, java.io.File,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat)
* @param inputFile
* @param inputFormat
* @param outputFile
* @param outputFormat
* @throws Exception
*/
public void convert(File inputFile, DocumentFormat inputFormat, File outputFile, DocumentFormat outputFormat)
throws Exception {
ensureNotNull(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.10"), inputFile); //$NON-NLS-1$
ensureNotNull(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.11"), outputFile); //$NON-NLS-1$
if (!inputFile.exists()) {
throw new IllegalArgumentException(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.12") + inputFile); //$NON-NLS-1$
}
if (inputFormat == null) {
inputFormat = guessDocumentFormat(inputFile);
}
if (outputFormat == null) {
outputFormat = guessDocumentFormat(outputFile);
}
if (!inputFormat.isImportable()) {
throw new IllegalArgumentException(
Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.13") + inputFormat.getName()); //$NON-NLS-1$
}
if (!inputFormat.isExportableTo(outputFormat)) {
MessageFormat mf = new MessageFormat(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.14")); //$NON-NLS-1$
Object[] args = new Object[] { inputFormat.getName(), outputFormat.getName() };
String errMsg = mf.format(args);
args = null;
throw new IllegalArgumentException(errMsg);
}
convertInternal(inputFile, inputFormat, outputFile, outputFormat);
}
/**
* Convert internal.
* @param inputStream
* the input stream
* @param inputFormat
* the input format
* @param outputStream
* the output stream
* @param outputFormat
* the output format
* @throws Exception
* the exception
*/
protected abstract void convertInternal(InputStream inputStream, DocumentFormat inputFormat,
OutputStream outputStream, DocumentFormat outputFormat) throws Exception;
/**
* Convert internal.
* @param inputFile
* the input file
* @param inputFormat
* the input format
* @param outputFile
* the output file
* @param outputFormat
* the output format
* @throws Exception
* the exception
*/
protected abstract void convertInternal(File inputFile, DocumentFormat inputFormat, File outputFile,
DocumentFormat outputFormat) throws Exception;
/**
* Ensure not null.
* @param argumentName
* the argument name
* @param argumentValue
* the argument value
*/
private void ensureNotNull(String argumentName, Object argumentValue) {
if (argumentValue == null) {
throw new IllegalArgumentException(argumentName
+ Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.15")); //$NON-NLS-1$
}
}
/**
* Guess document format.
* @param file
* the file
* @return the document format
*/
private DocumentFormat guessDocumentFormat(File file) {
String extension = FilenameUtils.getExtension(file.getName());
DocumentFormat format = getDocumentFormatRegistry().getFormatByFileExtension(extension);
if (format == null) {
throw new IllegalArgumentException(Messages.getString("ooconverter.AbstractOpenOfficeDocumentConverter.16") + file); //$NON-NLS-1$
}
return format;
}
/**
* Refresh document.
* @param document
* the document
*/
protected void refreshDocument(XComponent document) {
XRefreshable refreshable = (XRefreshable) UnoRuntime.queryInterface(XRefreshable.class, document);
if (refreshable != null) {
refreshable.refresh();
}
}
/**
* Property.
* @param name
* the name
* @param value
* the value
* @return the property value
*/
protected static PropertyValue property(String name, Object value) {
PropertyValue property = new PropertyValue();
property.Name = name;
property.Value = value;
return property;
}
/**
* To property values.
* @param properties
* the properties
* @return the property value[]
*/
@SuppressWarnings("unchecked")
protected static PropertyValue[] toPropertyValues(Map/* <String,Object> */properties) {
PropertyValue[] propertyValues = new PropertyValue[properties.size()];
int i = 0;
for (Iterator iter = properties.entrySet().iterator(); iter.hasNext();) {
Map.Entry entry = (Map.Entry) iter.next();
Object value = entry.getValue();
if (value instanceof Map) {
// recursively convert nested Map to PropertyValue[]
Map subProperties = (Map) value;
value = toPropertyValues(subProperties);
}
propertyValues[i++] = property((String) entry.getKey(), value);
}
return propertyValues;
}
}
| 9,744 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DocumentFormatRegistry.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/DocumentFormatRegistry.java | /**
* DocumentFormatRegistry.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter;
import net.heartsome.cat.converter.ooconverter.impl.DocumentFormat;
/**
* The Interface DocumentFormatRegistry.
* @author John Zhu
* @version
* @since JDK1.6
*/
public interface DocumentFormatRegistry {
/**
* Gets the format by file extension.
* @param extension
* the extension
* @return the format by file extension
*/
DocumentFormat getFormatByFileExtension(String extension);
/**
* Gets the format by mime type.
* @param extension
* the extension
* @return the format by mime type
*/
DocumentFormat getFormatByMimeType(String extension);
}
| 765 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DOCConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/DOCConverter.java | /**
* DOCConverter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import net.heartsome.cat.converter.ooconverter.impl.DocumentFormat;
/**
* The Interface DOCConverter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public interface DOCConverter {
/**
* Convert a document.
* <p>
* Note that this method does not close <tt>inputStream</tt> and <tt>outputStream</tt>.
* @param inputStream
* the input stream
* @param inputFormat
* the input format
* @param outputStream
* the output stream
* @param outputFormat
* the output format
* @throws Exception
* the exception
*/
void convert(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream,
DocumentFormat outputFormat) throws Exception;
/**
* Convert a document.
* @param inputFile
* the input file
* @param inputFormat
* the input format
* @param outputFile
* the output file
* @param outputFormat
* the output format
* @throws Exception
* the exception
*/
void convert(File inputFile, DocumentFormat inputFormat, File outputFile, DocumentFormat outputFormat)
throws Exception;
/**
* Convert a document. The input format is guessed from the file extension.
* @param inputDocument
* the input document
* @param outputDocument
* the output document
* @param outputFormat
* the output format
* @throws Exception
* the exception
*/
void convert(File inputDocument, File outputDocument, DocumentFormat outputFormat) throws Exception;
/**
* Convert a document. Both input and output formats are guessed from the file extension.
* @param inputDocument
* the input document
* @param outputDocument
* the output document
* @throws Exception
* the exception
*/
void convert(File inputDocument, File outputDocument) throws Exception;
}
| 2,173 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenOfficeDocumentConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/OpenOfficeDocumentConverter.java | /**
* OpenOfficeDocumentConverter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.msoffice2003.resource.Messages;
import net.heartsome.cat.converter.ooconnect.OPConnection;
import net.heartsome.cat.converter.ooconnect.OPException;
import net.heartsome.cat.converter.ooconverter.impl.DocumentFormat;
import org.apache.commons.io.IOUtils;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.IllegalArgumentException;
import com.sun.star.lang.XComponent;
import com.sun.star.ucb.XFileIdentifierConverter;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.util.CloseVetoException;
import com.sun.star.util.XCloseable;
/**
* The Class OpenOfficeDocumentConverter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class OpenOfficeDocumentConverter extends AbstractOpenOfficeDocumentConverter {
// private static final Logger logger =
// LoggerFactory.getLogger(OpenOfficeDocumentConverter.class);
/**
* Instantiates a new open office document converter.
* @param connection
* the connection
*/
public OpenOfficeDocumentConverter(OPConnection connection) {
super(connection);
}
/**
* Instantiates a new open office document converter.
* @param connection
* the connection
* @param formatRegistry
* the format registry
*/
public OpenOfficeDocumentConverter(OPConnection connection, DocumentFormatRegistry formatRegistry) {
super(connection, formatRegistry);
}
/**
* In this file-based implementation, streams are emulated using temporary files.
* @param inputStream
* the input stream
* @param inputFormat
* the input format
* @param outputStream
* the output stream
* @param outputFormat
* the output format
* @throws Exception
* the exception
*/
protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream,
DocumentFormat outputFormat) throws Exception {
File inputFile = null;
File outputFile = null;
try {
inputFile = File.createTempFile("document", "." + inputFormat.getFileExtension()); //$NON-NLS-1$ //$NON-NLS-2$
OutputStream inputFileStream = null;
try {
inputFileStream = new FileOutputStream(inputFile);
IOUtils.copy(inputStream, inputFileStream);
} finally {
IOUtils.closeQuietly(inputFileStream);
}
outputFile = File.createTempFile("document", "." + outputFormat.getFileExtension()); //$NON-NLS-1$ //$NON-NLS-2$
convert(inputFile, inputFormat, outputFile, outputFormat);
InputStream outputFileStream = null;
try {
outputFileStream = new FileInputStream(outputFile);
IOUtils.copy(outputFileStream, outputStream);
} finally {
IOUtils.closeQuietly(outputFileStream);
}
} catch (IOException ioException) {
throw new OPException(Messages.getString("ooconverter.OpenOfficeDocumentConverter.4"), ioException); //$NON-NLS-1$
} finally {
if (inputFile != null) {
inputFile.delete();
}
if (outputFile != null) {
outputFile.delete();
}
}
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.AbstractOpenOfficeDocumentConverter#convertInternal(java.io.File,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat, java.io.File,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat)
* @param inputFile
* @param inputFormat
* @param outputFile
* @param outputFormat
* @throws Exception
*/
@SuppressWarnings("unchecked")
protected void convertInternal(File inputFile, DocumentFormat inputFormat, File outputFile,
DocumentFormat outputFormat) throws Exception {
Map/* <String,Object> */loadProperties = new HashMap();
loadProperties.putAll(getDefaultLoadProperties());
loadProperties.putAll(inputFormat.getImportOptions());
Map/* <String,Object> */storeProperties = outputFormat.getExportOptions(inputFormat.getFamily());
synchronized (openOfficeConnection) {
XFileIdentifierConverter fileContentProvider = openOfficeConnection.getFileContentProvider();
String inputUrl = fileContentProvider.getFileURLFromSystemPath("", inputFile.getAbsolutePath()); //$NON-NLS-1$
String outputUrl = fileContentProvider.getFileURLFromSystemPath("", outputFile.getAbsolutePath()); //$NON-NLS-1$
loadAndExport(inputUrl, loadProperties, outputUrl, storeProperties);
}
}
/**
* Load and export.
* @param inputUrl
* the input url
* @param loadProperties
* the load properties
* @param outputUrl
* the output url
* @param storeProperties
* the store properties
* @throws Exception
* the exception
*/
@SuppressWarnings("unchecked")
private void loadAndExport(String inputUrl, Map/* <String,Object> */loadProperties, String outputUrl,
Map/* <String,Object> */storeProperties) throws Exception {
XComponent document;
// try {
document = loadDocument(inputUrl, loadProperties);
// } catch (ErrorCodeIOException errorCodeIOException) {
// throw new
// OPException("conversion failed: could not load input document; OOo errorCode: "
// + errorCodeIOException.ErrCode, errorCodeIOException);
// } catch (Exception otherException) {
// throw new
// OPException("conversion failed: could not load input document",
// otherException);
// }
if (document == null) {
throw new OPException(Messages.getString("ooconverter.OpenOfficeDocumentConverter.9")); //$NON-NLS-1$
}
refreshDocument(document);
// try {
storeDocument(document, outputUrl, storeProperties);
// } catch (ErrorCodeIOException errorCodeIOException) {
// throw new
// OPException("conversion failed: could not save output document; OOo errorCode: "
// + errorCodeIOException.ErrCode, errorCodeIOException);
// } catch (Exception otherException) {
// throw new
// OPException("conversion failed: could not save output document",
// otherException);
// }
}
/**
* Load document.
* @param inputUrl
* the input url
* @param loadProperties
* the load properties
* @return the x component
* @throws IllegalArgumentException
* the illegal argument exception
*/
@SuppressWarnings("unchecked")
private XComponent loadDocument(String inputUrl, Map loadProperties) throws com.sun.star.io.IOException,
IllegalArgumentException {
XComponentLoader desktop = openOfficeConnection.getDesktopObject();
return desktop.loadComponentFromURL(inputUrl, "_blank", 0, toPropertyValues(loadProperties)); //$NON-NLS-1$
}
/**
* Store document.
* @param document
* the document
* @param outputUrl
* the output url
* @param storeProperties
* the store properties
*/
@SuppressWarnings("unchecked")
private void storeDocument(XComponent document, String outputUrl, Map storeProperties)
throws com.sun.star.io.IOException {
try {
XStorable storable = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
storable.storeToURL(outputUrl, toPropertyValues(storeProperties));
} finally {
XCloseable closeable = (XCloseable) UnoRuntime.queryInterface(XCloseable.class, document);
if (closeable != null) {
try {
closeable.close(true);
} catch (CloseVetoException closeVetoException) {
if (Converter.DEBUG_MODE) {
closeVetoException.printStackTrace();
}
}
} else {
document.dispose();
}
}
}
}
| 7,871 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StreamOpenOfficeDocumentConverter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/StreamOpenOfficeDocumentConverter.java | /**
* StreamOpenOfficeDocumentConverter.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.msoffice2003.resource.Messages;
import net.heartsome.cat.converter.ooconnect.OPConnection;
import net.heartsome.cat.converter.ooconnect.OPException;
import net.heartsome.cat.converter.ooconverter.impl.DocumentFormat;
import org.apache.commons.io.IOUtils;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lib.uno.adapter.ByteArrayToXInputStreamAdapter;
import com.sun.star.lib.uno.adapter.OutputStreamToXOutputStreamAdapter;
import com.sun.star.uno.UnoRuntime;
/**
* The Class StreamOpenOfficeDocumentConverter.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class StreamOpenOfficeDocumentConverter extends AbstractOpenOfficeDocumentConverter {
/**
* Instantiates a new stream open office document converter.
* @param connection
* the connection
*/
public StreamOpenOfficeDocumentConverter(OPConnection connection) {
super(connection);
}
/**
* Instantiates a new stream open office document converter.
* @param connection
* the connection
* @param formatRegistry
* the format registry
*/
public StreamOpenOfficeDocumentConverter(OPConnection connection, DocumentFormatRegistry formatRegistry) {
super(connection, formatRegistry);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.AbstractOpenOfficeDocumentConverter#convertInternal(java.io.File,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat, java.io.File,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat)
* @param inputFile
* @param inputFormat
* @param outputFile
* @param outputFormat
* @throws Exception
*/
protected void convertInternal(File inputFile, DocumentFormat inputFormat, File outputFile,
DocumentFormat outputFormat) throws Exception {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(inputFile);
outputStream = new FileOutputStream(outputFile);
convert(inputStream, inputFormat, outputStream, outputFormat);
} catch (FileNotFoundException fileNotFoundException) {
throw new IllegalArgumentException(fileNotFoundException.getMessage());
} finally {
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
}
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.AbstractOpenOfficeDocumentConverter#convertInternal(java.io.InputStream,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat, java.io.OutputStream,
* net.heartsome.cat.converter.ooconverter.impl.DocumentFormat)
* @param inputStream
* @param inputFormat
* @param outputStream
* @param outputFormat
*/
@SuppressWarnings("unchecked")
protected void convertInternal(InputStream inputStream, DocumentFormat inputFormat, OutputStream outputStream,
DocumentFormat outputFormat) {
Map/* <String,Object> */exportOptions = outputFormat.getExportOptions(inputFormat.getFamily());
try {
synchronized (openOfficeConnection) {
loadAndExport(inputStream, inputFormat.getImportOptions(), outputStream, exportOptions);
}
} catch (OPException openOfficeException) {
throw openOfficeException;
} catch (Throwable throwable) {
throw new OPException(Messages.getString("ooconverter.StreamOpenOfficeDocumentConverter.1"), throwable); //$NON-NLS-1$
}
}
/**
* Load and export.
* @param inputStream
* the input stream
* @param importOptions
* the import options
* @param outputStream
* the output stream
* @param exportOptions
* the export options
* @throws Exception
* the exception
*/
@SuppressWarnings("unchecked")
private void loadAndExport(InputStream inputStream, Map/* <String,Object> */importOptions,
OutputStream outputStream, Map/* <String,Object> */exportOptions) throws Exception {
XComponentLoader desktop = openOfficeConnection.getDesktopObject();
Map/* <String,Object> */loadProperties = new HashMap();
loadProperties.putAll(getDefaultLoadProperties());
loadProperties.putAll(importOptions);
// doesn't work using InputStreamToXInputStreamAdapter; probably because
// it's not XSeekable
// property("InputStream", new
// InputStreamToXInputStreamAdapter(inputStream))
loadProperties.put("InputStream", new ByteArrayToXInputStreamAdapter(IOUtils.toByteArray(inputStream))); //$NON-NLS-1$
XComponent document = desktop.loadComponentFromURL(
"private:stream", "_blank", 0, toPropertyValues(loadProperties)); //$NON-NLS-1$ //$NON-NLS-2$
if (document == null) {
throw new OPException(Messages.getString("ooconverter.StreamOpenOfficeDocumentConverter.6")); //$NON-NLS-1$
}
refreshDocument(document);
Map/* <String,Object> */storeProperties = new HashMap();
storeProperties.putAll(exportOptions);
storeProperties.put("OutputStream", new OutputStreamToXOutputStreamAdapter(outputStream)); //$NON-NLS-1$
try {
XStorable storable = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
storable.storeToURL("private:stream", toPropertyValues(storeProperties)); //$NON-NLS-1$
} finally {
document.dispose();
}
}
}
| 5,665 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DocumentFamily.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/impl/DocumentFamily.java | /**
* DocumentFamily.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter.impl;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.msoffice2003.resource.Messages;
/**
* The Class DocumentFamily.
* @author John Zhu
* @version
* @since JDK1.6
*/
@SuppressWarnings("unchecked")
public final class DocumentFamily {
/** The Constant TEXT. */
public static final DocumentFamily TEXT = new DocumentFamily("Text"); //$NON-NLS-1$
/** The Constant SPREADSHEET. */
public static final DocumentFamily SPREADSHEET = new DocumentFamily("Spreadsheet"); //$NON-NLS-1$
/** The Constant PRESENTATION. */
public static final DocumentFamily PRESENTATION = new DocumentFamily("Presentation"); //$NON-NLS-1$
/** The Constant DRAWING. */
public static final DocumentFamily DRAWING = new DocumentFamily("Drawing"); //$NON-NLS-1$
/** The FAMILIES. */
private static Map mapFamilies = new HashMap();
static {
mapFamilies.put(TEXT.name, TEXT);
mapFamilies.put(SPREADSHEET.name, SPREADSHEET);
mapFamilies.put(PRESENTATION.name, PRESENTATION);
mapFamilies.put(DRAWING.name, DRAWING);
}
/** The name. */
private String name;
/**
* Instantiates a new document family.
* @param name
* the name
*/
private DocumentFamily(String name) {
this.name = name;
}
/**
* Gets the name.
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the family.
* @param name
* the name
* @return the family
*/
public static DocumentFamily getFamily(String name) {
DocumentFamily family = (DocumentFamily) mapFamilies.get(name);
if (family == null) {
throw new IllegalArgumentException(Messages.getString("impl.DocumentFamily.0") + name); //$NON-NLS-1$
}
return family;
}
} | 1,864 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DefaultDocumentFormatRegistry.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/impl/DefaultDocumentFormatRegistry.java | /**
* DefaultDocumentFormatRegistry.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter.impl;
/**
* The Class DefaultDocumentFormatRegistry.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class DefaultDocumentFormatRegistry extends BasicDocumentFormatRegistry {
/**
* Instantiates a new default document format registry.
*/
public DefaultDocumentFormatRegistry() {
final DocumentFormat pdf = new DocumentFormat("Portable Document Format", "application/pdf", "pdf"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
pdf.setExportFilter(DocumentFamily.DRAWING, "draw_pdf_Export"); //$NON-NLS-1$
pdf.setExportFilter(DocumentFamily.PRESENTATION, "impress_pdf_Export"); //$NON-NLS-1$
pdf.setExportFilter(DocumentFamily.SPREADSHEET, "calc_pdf_Export"); //$NON-NLS-1$
pdf.setExportFilter(DocumentFamily.TEXT, "writer_pdf_Export"); //$NON-NLS-1$
addDocumentFormat(pdf);
final DocumentFormat swf = new DocumentFormat("Macromedia Flash", "application/x-shockwave-flash", "swf"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
swf.setExportFilter(DocumentFamily.DRAWING, "draw_flash_Export"); //$NON-NLS-1$
swf.setExportFilter(DocumentFamily.PRESENTATION, "impress_flash_Export"); //$NON-NLS-1$
addDocumentFormat(swf);
final DocumentFormat xhtml = new DocumentFormat("XHTML", "application/xhtml+xml", "xhtml"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
xhtml.setExportFilter(DocumentFamily.PRESENTATION, "XHTML Impress File"); //$NON-NLS-1$
xhtml.setExportFilter(DocumentFamily.SPREADSHEET, "XHTML Calc File"); //$NON-NLS-1$
xhtml.setExportFilter(DocumentFamily.TEXT, "XHTML Writer File"); //$NON-NLS-1$
addDocumentFormat(xhtml);
// HTML is treated as Text when supplied as input, but as an output it
// is also
// available for exporting Spreadsheet and Presentation formats
final DocumentFormat html = new DocumentFormat("HTML", DocumentFamily.TEXT, "text/html", "html"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
html.setExportFilter(DocumentFamily.PRESENTATION, "impress_html_Export"); //$NON-NLS-1$
html.setExportFilter(DocumentFamily.SPREADSHEET, "HTML (StarCalc)"); //$NON-NLS-1$
html.setExportFilter(DocumentFamily.TEXT, "HTML (StarWriter)"); //$NON-NLS-1$
addDocumentFormat(html);
final DocumentFormat odt = new DocumentFormat(
"OpenDocument Text", DocumentFamily.TEXT, "application/vnd.oasis.opendocument.text", "odt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
odt.setExportFilter(DocumentFamily.TEXT, "writer8"); //$NON-NLS-1$
addDocumentFormat(odt);
final DocumentFormat sxw = new DocumentFormat(
"OpenOffice.org 1.0 Text Document", DocumentFamily.TEXT, "application/vnd.sun.xml.writer", "sxw"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
sxw.setExportFilter(DocumentFamily.TEXT, "StarOffice XML (Writer)"); //$NON-NLS-1$
addDocumentFormat(sxw);
final DocumentFormat doc = new DocumentFormat(
"Microsoft Word", DocumentFamily.TEXT, "application/msword", "doc"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
doc.setExportFilter(DocumentFamily.TEXT, "MS Word 97"); //$NON-NLS-1$
addDocumentFormat(doc);
final DocumentFormat rtf = new DocumentFormat("Rich Text Format", DocumentFamily.TEXT, "text/rtf", "rtf"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
rtf.setExportFilter(DocumentFamily.TEXT, "Rich Text Format"); //$NON-NLS-1$
addDocumentFormat(rtf);
final DocumentFormat wpd = new DocumentFormat(
"WordPerfect", DocumentFamily.TEXT, "application/wordperfect", "wpd"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
addDocumentFormat(wpd);
final DocumentFormat txt = new DocumentFormat("Plain Text", DocumentFamily.TEXT, "text/plain", "txt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// set FilterName to "Text" to prevent OOo from tryign to display the
// "ASCII Filter Options" dialog
// alternatively FilterName could be "Text (encoded)" and FilterOptions
// used to set encoding if needed
txt.setImportOption("FilterName", "Text"); //$NON-NLS-1$ //$NON-NLS-2$
txt.setExportFilter(DocumentFamily.TEXT, "Text"); //$NON-NLS-1$
addDocumentFormat(txt);
final DocumentFormat wikitext = new DocumentFormat("MediaWiki wikitext", "text/x-wiki", "wiki"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
wikitext.setExportFilter(DocumentFamily.TEXT, "MediaWiki"); //$NON-NLS-1$
addDocumentFormat(wikitext);
final DocumentFormat ods = new DocumentFormat(
"OpenDocument Spreadsheet", DocumentFamily.SPREADSHEET, "application/vnd.oasis.opendocument.spreadsheet", "ods"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ods.setExportFilter(DocumentFamily.SPREADSHEET, "calc8"); //$NON-NLS-1$
addDocumentFormat(ods);
final DocumentFormat sxc = new DocumentFormat(
"OpenOffice.org 1.0 Spreadsheet", DocumentFamily.SPREADSHEET, "application/vnd.sun.xml.calc", "sxc"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
sxc.setExportFilter(DocumentFamily.SPREADSHEET, "StarOffice XML (Calc)"); //$NON-NLS-1$
addDocumentFormat(sxc);
final DocumentFormat xls = new DocumentFormat(
"Microsoft Excel", DocumentFamily.SPREADSHEET, "application/vnd.ms-excel", "xls"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
xls.setExportFilter(DocumentFamily.SPREADSHEET, "MS Excel 97"); //$NON-NLS-1$
addDocumentFormat(xls);
final DocumentFormat csv = new DocumentFormat("CSV", DocumentFamily.SPREADSHEET, "text/csv", "csv"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
csv.setImportOption("FilterName", "Text - txt - csv (StarCalc)"); //$NON-NLS-1$ //$NON-NLS-2$
csv.setImportOption("FilterOptions", "44,34,0"); // Field Separator: ','; Text Delimiter: '"' //$NON-NLS-1$ //$NON-NLS-2$
csv.setExportFilter(DocumentFamily.SPREADSHEET, "Text - txt - csv (StarCalc)"); //$NON-NLS-1$
csv.setExportOption(DocumentFamily.SPREADSHEET, "FilterOptions", "44,34,0"); //$NON-NLS-1$ //$NON-NLS-2$
addDocumentFormat(csv);
final DocumentFormat tsv = new DocumentFormat(
"Tab-separated Values", DocumentFamily.SPREADSHEET, "text/tab-separated-values", "tsv"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
tsv.setImportOption("FilterName", "Text - txt - csv (StarCalc)"); //$NON-NLS-1$ //$NON-NLS-2$
tsv.setImportOption("FilterOptions", "9,34,0"); // Field Separator: '\t'; Text Delimiter: '"' //$NON-NLS-1$ //$NON-NLS-2$
tsv.setExportFilter(DocumentFamily.SPREADSHEET, "Text - txt - csv (StarCalc)"); //$NON-NLS-1$
tsv.setExportOption(DocumentFamily.SPREADSHEET, "FilterOptions", "9,34,0"); //$NON-NLS-1$ //$NON-NLS-2$
addDocumentFormat(tsv);
final DocumentFormat odp = new DocumentFormat(
"OpenDocument Presentation", DocumentFamily.PRESENTATION, "application/vnd.oasis.opendocument.presentation", "odp"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
odp.setExportFilter(DocumentFamily.PRESENTATION, "impress8"); //$NON-NLS-1$
addDocumentFormat(odp);
final DocumentFormat sxi = new DocumentFormat(
"OpenOffice.org 1.0 Presentation", DocumentFamily.PRESENTATION, "application/vnd.sun.xml.impress", "sxi"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
sxi.setExportFilter(DocumentFamily.PRESENTATION, "StarOffice XML (Impress)"); //$NON-NLS-1$
addDocumentFormat(sxi);
final DocumentFormat ppt = new DocumentFormat(
"Microsoft PowerPoint", DocumentFamily.PRESENTATION, "application/vnd.ms-powerpoint", "ppt"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ppt.setExportFilter(DocumentFamily.PRESENTATION, "MS PowerPoint 97"); //$NON-NLS-1$
addDocumentFormat(ppt);
final DocumentFormat odg = new DocumentFormat(
"OpenDocument Drawing", DocumentFamily.DRAWING, "application/vnd.oasis.opendocument.graphics", "odg"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
odg.setExportFilter(DocumentFamily.DRAWING, "draw8"); //$NON-NLS-1$
addDocumentFormat(odg);
final DocumentFormat svg = new DocumentFormat("Scalable Vector Graphics", "image/svg+xml", "svg"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
svg.setExportFilter(DocumentFamily.DRAWING, "draw_svg_Export"); //$NON-NLS-1$
addDocumentFormat(svg);
}
}
| 8,033 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
BasicDocumentFormatRegistry.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/impl/BasicDocumentFormatRegistry.java | /**
* BasicDocumentFormatRegistry.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter.impl;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import net.heartsome.cat.converter.ooconverter.DocumentFormatRegistry;
/**
* The Class BasicDocumentFormatRegistry.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
/** The document formats. */
private List documentFormats = new LinkedList();
/**
* Adds the document format.
* @param documentFormat
* the document format
*/
public void addDocumentFormat(DocumentFormat documentFormat) {
documentFormats.add(documentFormat);
}
/**
* Gets the document formats.
* @return the document formats
*/
protected List getDocumentFormats() {
return documentFormats;
}
/**
* Gets the format by file extension.
* @param extension
* the file extension
* @return the DocumentFormat for this extension, or null if the extension is not mapped
*/
public DocumentFormat getFormatByFileExtension(String extension) {
if (extension == null) {
return null;
}
String lowerExtension = extension.toLowerCase();
for (Iterator it = documentFormats.iterator(); it.hasNext();) {
DocumentFormat format = (DocumentFormat) it.next();
if (format.getFileExtension().equals(lowerExtension)) {
return format;
}
}
return null;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.ooconverter.DocumentFormatRegistry#getFormatByMimeType(java.lang.String)
* @param mimeType
* @return
*/
public DocumentFormat getFormatByMimeType(String mimeType) {
for (Iterator it = documentFormats.iterator(); it.hasNext();) {
DocumentFormat format = (DocumentFormat) it.next();
if (format.getMimeType().equals(mimeType)) {
return format;
}
}
return null;
}
}
| 1,973 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DocumentFormat.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msoffice2003/src/net/heartsome/cat/converter/ooconverter/impl/DocumentFormat.java | /**
* DocumentFormat.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ooconverter.impl;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a document format ("OpenDocument Text" or "PDF"). Also contains its available export filters.
*/
public class DocumentFormat {
/** The Constant FILTER_NAME. */
private static final String FILTER_NAME = "FilterName"; //$NON-NLS-1$
/** The name. */
private String name;
/** The family. */
private DocumentFamily family;
/** The mime type. */
private String mimeType;
/** The file extension. */
private String fileExtension;
/** The export options. */
@SuppressWarnings("unchecked")
private Map exportOptions = new HashMap();
/** The import options. */
@SuppressWarnings("unchecked")
private Map importOptions = new HashMap();
/**
* Instantiates a new document format.
*/
public DocumentFormat() {
// empty constructor needed for XStream deserialization
}
/**
* Instantiates a new document format.
* @param name
* the name
* @param mimeType
* the mime type
* @param extension
* the extension
*/
public DocumentFormat(String name, String mimeType, String extension) {
this.name = name;
this.mimeType = mimeType;
this.fileExtension = extension;
}
/**
* Instantiates a new document format.
* @param name
* the name
* @param family
* the family
* @param mimeType
* the mime type
* @param extension
* the extension
*/
public DocumentFormat(String name, DocumentFamily family, String mimeType, String extension) {
this.name = name;
this.family = family;
this.mimeType = mimeType;
this.fileExtension = extension;
}
/**
* Gets the name.
* @return the name
*/
public String getName() {
return name;
}
/**
* Gets the family.
* @return the family
*/
public DocumentFamily getFamily() {
return family;
}
/**
* Gets the mime type.
* @return the mime type
*/
public String getMimeType() {
return mimeType;
}
/**
* Gets the file extension.
* @return the file extension
*/
public String getFileExtension() {
return fileExtension;
}
/**
* Gets the export filter.
* @param family
* the family
* @return the export filter
*/
private String getExportFilter(DocumentFamily family) {
return (String) getExportOptions(family).get(FILTER_NAME);
}
/**
* Checks if is importable.
* @return true, if is importable
*/
public boolean isImportable() {
return family != null;
}
/**
* Checks if is export only.
* @return true, if is export only
*/
public boolean isExportOnly() {
return !isImportable();
}
/**
* Checks if is exportable to.
* @param otherFormat
* the other format
* @return true, if is exportable to
*/
public boolean isExportableTo(DocumentFormat otherFormat) {
return otherFormat.isExportableFrom(this.family);
}
/**
* Checks if is exportable from.
* @param family
* the family
* @return true, if is exportable from
*/
public boolean isExportableFrom(DocumentFamily family) {
return getExportFilter(family) != null;
}
/**
* Sets the export filter.
* @param family
* the family
* @param filter
* the filter
*/
public void setExportFilter(DocumentFamily family, String filter) {
getExportOptions(family).put(FILTER_NAME, filter);
}
/**
* Sets the export option.
* @param family
* the family
* @param name
* the name
* @param value
* the value
*/
public void setExportOption(DocumentFamily family, String name, Object value) {
Map options = (Map) exportOptions.get(family);
if (options == null) {
options = new HashMap();
exportOptions.put(family, options);
}
options.put(name, value);
}
/**
* Gets the export options.
* @param family
* the family
* @return the export options
*/
public Map getExportOptions(DocumentFamily family) {
Map options = (Map) exportOptions.get(family);
if (options == null) {
options = new HashMap();
exportOptions.put(family, options);
}
return options;
}
/**
* Sets the import option.
* @param name
* the name
* @param value
* the value
*/
public void setImportOption(String name, Object value) {
importOptions.put(name, value);
}
/**
* Gets the import options.
* @return the import options
*/
public Map getImportOptions() {
if (importOptions != null) {
return importOptions;
} else {
return Collections.EMPTY_MAP;
}
}
} | 4,720 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2PoTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.po/testSrc/net/heartsome/cat/converter/po/test/Xliff2PoTest.java | package net.heartsome.cat.converter.po.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.po.Xliff2Po;
import org.junit.Before;
import org.junit.Test;
public class Xliff2PoTest {
public static Xliff2Po converter = new Xliff2Po();
private static String tgtFile = "rc/Test_zh-CN.po";
private static String xlfFile = "rc/Test.po.xlf";
private static String sklFile = "rc/Test.po.skl";
@Before
public void setUp() {
File tgt = new File(tgtFile);
if (tgt.exists()) {
tgt.delete();
}
}
@Test
public void testConvert() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8");
Map<String, String> result = converter.convert(args, null);
String target = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(target);
File tgtFile = new File(target);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
}
| 1,363 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Po2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.po/testSrc/net/heartsome/cat/converter/po/test/Po2XliffTest.java | package net.heartsome.cat.converter.po.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.po.Po2Xliff;
import org.junit.Before;
import org.junit.Test;
public class Po2XliffTest {
public static Po2Xliff converter = new Po2Xliff();
private static String srcFile = "rc/Test.po";
private static String xlfFile = "rc/Test.po.xlf";
private static String sklFile = "rc/Test.po.skl";
@Before
public void setUp(){
File skl = new File(sklFile);
if(skl.exists()){
skl.delete();
}
File xlf = new File(xlfFile);
if(xlf.exists()){
xlf.delete();
}
}
@Test(timeout = 10000)
public void testConvert() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "en-US"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
}
| 1,526 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Po2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.po/src/net/heartsome/cat/converter/po/Po2Xliff.java | /**
* Po2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.po;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.po.resource.Messages;
import net.heartsome.cat.converter.util.CalculateProcessedBytes;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.util.CRC16;
import net.heartsome.util.TextUtil;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
/**
* The Class Po2Xliff.
* @author John Zhu
*/
public class Po2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "po";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("po.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "PO to XLIFF Conveter";
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Po2XliffImpl converter = new Po2XliffImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getName()
* @return
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getType()
* @return
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getTypeName()
* @return
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* The Class Po2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Po2XliffImpl {
/** The input. */
private InputStreamReader input;
/** The output. */
private FileOutputStream output;
/** The skeleton. */
private FileOutputStream skeleton;
/** The buffer. */
private BufferedReader buffer;
/** The input file. */
private String inputFile;
/** The xliff file. */
private String xliffFile;
/** The skeleton file. */
private String skeletonFile;
/** The source. */
private String source;
/** The target. */
private String target;
/** The comment. */
private String comment;
/** The context. */
private String context;
/** The reference. */
private String reference;
/** The flags. */
private String flags;
/** The fuzzy. */
private boolean fuzzy;
/** The cformat. */
private boolean cformat;
/** The in domain. */
private boolean inDomain;
/** The source language. */
private String sourceLanguage;
private String targetLanguage;
/** The seg id. */
private int segId;
/** The domain id. */
private int domainId;
/** The context id. */
private int contextId = 1;
/** The ref id. */
private int refId = 1;
/**
* Run.
* @param params
* the params
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
Map<String, String> result = new HashMap<String, String>();
inputFile = params.get(Converter.ATTR_SOURCE_FILE);
xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
skeletonFile = params.get(Converter.ATTR_SKELETON_FILE);
sourceLanguage = params.get(Converter.ATTR_SOURCE_LANGUAGE);
targetLanguage = params.get(Converter.ATTR_TARGET_LANGUAGE);
String srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING);
boolean isSuite = false;
if (Converter.TRUE.equalsIgnoreCase(params.get(Converter.ATTR_IS_SUITE))) {
isSuite = true;
}
String qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID)
: Converter.QT_TOOLID_DEFAULT_VALUE;
source = ""; //$NON-NLS-1$
target = ""; //$NON-NLS-1$
comment = ""; //$NON-NLS-1$
context = ""; //$NON-NLS-1$
reference = ""; //$NON-NLS-1$
flags = ""; //$NON-NLS-1$
fuzzy = false;
inDomain = false;
cformat = false;
try {
// 计算总任务数
CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(inputFile);
monitor.beginTask(Messages.getString("po.Po2Xliff.task1"), cpb.getTotalTask());
monitor.subTask("");
FileInputStream stream = new FileInputStream(inputFile);
input = new InputStreamReader(stream, srcEncoding);
buffer = new BufferedReader(input);
output = new FileOutputStream(xliffFile);
writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); //$NON-NLS-1$
writeString("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " + //$NON-NLS-1$
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\""
+ Converter.HSNAMESPACE + "\" " + //$NON-NLS-1$
"xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " //$NON-NLS-1$
+ Converter.HSSCHEMALOCATION + "\">\n"); //$NON-NLS-1$
if (!"".equals(targetLanguage)) {
writeString("<file original=\"" + inputFile //$NON-NLS-1$
+ "\" source-language=\"" + sourceLanguage //$NON-NLS-1$
+ "\" target-language=\""+targetLanguage+"\" datatype=\"" + TYPE_VALUE + "\">\n"); //$NON-NLS-1$
} else {
writeString("<file original=\"" + inputFile //$NON-NLS-1$
+ "\" source-language=\"" + sourceLanguage //$NON-NLS-1$
+ "\" datatype=\"" + TYPE_VALUE + "\">\n"); //$NON-NLS-1$
}
writeString("<header>\n"); //$NON-NLS-1$
writeString(" <skl>\n"); //$NON-NLS-1$
String crc = ""; //$NON-NLS-1$
if (isSuite) {
crc = "crc=\"" + CRC16.crc16(TextUtil.cleanString(skeletonFile).getBytes("UTF-8")) + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
writeString(" <external-file href=\"" + TextUtil.cleanString(skeletonFile) + "\" " + crc + "/>\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
writeString(" </skl>\n"); //$NON-NLS-1$
writeString(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n"); //$NON-NLS-1$ //$NON-NLS-2$
writeString(" <hs:prop-group name=\"encoding\">\n" + //$NON-NLS-1$
" <hs:prop prop-type=\"encoding\">" //$NON-NLS-1$
+ srcEncoding + "</hs:prop>\n" //$NON-NLS-1$
+ " </hs:prop-group>\n"); //$NON-NLS-1$
writeString("</header>\n"); //$NON-NLS-1$
writeString("<body>\n"); //$NON-NLS-1$
skeleton = new FileOutputStream(skeletonFile);
String line = buffer.readLine();
cpb.calculateProcessed(monitor, line, srcEncoding);
while (line != null) {
line = line + "\n"; //$NON-NLS-1$
if (line.trim().length() == 0) {
// no text in this line
// segment separator
writeSkeleton(line);
} else {
if (line.startsWith("#:")) { //$NON-NLS-1$
// it is a reference
if (reference.equals("")) { //$NON-NLS-1$
reference = line.substring(2);
} else {
reference = reference + " " + line.substring(2); //$NON-NLS-1$
}
}
if (line.startsWith("# ")) { //$NON-NLS-1$
// translator comment
comment = comment + line.substring(2);
}
if (line.trim().equals("#")) { //$NON-NLS-1$
comment = comment + "\n"; //$NON-NLS-1$
}
if (line.startsWith("#.")) { //$NON-NLS-1$
// automatic comment
context = context + line.substring(2);
}
if (line.startsWith("#,")) { //$NON-NLS-1$
flags = line.substring(2);
// check for fuzzy
if (flags.indexOf("fuzzy") != -1) { //$NON-NLS-1$
fuzzy = true;
}
// Only c-format is parsed. Tags from other
// formats, like php-format or python-format,
// are left as part of the text
if (flags.indexOf("c-format") != -1 //$NON-NLS-1$
&& flags.indexOf("no-c-format") == -1) { //$NON-NLS-1$
cformat = true;
}
}
if (line.startsWith("#~")) { //$NON-NLS-1$
// commented entry
writeSkeleton(line);
}
if (line.startsWith("msgid")) { //$NON-NLS-1$
// get source text
line = line.substring(5);
source = line.substring(line.indexOf("\"") + 1, //$NON-NLS-1$
line.lastIndexOf("\"")); //$NON-NLS-1$
line = buffer.readLine();
cpb.calculateProcessed(monitor, line, srcEncoding);
while (line.startsWith("\"")) { //$NON-NLS-1$
source = source + "\n" //$NON-NLS-1$
+ line.substring(line.indexOf("\"") + 1, //$NON-NLS-1$
line.lastIndexOf("\"")); //$NON-NLS-1$
line = buffer.readLine();
cpb.calculateProcessed(monitor, line, srcEncoding);
}
continue;
}
if (line.startsWith("msgstr")) { //$NON-NLS-1$
// get the target
line = line.substring(6);
target = line.substring(line.indexOf("\"") + 1, //$NON-NLS-1$
line.lastIndexOf("\"")); //$NON-NLS-1$
line = buffer.readLine();
cpb.calculateProcessed(monitor, line, srcEncoding);
while (line != null && line.startsWith("\"")) { //$NON-NLS-1$
target = target + "\n" //$NON-NLS-1$
+ line.substring(line.indexOf("\"") + 1, //$NON-NLS-1$
line.lastIndexOf("\"")); //$NON-NLS-1$
line = buffer.readLine();
cpb.calculateProcessed(monitor, line, srcEncoding);
if (line == null) {
line = ""; //$NON-NLS-1$
}
}
writeSegment();
continue;
}
if (line.startsWith("domain")) { //$NON-NLS-1$
if (inDomain) {
writeString(" </group>\n"); //$NON-NLS-1$
}
inDomain = true;
writeString(" <group id=\"##" //$NON-NLS-1$
+ domainId++ + "\" restype=\"x-gettext-domain\" resname=\"" //$NON-NLS-1$
+ line.substring(6).trim() + "\">\n"); //$NON-NLS-1$
writeSkeleton(line);
}
}
line = buffer.readLine();
cpb.calculateProcessed(monitor, line, srcEncoding);
}
skeleton.close();
if (inDomain) {
writeString(" </group>\n"); //$NON-NLS-1$
}
writeString("</body>\n"); //$NON-NLS-1$
writeString("</file>\n"); //$NON-NLS-1$
writeString("</xliff>"); //$NON-NLS-1$
input.close();
output.close();
result.put(Converter.ATTR_XLIFF_FILE, xliffFile);
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("po.Po2Xliff.msg1"), e);
} finally {
monitor.done();
}
return result;
}
/**
* Write string.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string) throws IOException {
output.write(string.getBytes("UTF-8")); //$NON-NLS-1$
}
/**
* Write skeleton.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeSkeleton(String string) throws IOException {
skeleton.write(string.getBytes("UTF-8")); //$NON-NLS-1$
}
/**
* Write segment.
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeSegment() throws IOException {
String approved = "no"; //$NON-NLS-1$
if (!fuzzy && target.trim().length() > 0) {
approved = "yes"; //$NON-NLS-1$
}
String restype = ""; //$NON-NLS-1$
if (source.trim().equals("")) { //$NON-NLS-1$
restype = " restype=\"x-gettext-domain-header\" "; //$NON-NLS-1$
}
writeString(" <trans-unit id=\"" //$NON-NLS-1$
+ segId + "\" xml:space=\"preserve\" approved=\"" //$NON-NLS-1$
+ approved + "\"" //$NON-NLS-1$
+ restype + ">\n"); //$NON-NLS-1$
if (cformat) {
writeString(" <source xml:lang=\"" //$NON-NLS-1$
+ sourceLanguage + "\">" //$NON-NLS-1$
+ parseString(TextUtil.cleanString(source)) + "</source>\n"); //$NON-NLS-1$
if (target.length() > 0 || approved.equals("yes")) { //$NON-NLS-1$
writeString(" <target>" //$NON-NLS-1$
+ parseString(TextUtil.cleanString(target)) + "</target>\n"); //$NON-NLS-1$
}
} else {
if (source.trim().equals("")) { //$NON-NLS-1$
source = target;
}
writeString(" <source xml:lang=\"" //$NON-NLS-1$
+ sourceLanguage + "\">" //$NON-NLS-1$
+ TextUtil.cleanString(source) + "</source>\n"); //$NON-NLS-1$
if (target.length() > 0 || approved.equals("yes")) { //$NON-NLS-1$
writeString(" <target>" //$NON-NLS-1$
+ TextUtil.cleanString(target) + "</target>\n"); //$NON-NLS-1$
}
}
if (!comment.equals("")) { //$NON-NLS-1$
writeString(" <note from=\"po-file\">" //$NON-NLS-1$
+ TextUtil.cleanString(comment) + "</note>\n"); //$NON-NLS-1$
}
if (!context.equals("")) { //$NON-NLS-1$
writeString(" <context-group name=\"x-po-entry-header#" //$NON-NLS-1$
+ contextId++ + "\" purpose=\"information\">\n" //$NON-NLS-1$
+ " <context context-type=\"x-po-autocomment\">" //$NON-NLS-1$
+ TextUtil.cleanString(context) + "</context>\n" //$NON-NLS-1$
+ " </context-group>\n"); //$NON-NLS-1$
}
if (!reference.equals("")) { //$NON-NLS-1$
parseReference(TextUtil.cleanString(reference));
}
if (!flags.equals("")) { //$NON-NLS-1$
writeString(" <hs:prop-group>\n" //$NON-NLS-1$
+ " <hs:prop prop-type=\"x-po-flags\">" //$NON-NLS-1$
+ TextUtil.cleanString(flags).trim() + "</hs:prop>\n" //$NON-NLS-1$
+ " </hs:prop-group>\n"); //$NON-NLS-1$
}
writeString(" </trans-unit>\n"); //$NON-NLS-1$
writeSkeleton("%%%" + segId++ + "%%%\n"); //$NON-NLS-1$ //$NON-NLS-2$
source = ""; //$NON-NLS-1$
target = ""; //$NON-NLS-1$
comment = ""; //$NON-NLS-1$
context = ""; //$NON-NLS-1$
reference = ""; //$NON-NLS-1$
flags = ""; //$NON-NLS-1$
fuzzy = false;
cformat = false;
}
/**
* Parses the reference.
* @param ref
* the ref
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void parseReference(String ref) throws IOException {
if (ref.trim().equals("")) { //$NON-NLS-1$
return;
}
// fixed bug 425 by john. added context element to context-group
// element.
String[] refs = ref.trim().split("#:"); //$NON-NLS-1$
for (int i = 0, size = refs.length; i < size; i++) {
writeString(" <context-group name=\"x-po-reference#" //$NON-NLS-1$
+ refId++ + "\" purpose=\"location\">\n"); //$NON-NLS-1$
String token = refs[i];
if (token.indexOf(":") != -1) { //$NON-NLS-1$
writeString(" <context context-type=\"sourcefile\">" //$NON-NLS-1$
+ token.substring(0, token.indexOf(":")) //$NON-NLS-1$
+ "</context>\n"); //$NON-NLS-1$
writeString(" <context context-type=\"linenumber\">" //$NON-NLS-1$
+ token.substring(token.indexOf(":") + 1) //$NON-NLS-1$
+ "</context>\n"); //$NON-NLS-1$
} else {
writeString(" <context context-type=\"sourcefile\">" + token //$NON-NLS-1$
+ "</context>\n"); //$NON-NLS-1$
writeString(" <context context-type=\"linenumber\" />\n"); //$NON-NLS-1$
}
writeString(" </context-group>\n"); //$NON-NLS-1$
}
refs = null;
}
}
/**
* Parses the string.
* @param string
* the string
* @return the string
*/
private static String parseString(String string) {
// Valid c format especifications must end
// with one of diouxXfeEgGcs
int id = 1;
int index = string.indexOf("%"); //$NON-NLS-1$
if (index == -1) {
return string;
}
if (string.charAt(index + 1) == '%') {
index = string.indexOf("%", index + 2); //$NON-NLS-1$
}
String result = ""; //$NON-NLS-1$
while (index != -1) {
result = result + string.substring(0, index) + "<ph ctype=\"x-c-param\" id=\"" + id++ + "\">"; //$NON-NLS-1$ //$NON-NLS-2$
int i = index;
char c = string.charAt(i++);
while (i < string.length() && "diouxXfeEgGcs".indexOf(c) == -1) { //$NON-NLS-1$
result = result + c;
c = string.charAt(i++);
}
result = result + c + "</ph>"; //$NON-NLS-1$
string = string.substring(i);
index = string.indexOf("%"); //$NON-NLS-1$
if (index != -1 && index < string.length() && string.charAt(index + 1) == '%') {
index = string.indexOf("%", index + 2); //$NON-NLS-1$
}
}
result = result + string;
return result;
}
}
| 17,743 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Po.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.po/src/net/heartsome/cat/converter/po/Xliff2Po.java | /**
* Xliff2Po.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.po;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.Vector;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.po.resource.Messages;
import net.heartsome.cat.converter.util.CalculateProcessedBytes;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.converter.util.ReverseConversionInfoLogRecord;
import net.heartsome.xml.Document;
import net.heartsome.xml.Element;
import net.heartsome.xml.SAXBuilder;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.xml.sax.SAXException;
/**
* The Class Xliff2Po.
* @author John Zhu
*/
public class Xliff2Po implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "po";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("po.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to PO Conveter";
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Xliff2PoImpl converter = new Xliff2PoImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getName()
* @return
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getType()
* @return
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getTypeName()
* @return
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* The Class Xliff2PoImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class Xliff2PoImpl {
private static final String UTF_8 = "UTF-8";
/** The input. */
private InputStreamReader input;
/** The buffer. */
private BufferedReader buffer;
/** The skl file. */
private String sklFile;
/** The xliff file. */
private String xliffFile;
/** The line. */
private String line;
/** The segments. */
private Hashtable<String, Element> segments;
/** The output. */
private FileOutputStream output;
/** The encoding. */
private String encoding;
private boolean isPreviewMode;
/**
* Run.
* @param params
* the params
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord();
infoLogger.startConversion();
Map<String, String> result = new HashMap<String, String>();
sklFile = params.get(Converter.ATTR_SKELETON_FILE);
xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
String outputFile = params.get(Converter.ATTR_TARGET_FILE);
String attrIsPreviewMode = params.get(Converter.ATTR_IS_PREVIEW_MODE);
/* 是否为预览翻译模式 */
isPreviewMode = attrIsPreviewMode != null && attrIsPreviewMode.equals(Converter.TRUE);
try {
// 把转换过程分为两部分共 10 个任务,其中加载 xliff 占 5,替换过程占 5。
monitor.beginTask("", 10);
infoLogger.logConversionFileInfo(null, null, xliffFile, sklFile);
monitor.subTask(Messages.getString("po.Xliff2Po.task2"));
infoLogger.startLoadingXliffFile();
output = new FileOutputStream(outputFile);
loadSegments();
infoLogger.endLoadingXliffFile();
monitor.worked(5);
IProgressMonitor replaceMonitor = Progress.getSubMonitor(monitor, 5);
try {
// 是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("po.cancel"));
}
infoLogger.startReplacingSegmentSymbol();
CalculateProcessedBytes cpb = ConverterUtils.getCalculateProcessedBytes(sklFile);
replaceMonitor.beginTask(Messages.getString("po.Xliff2Po.task3"), cpb.getTotalTask());
replaceMonitor.subTask("");
input = new InputStreamReader(new FileInputStream(sklFile), UTF_8); //$NON-NLS-1$
buffer = new BufferedReader(input);
line = buffer.readLine();
while (line != null) {
// 是否取消
if (replaceMonitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("po.cancel"));
}
cpb.calculateProcessed(replaceMonitor, line, UTF_8);
line = line + "\n"; //$NON-NLS-1$
if (line.indexOf("%%%") != -1) { //$NON-NLS-1$
//
// contains translatable text
//
int index = line.indexOf("%%%"); //$NON-NLS-1$
while (index != -1) {
String start = line.substring(0, index);
writeString(start);
line = line.substring(index + 3);
String code = line.substring(0, line.indexOf("%%%")); //$NON-NLS-1$
line = line.substring(line.indexOf("%%%") + 3); //$NON-NLS-1$
Element segment = segments.get(code);
if (segment != null) {
writeSegment(segment);
} else {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, MessageFormat.format(
Messages.getString("po.Xliff2Po.msg1"), code));
}
index = line.indexOf("%%%"); //$NON-NLS-1$
if (index == -1) {
writeString(line);
}
} // end while
} else {
//
// non translatable portion
//
writeString(line);
}
line = buffer.readLine();
}
} finally {
replaceMonitor.done();
}
infoLogger.endReplacingSegmentSymbol();
output.close();
result.put(Converter.ATTR_TARGET_FILE, outputFile);
infoLogger.endConversion();
} catch (OperationCanceledException e) {
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("po.Xliff2Po.msg2"), e);
} finally {
monitor.done();
}
return result;
}
/**
* Write segment.
* @param segment
* the segment
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeSegment(Element segment) throws IOException {
Element target = segment.getChild("target"); //$NON-NLS-1$
Element source = segment.getChild("source"); //$NON-NLS-1$
boolean newLine = false;
boolean fuzzy = false;
if (isPreviewMode
|| !segment.getAttributeValue("approved", "no").equalsIgnoreCase("Yes") && target != null && !target.getText().trim().equals("")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
fuzzy = true;
}
writeComments(segment);
writeContext(segment);
writeReferences(segment);
writeFlags(segment, fuzzy);
if (source.getText().endsWith("\n")) { //$NON-NLS-1$
newLine = true;
} else {
newLine = false;
}
if (!segment.getAttributeValue("restype", "").equals("x-gettext-domain-header")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
writeString("msgid \"" + addQuotes(source.getText()) + "\"\n"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
writeString("msgid \"\"\n"); //$NON-NLS-1$
}
if (target != null) {
String text = target.getText();
if (newLine && !text.endsWith("\n")) { //$NON-NLS-1$
text = text + "\"\"\n"; //$NON-NLS-1$
}
writeString("msgstr \"" + addQuotes(text) + "\""); //$NON-NLS-1$ //$NON-NLS-2$
} else {
writeString("msgstr \"\""); //$NON-NLS-1$
}
}
/**
* Write flags.
* @param segment
* the segment
* @param fuzzy
* the fuzzy
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeFlags(Element segment, boolean fuzzy) throws IOException {
List<Element> groups = segment.getChildren("hs:prop-group"); //$NON-NLS-1$
Iterator<Element> i = groups.iterator();
String flags = ""; //$NON-NLS-1$
while (i.hasNext()) {
Element group = i.next();
List<Element> contexts = group.getChildren();
Iterator<Element> h = contexts.iterator();
while (h.hasNext()) {
Element prop = h.next();
if (prop.getAttributeValue("ctype", "").equals("x-po-flags")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
flags = prop.getText();
}
}
}
if (fuzzy) {
if (flags.indexOf("fuzzy") == -1) { //$NON-NLS-1$
writeString("#, fuzzy " + flags + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
writeString("#, " + flags + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
if (flags.indexOf("fuzzy") == -1) { //$NON-NLS-1$
if (!flags.equals("")) { //$NON-NLS-1$
writeString("#, " + flags + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
flags = flags.substring(0, flags.indexOf("fuzzy")) + flags.substring(flags.indexOf("fuzzy") + 5); //$NON-NLS-1$ //$NON-NLS-2$
if (!flags.equals("")) { //$NON-NLS-1$
writeString("#, " + flags + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
}
/**
* Write references.
* @param segment
* the segment
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeReferences(Element segment) throws IOException {
String reference = "#:"; //$NON-NLS-1$
List<Element> groups = segment.getChildren("context-group"); //$NON-NLS-1$
Iterator<Element> i = groups.iterator();
while (i.hasNext()) {
Element group = i.next();
if (group.getAttributeValue("name", "").startsWith("x-po-reference") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
&& group.getAttributeValue("purpose").equals("location")) //$NON-NLS-1$ //$NON-NLS-2$
{
String file = ""; //$NON-NLS-1$
String linenumber = ""; //$NON-NLS-1$
List<Element> contexts = group.getChildren();
Iterator<Element> h = contexts.iterator();
while (h.hasNext()) {
Element context = h.next();
if (context.getAttributeValue("context-type", "").equals("sourcefile")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
file = context.getText();
}
if (context.getAttributeValue("context-type", "").equals("linenumber")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
linenumber = context.getText();
}
}
String test = reference + " " + file + ":" + linenumber; //$NON-NLS-1$ //$NON-NLS-2$
if (test.substring(test.lastIndexOf("#:")).length() > 80) { //$NON-NLS-1$
reference = reference + "\n#:"; //$NON-NLS-1$
}
reference = reference + " " + file + ":" + linenumber; //$NON-NLS-1$ //$NON-NLS-2$
// fixed bug 425 by john.
if (reference.endsWith(":")) { //$NON-NLS-1$
reference = reference.substring(0, reference.length() - 1);
}
}
}
if (!reference.equals("#:")) { //$NON-NLS-1$
writeString(reference + "\n"); //$NON-NLS-1$
}
}
/**
* Write context.
* @param segment
* the segment
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeContext(Element segment) throws IOException {
List<Element> groups = segment.getChildren("context-group"); //$NON-NLS-1$
Iterator<Element> i = groups.iterator();
while (i.hasNext()) {
Element group = i.next();
if (group.getAttributeValue("name", "").startsWith("x-po-entry-header") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
&& group.getAttributeValue("purpose").equals("information")) //$NON-NLS-1$ //$NON-NLS-2$
{
List<Element> contexts = group.getChildren();
Iterator<Element> h = contexts.iterator();
while (h.hasNext()) {
Element context = h.next();
if (context.getAttributeValue("context-type", "").equals("x-po-autocomment")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
Vector<String> comments = splitLines(context.getText());
for (int j = 0; j < comments.size(); j++) {
String comment = comments.get(j);
if (!comment.trim().equals("")) { //$NON-NLS-1$
writeString("#. " + comment.trim() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
} else {
writeString("#.\n"); //$NON-NLS-1$
}
}
}
}
}
}
}
/**
* Write comments.
* @param segment
* the segment
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeComments(Element segment) throws IOException {
List<Element> notes = segment.getChildren("note"); //$NON-NLS-1$
Iterator<Element> i = notes.iterator();
while (i.hasNext()) {
Element note = i.next();
Vector<String> lines = splitLines(note.getText());
Iterator<String> h = lines.iterator();
while (h.hasNext()) {
String comment = h.next();
writeString("# " + comment.trim() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
/**
* Split lines.
* @param text
* the text
* @return the vector< string>
*/
private Vector<String> splitLines(String text) {
Vector<String> result = new Vector<String>();
StringTokenizer tokenizer = new StringTokenizer(text, "\n"); //$NON-NLS-1$
if (text.startsWith("\n\n")) { //$NON-NLS-1$
result.add(""); //$NON-NLS-1$
}
while (tokenizer.hasMoreTokens()) {
result.add(tokenizer.nextToken());
}
if (text.endsWith("\n\n")) { //$NON-NLS-1$
result.add(""); //$NON-NLS-1$
}
tokenizer = null;
return result;
}
/**
* Load segments.
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void loadSegments() throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xliffFile);
Element root = doc.getRootElement();
segments = new Hashtable<String, Element>();
recurse(root);
}
/**
* Recurse.
* @param e
* the e
*/
private void recurse(Element e) {
List<Element> list = e.getChildren();
Iterator<Element> i = list.iterator();
while (i.hasNext()) {
Element u = i.next();
if (u.getName().equals("trans-unit")) { //$NON-NLS-1$
segments.put(u.getAttributeValue("id"), u); //$NON-NLS-1$
} else {
recurse(u);
}
}
}
/**
* Write string.
* @param string
* the string
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void writeString(String string) throws IOException {
output.write(string.getBytes(encoding));
}
}
/**
* Adds the quotes.
* @param string
* the string
* @return the string
*/
private static String addQuotes(String string) {
return string.replaceAll("\n", "\"\n\""); //$NON-NLS-1$ //$NON-NLS-2$
}
}
| 16,259 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.po/src/net/heartsome/cat/converter/po/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.po;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.ConverterRegister;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The Class Activator.The activator class controls the plug-in life cycle.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Activator implements BundleActivator {
// The plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.po";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The po2 xliff sr. */
private ServiceRegistration po2XliffSR;
/** The xliff2 po sr. */
private ServiceRegistration xliff2PoSR;
/**
* The constructor.
*/
public Activator() {
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void start(BundleContext context) throws Exception {
plugin = this;
// register the converter services
Converter po2Xliff = new Po2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Po2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Po2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Po2Xliff.TYPE_NAME_VALUE);
po2XliffSR = ConverterRegister.registerPositiveConverter(context, po2Xliff, properties);
Converter xliff2Po = new Xliff2Po();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Po.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Po.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Po.TYPE_NAME_VALUE);
xliff2PoSR = ConverterRegister.registerReverseConverter(context, xliff2Po, properties);
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void stop(BundleContext context) throws Exception {
if (po2XliffSR != null) {
po2XliffSR.unregister();
}
if (xliff2PoSR != null) {
xliff2PoSR.unregister();
}
plugin = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,476 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.po/src/net/heartsome/cat/converter/po/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.po.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* The Class Messages.
* @author John Zhu
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.po.resource.po"; //$NON-NLS-1$
/** The Constant RESOURCE_BUNDLE. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
/**
* Instantiates a new messages.
*/
private Messages() {
// Do nothing
}
/**
* Gets the string.
* @param key
* the key
* @return the string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| 1,010 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2TtxTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/testSrc/net/heartsome/cat/converter/ttx/test/Xliff2TtxTest.java | package net.heartsome.cat.converter.ttx.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.ttx.Xliff2Ttx;
import org.junit.Before;
import org.junit.Test;
public class Xliff2TtxTest {
public static Xliff2Ttx converter = new Xliff2Ttx();
private static String tgtFile = "rc/Test_en-US.ttx";
private static String xlfFile = "rc/Test.ttx.xlf";
private static String sklFile = "rc/Test.ttx.skl";
@Before
public void setUp() {
File tgt = new File(tgtFile);
if (tgt.exists()) {
tgt.delete();
}
}
@Test
public void testConvert() throws ConverterException {
String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtFile);
args.put(Converter.ATTR_XLIFF_FILE, xlfFile);
args.put(Converter.ATTR_SKELETON_FILE, sklFile);
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-16LE");
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
Map<String, String> result = converter.convert(args, null);
String target = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(target);
File tgtFile = new File(target);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
}
| 1,473 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Ttx2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/testSrc/net/heartsome/cat/converter/ttx/test/Ttx2XliffTest.java | package net.heartsome.cat.converter.ttx.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.ttx.Ttx2Xliff;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
public class Ttx2XliffTest {
public static Ttx2Xliff converter = new Ttx2Xliff();
private static String srcFile = "rc/Test.ttx";
private static String sklFile = "rc/Test.ttx.skl";
private static String xlfFile = "rc/Test.ttx.xlf";
@Before
public void setUp(){
File skl = new File(sklFile);
if(skl.exists()){
skl.delete();
}
File xlf = new File(xlfFile);
if(xlf.exists()){
xlf.delete();
}
}
@Test(expected = ConverterException.class)
public void testConvertMissingCatalog() throws ConverterException {
String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-16LE"); //$NON-NLS-1$
// args.put(Converter.ATTR_CATALOGUE, rootFolder +
// "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
@Test(expected = ConverterException.class)
public void testConvertMissingSRX() throws ConverterException {
String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-16LE"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
// args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
@AfterClass
public static void testConvert() throws ConverterException {
String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-16LE"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
}
| 3,679 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SegmentBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/SegmentBean.java | package net.heartsome.cat.converter.ttx;
/**
* 专门针对 ArrangeTTX 类所需要用的数据进行封装的 POJO 类。
* @author robert 2012-07-25
*/
public class SegmentBean {
/** 一个文本段(即要进行翻译的文本段)所处在节点的父节点的内容,通常指 <df> 节点,若无 <df> ,则其内容为其自己。 */
private String parentNodeFrag;
/** 这个文本段的父节点是否包括标记 */
private boolean hasTag;
/** 文本段的内容 */
private String segment;
/** <ut> 标记,这个标记的内容有可能是paragram, 也有可能是 cf 节点。 */
private String tagStr;
public SegmentBean(){}
public String getParentNodeFrag() {
return parentNodeFrag;
}
public void setParentNodeFrag(String parentNodeFrag) {
this.parentNodeFrag = parentNodeFrag;
}
public boolean isHasTag() {
return hasTag;
}
public void setHasTag(boolean hasTag) {
this.hasTag = hasTag;
}
public String getSegment() {
return segment;
}
public void setSegment(String segment) {
this.segment = segment;
}
public String getTagStr() {
return tagStr;
}
public void setTagStr(String tagStr) {
this.tagStr = tagStr;
}
}
| 1,182 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ttx;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.ConverterRegister;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The Class Activator.The activator class controls the plug-in life cycle.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Activator implements BundleActivator {
// The plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.ttx";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The ttx2 xliff sr. */
private ServiceRegistration ttx2XliffSR;
/** The xliff2 ttx sr. */
private ServiceRegistration xliff2TtxSR;
/**
* The constructor.
*/
public Activator() {
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void start(BundleContext context) throws Exception {
plugin = this;
// register the convert service
Converter ttx2Xliff = new Ttx2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Ttx2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Ttx2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Ttx2Xliff.TYPE_NAME_VALUE);
ttx2XliffSR = ConverterRegister.registerPositiveConverter(context, ttx2Xliff, properties);
Converter xliff2Ttx = new Xliff2Ttx();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Ttx.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Ttx.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Ttx.TYPE_NAME_VALUE);
xliff2TtxSR = ConverterRegister.registerReverseConverter(context, xliff2Ttx, properties);
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void stop(BundleContext context) throws Exception {
if (ttx2XliffSR != null) {
ttx2XliffSR.unregister();
ttx2XliffSR = null;
}
if (xliff2TtxSR != null) {
xliff2TtxSR.unregister();
xliff2TtxSR = null;
}
plugin = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,543 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ArrangeTTX.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/ArrangeTTX.java | package net.heartsome.cat.converter.ttx;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.TreeMap;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.StringSegmenter;
import net.heartsome.xml.vtdimpl.VTDUtils;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* 整体ttx文件,主要内容就是将一个未翻译的ttx文件进行相关的处理,分段,添加tu节点,这样方便进行转换。
* @author robert 2012-07-16
*/
public class ArrangeTTX {
private StringSegmenter segmenter;
private VTDNav sklVN;
private XMLModifier sklXM;
/** 当前要处理的 ttx 文件自带的源语言 */
private String detectedSourceLang;
/** 当前要处理的 ttx 文件自带的目标语言 */
private String detectedTargetLang;
private VTDUtils vu;
/** 对 Raw 节点下的文本节点单独取出后存放, key值为token */
private List<Integer> rawTextTokenList;
/** 单元的起始符,单元为 ut 节点 DisplayText="paragraph" 或者 DisplayText="^" 的区间,单元的结束标志为 <ut Type="end" ... > 或遇到 <Tu> 节点 */
private boolean start = false;
private boolean end = false;
/** 针对每个文本段,是否需要加入segBeanMap中 */
private boolean needAdd = false;
public ArrangeTTX() { }
// UNDO 这里处理的 paragraph 还有问题,而且问题还插严重。
public ArrangeTTX(VTDNav sklVN, XMLModifier sklXM, String elementSegmentation, String initSegmenter,
String userSourceLang, String catalogue, String detectedSourceLang, String detectedTargetLang) throws Exception {
boolean segByElement = false;
if (Converter.TRUE.equals(elementSegmentation)) {
segByElement = true;
} else {
segByElement = false;
}
if (!segByElement) {
segmenter = new StringSegmenter(initSegmenter, userSourceLang, catalogue);
}
this.sklVN = sklVN;
this.sklXM = sklXM;
this.detectedSourceLang = detectedSourceLang;
this.detectedTargetLang = detectedTargetLang;
System.out.println("detectedTargetLang = " + detectedTargetLang);
vu = new VTDUtils(sklVN);
rawTextTokenList = new LinkedList<Integer>();
}
/**
* 生成tu节点
*/
public void createTuNode(String skeletonFile) throws Exception{
//循环每一个文本子节点进行,先对它进行分段,再对分段后的进行包裹 Tu 节点
// 首先分段,读取每一个单元,在这个单元内进行分段操作。这个单元就是 ut 节点 DisplayText="paragraph" 或者 DisplayText="^" 的区间
getRawTextToken();
String xpath = "/TRADOStag/Body/Raw/node()";
AutoPilot ap = new AutoPilot(sklVN);
ap.selectXPath(xpath);
TreeMap<Integer, SegmentBean> segBeanMap = new TreeMap<Integer, SegmentBean>();
SegmentBean segBean;
int index = -1;
while(ap.evalXPath() != -1){
String nodeName = vu.getCurrentElementName();
segBean = new SegmentBean();
// 首先处理raw节点的直接子节点
index = sklVN.getCurrentIndex() - 1;
if (rawTextTokenList.contains(index)) {
if (start && !end) { //处在开始标签与结束标签之前的节点才进行处理
segBean.setHasTag(false);
segBean.setParentNodeFrag(sklVN.toRawString(index));
segBean.setSegment(sklVN.toRawString(index));
segBeanMap.put(index, segBean);
//删除这个 raw 节点的文本子节点
sklXM.updateToken(index, "");
segBean = new SegmentBean();
}
}
// DOLATER 这个地方还没有验证一个文件中间地方出现一个 Tu 节点的情况。
//处理子节点
if ("df".equals(nodeName)) {
analysisDF(sklVN, segBean);
if (!end && needAdd) { //如果未结束,并且可以添加进segBeanMap,就添加
segBean.setParentNodeFrag(vu.getElementFragment());
segBeanMap.put(sklVN.getCurrentIndex(), segBean);
//删除这个节点
sklXM.remove();
}
}else if ("ut".equals(nodeName)) {
analysisUT(sklVN, segBean);
if (!end && needAdd) { //如果未结束,并且可以添加进segBeanMap,就添加
segBean.setParentNodeFrag(vu.getElementFragment());
segBeanMap.put(sklVN.getCurrentIndex(), segBean);
//删除这个节点
sklXM.remove();
}
}else if ("Tu".equals(nodeName)) {
end = true;
}
// 处于单元内部,进行相关处理
if (end) {
splitSegment(sklVN, segBeanMap);
}
}
sklXM.output(skeletonFile);
}
/**
* 处理一个单元格区间的每一个节点,
* @return true:调用此方法的程序继续执行, false:调用此方法的程序终止执行或跳出当前循环
*/
private void analysisDF(VTDNav vn, SegmentBean segBean) throws Exception{
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "./node()|text()";
ap.selectXPath(xpath);
int index = -1;
while(ap.evalXPath() != -1){
int tokenType = vn.getTokenType(vn.getCurrentIndex());
if (tokenType == 0) { //等于0表示为节点
String nodeName = vu.getCurrentElementName();
if ("ut".equals(nodeName)) {
String typeAtt = "";
if ((index = vn.getAttrVal("Type")) != -1) {
typeAtt = vn.toRawString(index);
}
String displayTextAtt = "";
if ((index = vn.getAttrVal("DisplayText")) != -1) {
displayTextAtt = vn.toRawString(index);
}
//判断开始与结束点
if ("start".equals(typeAtt) && !"cf".equals(displayTextAtt)) {
start = true; //一个单元的开始
end = false;
}else if ("end".equals(typeAtt) && !"cf".equals(displayTextAtt)) {
start = false;
end = true; // 一个单元的结束
}
segBean.setTagStr(vu.getElementFragment());
needAdd = true;
}else if ("Tu".equals(nodeName)) { //遇到 Tu 节点,单元结束,end = true,但是 start仍保持之前状态
needAdd = false;
end = true;
}
segBean.setHasTag(true); //有标记存在
}else if (tokenType == 5) { //等于5表示为文本子节点
segBean.setSegment(vn.toRawString(vn.getCurrentIndex()));
System.out.println(vn.toRawString(vn.getCurrentIndex()));
needAdd = true;
}
}
vn.pop();
}
/**
* 分析 ut 节点,这个节点里面保存的一般都是 cf 标记或者单元内容
* @throws Exception
*/
private void analysisUT(VTDNav vn, SegmentBean segBean) throws Exception{
vn.push();
int index = -1;
String typeAtt = "";
if ((index = vn.getAttrVal("Type")) != -1) {
typeAtt = vn.toRawString(index);
}
String displayTextAtt = "";
if ((index = vn.getAttrVal("DisplayText")) != -1) {
displayTextAtt = vn.toRawString(index);
}
//判断开始与结束点
if ("start".equals(typeAtt) && !"cf".equals(displayTextAtt)) {
start = true; //一个单元的开始
end = false;
}else if ("end".equals(typeAtt) && !"cf".equals(displayTextAtt)) {
start = false;
end = true; // 一个单元的结束
}
segBean.setTagStr(vu.getElementFragment());
segBean.setHasTag(true);
needAdd = true;
vn.pop();
}
/**
* 开始拆分文本段,从而进行组装
* @param vn
* @param segBeanMap
*/
private void splitSegment(VTDNav vn, TreeMap<Integer, SegmentBean> segBeanMap) throws Exception{
StringBuffer segSB = new StringBuffer();
for(Entry<Integer, SegmentBean> entry : segBeanMap.entrySet()){
if (entry.getValue().getSegment() != null) {
segSB.append(entry.getValue().getSegment());
}
}
System.out.println("未拆分前的名子=" + segSB.toString());
// 开始进行拆分
String[] segArray = segmenter.segment(segSB.toString());
System.out.println("拆分后的句子=");
for(String str : segArray){
System.out.println(str);
}
List<String> segList = new LinkedList<String>();
for (String str : segArray) {
if (str.trim().length() > 0) {
segList.add(str);
}
}
//拆分之后,就查看拆分后的每个小文本段是否在一个 df 节点或是一个单独的 raw 文本子节点,
//如果是,直接在里面进行生成tu,如果不是,直接生成一个tu。把这几个小文本段的父节点一下包括进来。
StringBuffer addSB = new StringBuffer();
StringBuffer tuSB;
for (Iterator<Entry<Integer, SegmentBean>> it = segBeanMap.entrySet().iterator(); it.hasNext();) {
SegmentBean segBean = it.next().getValue();
tuSB = new StringBuffer();
if (segBean.getSegment() != null) {
if (segList.size() > 0) {
if (segBean.getSegment().trim().equals(segList.get(0).trim())) {
tuSB.append("<Tu Origin=\"manual\"><Tuv Lang=\"" + detectedSourceLang + "\">");
tuSB.append(segBean.getSegment() + "</Tuv>");
tuSB.append("<Tuv Lang=\"" + detectedTargetLang + "\"></Tuv></Tu>");
addSB.append(segBean.getParentNodeFrag().replace(segBean.getSegment(), tuSB.toString()));
segList.remove(0);
} else if (segBean.getSegment().length() > segList.get(0).length()) {
//这是一个未分割的文本段分割后的段数大于1的情况。
while(segList.size() > 0 && segBean.getSegment().indexOf(segList.get(0)) != -1){
tuSB.append("<Tu Origin=\"manual\"><Tuv Lang=\"" + detectedSourceLang + "\">");
tuSB.append(segList.get(0) + "</Tuv>");
tuSB.append("<Tuv Lang=\"" + detectedTargetLang + "\"></Tuv></Tu>");
segList.remove(0);
}
addSB.append(segBean.getParentNodeFrag().replace(segBean.getSegment(), tuSB.toString()));
}else if (segBean.getSegment().length() < segList.get(0).length()) {
//这种情况是未分割的文本段分割后不足一个文本段的情况
tuSB.append("<Tu Origin=\"manual\"><Tuv Lang=\"" + detectedSourceLang + "\">");
tuSB.append(segBean.getParentNodeFrag());
while(it.hasNext()){
//segBean.getSegment() == null || (segList.get(0).indexOf(segBean.getSegment()) != -1 &&
segBean = it.next().getValue();
if (segBean.getSegment() != null && segList.get(0).indexOf(segBean.getSegment()) == -1) {
break;
}
tuSB.append(segBean.getParentNodeFrag());
}
tuSB.append("</Tuv><Tuv Lang=\"" + detectedTargetLang + "\"></Tuv></Tu>");
addSB.append(tuSB.toString());
segList.remove(0);
}
}
} else {
addSB.append(segBean.getParentNodeFrag());
}
}
sklXM.insertBeforeElement(addSB.toString());
System.out.println("-----------------------");
segBeanMap.clear();
end = false; // 处理完后,单元格标识为未结束状态
}
/**
* 取出 Raw 节点下的文本子节点的 token 值进行存放,单独进行处理
*/
private void getRawTextToken() throws Exception{
AutoPilot ap = new AutoPilot(sklVN);
String xpath = "/TRADOStag/Body/Raw/text()";
ap.selectXPath(xpath);
while(ap.evalXPath() != -1){
rawTextTokenList.add(sklVN.getCurrentIndex());
}
}
}
| 10,850 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Ttx.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/Xliff2Ttx.java | package net.heartsome.cat.converter.ttx;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import net.heartsome.cat.common.util.TextUtil;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.ttx.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.cat.converter.util.ReverseConversionInfoLogRecord;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SubProgressMonitor;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* trados 2007 的 ttx(tradostag Xliff) 文件逆向转换器。
* @author robert 2012-07-27
*/
public class Xliff2Ttx implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-ttx";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("ttx.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to TTX Conveter";
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Xliff2TtxImpl converter = new Xliff2TtxImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getName()
* @return
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getType()
* @return
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getTypeName()
* @return
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* 逆向转换器实现类
* <div style='color:red'>备注:trans-unit的id,对应 ttx 文件的 Tu 节点的id,
* 而 xlf 文件的标记 <g id='1'> 对应 ttx 文件的占位符如%%%1%%% 。</div>
* @author robert 2012-07-27
* @version
* @since JDK1.6
*/
class Xliff2TtxImpl {
/** 逆转换p */
private String outputFile;
/** The encoding. */
private String encoding;
/** ttx 的源语言 */
private String detectedSourceLang;
/** ttx 文件的目标语言 */
private String detectedTargetLang;
/** 是否是预翻译模式 */
private boolean isPreviewMode;
/** 骨架文件的解析游标 */
private VTDNav outputVN;
/** 骨架文件的修改类实例 */
private XMLModifier outputXM;
/** 骨架文件的查询实例 */
private AutoPilot outputAP;
private VTDUtils outputVU;
/** xliff文件的解析游标 */
private VTDNav xlfVN;
/** xliff 文件的查询实例 */
private AutoPilot xlfAP;
private static final String nodeXpath = "./node()|text()";
private AutoPilot tagAP;
private int addedEndTagNum = 0;
/** 这是进度条的前进间隔,也就是当循环多少个trans-unit节点后前进一格 */
private int workInterval = 1;
/**
* Run.
* @param params
* the params
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
ReverseConversionInfoLogRecord infoLogger = ConverterUtils.getReverseConversionInfoLogRecord();
infoLogger.startConversion();
Map<String, String> result = new HashMap<String, String>();
String sklFile = params.get(Converter.ATTR_SKELETON_FILE);
String xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
outputFile = params.get(Converter.ATTR_TARGET_FILE);
String attrIsPreviewMode = params.get(Converter.ATTR_IS_PREVIEW_MODE);
/* 是否为预览翻译模式 */
isPreviewMode = attrIsPreviewMode != null && attrIsPreviewMode.equals(Converter.TRUE);
try {
infoLogger.logConversionFileInfo(null, null, xliffFile, sklFile);
// 把转换过程分为两大部分共 10 个任务,其中加载 xliff 文件占 1,替换过程占 9。
monitor.beginTask(Messages.getString("ttx.Xliff2Ttx.task1"), 10);
//记录加载信息
infoLogger.startLoadingXliffFile();
String sklTempSkl = "";
//先将骨架文件的内容拷贝到目标文件,再解析目标文件
if (encoding.equalsIgnoreCase("utf-8")) {
copyFile(sklFile, outputFile);
parseOutputFile(outputFile, xliffFile);
}else {
sklTempSkl = File.createTempFile("tempskl", "skl").getAbsolutePath();
new File(sklTempSkl).deleteOnExit();
copyFile(sklFile, sklTempSkl);
parseOutputFile(sklTempSkl, xliffFile);
}
parseXlfFile(xliffFile);
getSrcAndTgtLang();
infoLogger.endLoadingXliffFile();
monitor.worked(1);
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("ttx.cancel"));
}
ananysisXlfTU(monitor);
//记录加载完。
infoLogger.endReplacingSegmentSymbol();
// 针对没有目标语言节点为 noLang 的 Tvu,将之 lang 属性变成 "";
// 如果 encoding 不是 utf-8,那么将这个临时文件从 utf-8 转换成 encoding 格式
if (encoding.equalsIgnoreCase("utf-8")) {
outputXM.output(outputFile);
parseOutputFile(outputFile, xliffFile);
deleteTgtLangIfNon();
outputXM.output(outputFile);
}else {
outputXM.output(sklTempSkl);
parseOutputFile(sklTempSkl, xliffFile);
deleteTgtLangIfNon();
outputXM.output(sklTempSkl);
copyFile(sklTempSkl, outputFile, "UTF-8", encoding);
}
//记录完成逆转换
infoLogger.endConversion();
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("ttx.Xliff2Ttx.msg1"), e);
} finally {
monitor.done();
}
result.put(Converter.ATTR_TARGET_FILE, outputFile);
return result;
}
/**
* 进度条前进处理类,若返回false,则标志退出程序的执行
* @param monitor
* @param traversalTuIndex
* @param last
* @return ;
*/
public boolean monitorWork(IProgressMonitor monitor, int traversalTuIndex, boolean last){
if (last) {
if (traversalTuIndex % workInterval != 0) {
if (monitor.isCanceled()) {
return false;
}
monitor.worked(1);
}
}else {
if (traversalTuIndex % workInterval == 0) {
if (monitor.isCanceled()) {
return false;
}
monitor.worked(1);
}
}
return true;
}
/**
* 解析结果文件(解析时这个结果文件还是一个骨架文件)
* @param file
* @throws Exception
*/
private void parseOutputFile(String file, String xliffFile) throws Exception {
VTDGen vg = new VTDGen();
if (vg.parseFile(file, true)) {
outputVN = vg.getNav();
outputXM = new XMLModifier(outputVN);
outputAP = new AutoPilot(outputVN);
outputVU = new VTDUtils(outputVN);
}else {
String errorInfo = MessageFormat.format("文件 {0} 的骨架信息无法解析,逆转换失败!",
new Object[]{new File(xliffFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 解析要被逆转换的xliff文件
* @param xliffFile
* @throws Exception
*/
private void parseXlfFile(String xliffFile) throws Exception {
VTDGen vg = new VTDGen();
if (vg.parseFile(xliffFile, true)) {
xlfVN = vg.getNav();
xlfAP = new AutoPilot(xlfVN);
}else {
String errorInfo = MessageFormat.format("文件 {0} 的骨架信息无法解析,逆转换失败!",
new Object[]{new File(xliffFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 分析xliff文件的每一个 trans-unit 节点
* <div style='color:red'>备注:trans-unit的id,对应 ttx 文件的 Tu 节点的id,而 xlf 文件的标记 <g id='1'> 对应 ttx 文件的占位符如%%%1%%% 。</div>
* @throws Exception
*/
private void ananysisXlfTU(IProgressMonitor monitor) throws Exception {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
AutoPilot ap = new AutoPilot(xlfVN);
AutoPilot childAP = new AutoPilot(xlfVN);
ap.selectXPath("count(/xliff/file/body//trans-unit)");
int tuTotalSum = (int) ap.evalXPathToNumber();
if (tuTotalSum > 500) {
workInterval = tuTotalSum / 500;
}
IProgressMonitor subMonitor = new SubProgressMonitor(monitor, 9, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
subMonitor.beginTask("", tuTotalSum % workInterval == 0 ? (tuTotalSum / workInterval) : (tuTotalSum / workInterval) + 1 );
VTDUtils vu = new VTDUtils(xlfVN);
String xpath = "/xliff/file/body//trans-unit";
String srcXpath = "./source";
String tgtXpath = "./target";
ap.selectXPath(xpath);
int attrIdx = -1;
// trans-unit的id,对应 ttx 文件的 Tu 节点的id
String segId = "";
// 添加到 ttx 源文的内容
String srcText = "";
// 添加到 ttx 目标的内容
String tgtText = "";
List<String> tagBorderList = new LinkedList<String>();
addedEndTagNum = 0;
int traversalTuIndex = 0;
while (ap.evalXPath() != -1) {
traversalTuIndex ++;
if ((attrIdx = xlfVN.getAttrVal("id")) == -1) {
continue;
}
srcText = "";
tgtText = "";
segId = xlfVN.toRawString(attrIdx);
tagBorderList.clear();
getStartAndEndTagStr(tagBorderList, segId);
if ((attrIdx = xlfVN.getAttrVal("addedEndTagNum")) != -1) {
addedEndTagNum = Integer.parseInt(xlfVN.toString(attrIdx));
}
// 处理source节点
xlfVN.push();
childAP.selectXPath(srcXpath);
if (childAP.evalXPath() != -1) {
String srcContent = vu.getElementContent();
srcText = createTTXTuvContent(xlfVN, vu, segId, srcContent, tagBorderList);
srcText = srcText.replaceAll("(<cf)\\s+(id=')\\d+(')\\s+", "<cf ");
}
xlfVN.pop();
// 处理target节点
xlfVN.push();
String tgtContent = null;
childAP.selectXPath(tgtXpath);
if (childAP.evalXPath() != -1) {
tgtContent = vu.getElementContent();
tgtText = createTTXTuvContent(xlfVN, vu, segId, tgtContent, tagBorderList);
tgtText = tgtText.replaceAll("(<cf)\\s+(id=')\\d+(')\\s+", "<cf ");
}
xlfVN.pop();
//判断是否处于锁定状态
if ((attrIdx = xlfVN.getAttrVal("translate")) != -1) {
if ("no".equalsIgnoreCase(xlfVN.toRawString(attrIdx))) {
// DOLATER 这里未处理锁定的相关东西
}
}
replaceSegment(segId, srcText, tgtText);
if (!monitorWork(subMonitor, traversalTuIndex, false)) {
throw new OperationCanceledException(Messages.getString("ttx.cancel"));
}
}
if (!monitorWork(subMonitor, traversalTuIndex, true)) {
throw new OperationCanceledException(Messages.getString("ttx.cancel"));
}
subMonitor.done();
}
/**
* 生成新的 ttx 文件 tuv 的内容
* @param segId trans-unit 与 Tu 节点的 id
* @param content xlf 节点source 或 target 节点的内容
* @param contentSB 新生成的 tuv 节点内容
*/
private String createTTXTuvContent(VTDNav vn, VTDUtils vu, String segId,
String content, List<String> tagBorderList) throws Exception {
if (content == null || "".equals(content)) {
return content;
}
int index = -1;
//先处理标记,由R8过来的标记是成对出现的,但是tuv里面的标记很乱,不会成对出现。故找到多余的结束标记进行处理。
// int tagPairNum = 0;
// for (int i = 0; i < tagBorderList.size(); i++) {
// String tagBorder = tagBorderList.get(i);
// if (i == 0 && "end".equals(tagBorder)) {
// content = "</g>" + content;
// while(i + 1 < tagBorderList.size() && "end".equals(tagBorderList.get(i + 1))){
// content = "</g>" + content;
// i++;
// }
// }else if ("start".equals(tagBorder)) {
// tagPairNum ++;
// }else if ("end".equals(tagBorder)) {
// tagPairNum --;
// }
// }
// if (tagPairNum > 0) { //结束标记少了,就应该删除多作的<g>
// while(tagPairNum != 0){
// if ((index = content.lastIndexOf("</g>")) != -1) {
// content = content.substring(0, index) + content.substring(index + 4);
// }
// tagPairNum--;
// }
// }else if (tagPairNum < 0) { //标记结束点多了<cf>,就应添加<g>,以保持r8与ttx文件标记的对应
// while(tagPairNum != 0){
// content = content + "</g>";
// tagPairNum++;
// }
// }
//
//
// //先处理标记,专门处理ttx原文结尾处没有成对的</cf>的情况
// int start = 0;
// int end = 0;
// for (int i = 0; i < tagBorderList.size(); i++) {
// if ("start".equals(tagBorderList.get(i))) {
// start ++;
// }else {
// if (start > end) {
// end ++;
// }
// }
// }
//
int ends = addedEndTagNum;
while(ends > 0){
if ((index = content.lastIndexOf("</g>")) != -1) {
content = content.substring(0, index) + content.substring(index + 4);
}
ends --;
}
//先判断当前节点下有没有子节点,也就是有没有<g>标记,如果没有,直接替换,否则生成新的标记
if (vu.getChildElementsCount() > 0) {
index = content.indexOf("<g");
while(index != -1){
int idIdx = content.indexOf(">", index);
String tagStr = content.substring(index, idIdx + 1);
//处理<g id='null?' />的情况
if (tagStr.indexOf("/>") != -1) {
String newTagStr = "<cf" + tagStr.substring(tagStr.indexOf("<g") + 2, tagStr.indexOf("/>")) + ">";
newTagStr = "<ut Type=\"start\" RightEdge=\"angle\" DisplayText=\"cf\">" + TextUtil.cleanSpecialString(newTagStr) + "</ut>"
+ "<ut Type=\"end\" LeftEdge=\"angle\" DisplayText=\"cf\"></cf></ut>";
content = content.replace(tagStr, newTagStr);
}else {
String tagId = getTagId(tagStr.indexOf("/>") == -1 ? (tagStr + "</g>") : tagStr);
// String tagId = "";
if ("".equals(tagId)) {
// 如果找不到相应标记的 id,那么自动将这个标记转换成 ttx 文件的 cf 标记。
String newTagStr = "<cf" + tagStr.substring(tagStr.indexOf("<g") + 2, tagStr.indexOf(">")) + ">";
newTagStr = "<ut Type=\"start\" RightEdge=\"angle\" DisplayText=\"cf\">" + TextUtil.cleanSpecialString(newTagStr) + "</ut>";
content = content.replace(tagStr, newTagStr);
}else {
String tagParentStr = getTagParent(segId, tagId);
if ("".equals(tagParentStr)) {
String newTagStr = "<cf" + tagStr.substring(tagStr.indexOf("<g") + 2, tagStr.indexOf(">")) + ">";
newTagStr = "<ut Type=\"start\" RightEdge=\"angle\" DisplayText=\"cf\">" + TextUtil.cleanSpecialString(newTagStr) + "</ut>";
content = content.replace(tagStr, newTagStr);
}else {
// 如果 cf 标记有父节点(父节点不是tuv),那么直接将占位符替换成这个标记里的内容即可
int endIdx = content.indexOf("<", idIdx);
String tagTextStr = content.substring(idIdx + 1, endIdx == -1 ? content.length() : endIdx);
tagParentStr = tagParentStr.replace("%%%"+tagId+"%%%", tagTextStr);
content = content.replace(tagStr + tagTextStr, tagParentStr);
}
}
}
index = content.indexOf("<g");
int aaa = content.indexOf("</g>");
int b = 0;
while(aaa != -1){
b ++;
aaa = content.indexOf("</g>", aaa + 1);
}
}
}
// 处理ph标记
index = content.indexOf("<ph");
while(index != -1){
String phFrag = content.substring(index, content.indexOf("</ph>", index) + 5);
content = content.replace(phFrag, replacePH(phFrag));
index = content.indexOf("<ph", index + 1);
}
//处理结束标记
index = content.indexOf("</g>");
if(index != -1){
String endTagStr = "<ut Type=\"end\" LeftEdge=\"angle\" DisplayText=\"cf\"></cf></ut>";
content = content.replaceAll("</g>", endTagStr);
}
return content;
}
/**
* 通过 trans-unit 的 id 及 语言获取 ttx 文件的 tuv 的内容,从而进行组装成新的内容,再将这个新的内容插入到 ttx 所对应的地方
*/
private String getTagParent(String segId, String tagId) throws Exception {
String xpath = "/TRADOStag/Body/Raw//Tu/Tuv[@Lang='" + detectedSourceLang + "']" +
"//node()[text()='%%%" + tagId + "%%%']";
String tagParent = "";
outputAP.selectXPath(xpath);
if (outputAP.evalXPath() != -1) {
outputAP.selectXPath("./text()");
StringBuffer textSB = new StringBuffer();
while (outputAP.evalXPath() != -1) {
textSB.append(outputVN.toString(outputVN.getCurrentIndex()));
}
// 如果 当前节点里面有多个占位符,那么返回应为空,这是修改 bug Bug #3396 TTX 转换器:无法转换 XLIFF 为目标文件,其中的问题主要是转换回去后,有未替换完的占位符
int placeHolderNum = 0;
for(char chr : textSB.toString().toCharArray()){
if (chr == '%') {
placeHolderNum ++;
}
}
if (placeHolderNum <= 6) {
tagParent = outputVU.getElementFragment();
}else {
tagParent = "";
}
}
return tagParent;
}
/**
* 起始标记不会丢失,结束标记会,因此获取出结束标记的数量,
* @param tagNumMap
*/
private void getStartAndEndTagStr(List<String> tagBorderList, String segId) throws Exception {
String xpath = "/TRADOStag/Body/Raw//Tu[@id='" + segId + "']" +
"/Tuv[@Lang='" + detectedSourceLang + "']/descendant::ut[@DisplayText=\"cf\"]";
outputAP.selectXPath(xpath);
int index = -1;
while (outputAP.evalXPath() != -1) {
if ((index = outputVN.getAttrVal("Type")) != -1) {
if ("start".equals(outputVN.toRawString(index))) {
tagBorderList.add("start");
}else if ("end".equals(outputVN.toRawString(index))) {
tagBorderList.add("end");
}
}
}
}
/**
* 替换掉骨架文件中的占位符
*
* @param segId
* @param srcBean
* @param tgtbeBean
*/
private void replaceSegment(String segId, String srcText, String tgtText) throws Exception {
String xpath = "/TRADOStag/Body/Raw//Tu[@id='" + segId + "']/Tuv";
outputAP.selectXPath(xpath);
int index = -1;
while (outputAP.evalXPath() != -1) {
if ((index = outputVN.getAttrVal("Lang")) != -1) {
String lang = outputVN.toRawString(index);
if (lang.equals(detectedSourceLang)) {
String tuvStr = outputVU.getElementHead() + (srcText == null ? "" : srcText) + "</Tuv>";
outputXM.remove();
outputXM.insertAfterElement(tuvStr);
}else if (lang.equals(detectedTargetLang)) {
if (tgtText != null && !"".equals(tgtText)) {
String tuvStr = outputVU.getElementHead() + "<df Font=\"Arial Unicode MS\">" + tgtText + "</df>" + "</Tuv>";
outputXM.remove();
outputXM.insertAfterElement(tuvStr.getBytes("UTF-8"));
}
}
}
}
}
/**
* 根据一个<g>标记的头部获取标记的 id 属性值
* @param tagStr
* @return
*/
private String getTagId(String tagStr) throws Exception {
String tagId = "";
VTDGen vg = new VTDGen();
vg.setDoc(tagStr.getBytes());
vg.parse(false);
VTDNav vn = vg.getNav();
tagAP = new AutoPilot(vn);
tagAP.selectXPath("/g");
int index = -1;
if (tagAP.evalXPath() != -1) {
if ((index = vn.getAttrVal("id")) != -1) {
tagId = vn.toRawString(index);
}
}
return tagId;
}
/**
* 获取源文件的源语言和目标语言
*/
private void getSrcAndTgtLang() throws Exception {
String srcLang = "";
String tgtLang = "";
String xpath = "/TRADOStag/FrontMatter/UserSettings";
outputAP.selectXPath(xpath);
int attrIdx = -1;
if (outputAP.evalXPath() != -1) {
if ((attrIdx = outputVN.getAttrVal("SourceLanguage")) != -1) {
srcLang = outputVN.toRawString(attrIdx);
}
if ((attrIdx = outputVN.getAttrVal("TargetLanguage")) != -1) {
tgtLang = outputVN.toRawString(attrIdx);
}
}
detectedSourceLang = srcLang;
//如果 ttx 的目标文件的目标语言为空,那设成转换的目标语言
detectedTargetLang = "".equals(tgtLang) ? "noLang" : tgtLang;
}
/**
* 针对没有目标语言节点为 noLang 的 Tvu,将之 lang 属性变成 "";
*/
private void deleteTgtLangIfNon() throws Exception {
String xpath = "/TRADOStag/Body/Raw//Tu/Tuv[@Lang='noLang']";
outputAP.selectXPath(xpath);
while(outputAP.evalXPath() != -1){
outputXM.updateToken(outputVN.getAttrVal("Lang"), "".getBytes("UTF-8"));
}
int index = -1;
xpath = "/TRADOStag/Body/Raw//Tu";
outputAP.selectXPath(xpath);
while(outputAP.evalXPath() != -1){
if ((index = outputVN.getAttrVal("id")) != -1) {
outputXM.removeAttribute(index - 1);
}
}
xpath = "/TRADOStag/Body/Raw//Tu//ut";
outputAP.selectXPath(xpath);
while(outputAP.evalXPath() != -1){
if ((index = outputVN.getAttrVal("id")) != -1) {
outputXM.removeAttribute(index - 1);
}
}
}
/**
* 处理 ph 节点
* @return
* @throws Exception
*/
private String replacePH(String phFrag) throws Exception{
String replaceText = "";
VTDGen vg = new VTDGen();
vg.setDoc(phFrag.getBytes());
vg.parse(true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
VTDUtils vu = new VTDUtils(vn);
ap.selectXPath("/ph");
String phContent = "";
int attrIdx = -1;
String utType = "";
String edgeStr = "";
if (ap.evalXPath() != -1) {
phContent = vu.getElementContent();
// 有type属性的,一般是cf标记
if ((attrIdx = vn.getAttrVal("type")) != -1) {
if ("cf".equals(vn.toString(attrIdx))) {
// 这个cf是开始还是结束<cf size="11" complexscriptssize="11">
if (phContent.indexOf("<cf") != -1) {
utType = "start";
edgeStr = "RightEdge=\"angle\"";
}else {
utType = "end";
edgeStr = "LeftEdge=\"angle\"";
}
replaceText += "<ut Type=\"" + utType + "\" "+ edgeStr +" DisplayText=\"cf\">" + phContent + "</ut>";
}
}else {
//没有type的,是其他标记,如<symbol font="Symbol" character="F0E2"/>
String tagName = "";
int startIdx = -1;
int endIdx = -1;
// 针对起始标记如<symbol font="Symbol" character="F0E2"/>
if ((startIdx = phContent.trim().indexOf("<")) != -1) {
//针对结束标记如</null?>
if ("/".equals(phContent.trim().substring(startIdx + 4, startIdx + 5))) {
tagName = phContent.trim().substring(startIdx + 5, phContent.trim().indexOf(">"));
utType = "end";
edgeStr = " LeftEdge=\"angle\"";
}else {
if ((endIdx = phContent.trim().indexOf(" ")) != -1) {
tagName = phContent.trim().substring(startIdx + 4, endIdx);
if (phContent.indexOf("/>") != -1) {
utType = "";
}else {
utType = "start";
edgeStr = " RightEdge=\"angle\"";
}
}else if((endIdx = phContent.trim().indexOf("/")) != -1) {
//针对没有空格的如<ph><field/></ph>
tagName = phContent.trim().substring(startIdx + 4, phContent.trim().indexOf("/"));
utType = "";
}else{
//针对 <field>
tagName = phContent.trim().substring(startIdx + 4, phContent.trim().indexOf(">"));
utType = "start";
edgeStr = " RightEdge=\"angle\"";
}
}
}
String utTypeAttrStr = utType.length() > 0 ? " Type=\""+utType+"\"" : "";
replaceText = "<ut"+ utTypeAttrStr + edgeStr +" DisplayText=\"" + tagName + "\">" + phContent + "</ut>";
}
}
return replaceText;
}
}
/**
* 将一个文件的数据复制到另一个文件
* @param in
* @param out
* @throws Exception
*/
private static void copyFile(String in, String out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
private static void copyFile(String oldFile, String newFilePath,
String strOldEncoding, String strNewEncoding) throws Exception {
FileInputStream fileInputStream = null;
InputStreamReader inputStreamRead = null;
BufferedReader bufferRead = null;
BufferedWriter newFileBW = null;
OutputStreamWriter outputStreamWriter = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(oldFile);
inputStreamRead = new InputStreamReader(fileInputStream,
strOldEncoding);
bufferRead = new BufferedReader(inputStreamRead);
fileOutputStream = new FileOutputStream(newFilePath, false);
outputStreamWriter = new OutputStreamWriter(fileOutputStream,
strNewEncoding);
newFileBW = new BufferedWriter(outputStreamWriter);
String strTSVLine = "";
while ((strTSVLine = bufferRead.readLine()) != null) {
if (strTSVLine.equals("")) {
continue;
}
newFileBW.write(strTSVLine.replaceAll("Shift_JIS", "UTF-8"));
newFileBW.write("\n");
}
} finally {
if (bufferRead != null)
bufferRead.close();
if (newFileBW != null) {
newFileBW.flush();
newFileBW.close();
}
}
}
public static void main(String[] args) {
// String content = "<g id='2'>this is a test</g>asdf as sad ";
// content = content.substring(0, content.lastIndexOf("</g>")) + content.substring(content.lastIndexOf("</g>") + 4);
// System.out.println(content);
// String content = "<g id='2'>this is a test</g>asdf as sad</g> ";
// int index = content.indexOf("</g>");
// content = "<cf" + content.substring(content.indexOf("<g") + 2, content.indexOf(">")) + ">";
// System.out.println(content);
int index = -1;
// String content = "<g id='2' size=\"11\" complexscriptssize=\"11\" complexscriptsbold=\"on\" bold=\"on\" superscript=\"on\"><ph><symbol font="Symbol" character="F0E2"/></ph></g>";
// String content = "<g id='2' size=\"11\" complexscriptssize=\"11\" complexscriptsbold=\"on\" bold=\"on\" superscript=\"on\"><ph><field/></ph></g>";
// String content = "<g id='2' size=\"11\" complexscriptssize=\"11\" complexscriptsbold=\"on\" bold=\"on\" superscript=\"on\"><ph></cf></ph></g><ph><field/></ph>";
String content = "<g id='2' size=\"11\" complexscriptssize=\"11\" complexscriptsbold=\"on\" bold=\"on\" superscript=\"on\"><ph></cf></ph></g>这后面是个cf标记了哦。<ph type='cf'></cf></ph>";
index = content.indexOf("<ph");
while(index != -1){
String phFrag = content.substring(index, content.indexOf("</ph>", index) + 5);
System.out.println(phFrag);
try {
VTDGen vg = new VTDGen();
vg.setDoc(phFrag.getBytes());
vg.parse(true);
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
VTDUtils vu = new VTDUtils(vn);
ap.selectXPath("/ph");
String replaceText = "";
String phContent = "";
int attrIdx = -1;
if (ap.evalXPath() != -1) {
phContent = vu.getElementContent();
// System.out.println("phContent = " + phContent);
// 有type属性的,一般是cf标记
if ((attrIdx = vn.getAttrVal("type")) != -1) {
if ("cf".equals(vn.toString(attrIdx))) {
String utType = "";
// 这个cf是开始还是结束<cf size="11" complexscriptssize="11">
if (phContent.indexOf("<cf") != -1) {
utType = "start";
}else {
utType = "end";
}
replaceText = "<ut Type=\"" + utType + "\" RightEdge=\"angle\" DisplayText=\"cf\">" + phContent + "</ut>";
}
}else {
//没有type的,是其他标记,如<symbol font="Symbol" character="F0E2"/>
String tagName = "";
int startIdx = -1;
int endIdx = -1;
// 针对起始标记如<symbol font="Symbol" character="F0E2"/>
if ((startIdx = phContent.trim().indexOf("<")) != -1) {
//针对结束标记如</null?>
if ("/".equals(phContent.trim().substring(startIdx + 4, startIdx + 5))) {
tagName = phContent.trim().substring(startIdx + 5, phContent.trim().indexOf(">"));
}else {
if ((endIdx = phContent.trim().indexOf(" ")) != -1) {
tagName = phContent.trim().substring(startIdx + 4, endIdx);
}else {
//针对没有空格的如<ph><field/></ph>
tagName = phContent.trim().substring(startIdx + 4, phContent.trim().indexOf("/"));
}
}
// System.out.println("tagName = '" + tagName + "'");
}
// System.out.println( "tagName = " + tagName);
replaceText = "<ut DisplayText=\"" + tagName + "\">" + phContent + "</ut>";
}
content = content.replace(phFrag, replaceText);
// System.out.println(content);
}
} catch (Exception e) {
e.printStackTrace();
}
index = content.indexOf("<ph", index + 1);
}
// System.out.println(content);
String tagStr = "<g id='1' size='12'/>";
String newTagStr = "<cf" + tagStr.substring(tagStr.indexOf("<g") + 2, tagStr.indexOf("/>")) + ">";
newTagStr = "<ut Type=\"start\" RightEdge=\"angle\" DisplayText=\"cf\">" + TextUtil.cleanSpecialString(newTagStr) + "</ut>";
// System.out.println("newTagStr = " + newTagStr);
}
}
| 31,341 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Ttx2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/Ttx2Xliff.java | /**
* Ttx2Xliff.java
*
* Version information :
*
* Date:Jun 16, 2012
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ttx;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.ttx.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.util.CRC16;
import net.heartsome.util.TextUtil;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* trados 2007 的 ttx(tradostag Xliff) 文件转换器。
* @author robert 2012-07-16
*/
public class Ttx2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-ttx";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("ttx.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "TTX to XLIFF Conveter";
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Ttx2XliffImpl converter = new Ttx2XliffImpl();
return converter.run(args, monitor);
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getName()
* @return
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getType()
* @return
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getTypeName()
* @return
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* trados 2007 ttx 文件的转换实现类
* @author robert
* @version
* @since JDK1.6
*/
class Ttx2XliffImpl {
/** 要转换的源文件 */
private String inputFile;
/** 转换后的 r8 hsxliff 文件 */
private String xliffFile;
/** 转换后的 r8 hsxliff 骨架文件 */
private String skeletonFile;
/** 用户所选择的源语言 */
private String userSourceLang;
/** 用户所选择的目标语言 */
private String targetLang;
/** 源文件 ttx 的源语言,解析文件时,要通过它来确定文件的源文。 */
private String detectedSourceLang;
/** 源文件 ttx 的目标语言,解析文件时,要通过它来确定文件的译文。 */
private String detectedTargetLang;
/** 选择的编码 */
private String srcEncoding;
/** 目标 hsxliff 文件的流输出类 */
private FileOutputStream output;
/** trans-unit 节点的id */
private int segId;
/** 标记的id */
private int tagId;
/** The lock xtrans. */
private boolean lockXtrans;
/** The lock100. */
private boolean lock100;
/** The is suite. */
private boolean isSuite;
/** The qt tool id. */
private String qtToolID;
/** 骨架文件的导航实例。 */
private VTDNav sklVN;
/** 骨架文件的 xml 修改实例。 */
private XMLModifier sklXM;
/** cf标记里是否要带走df的属性 */
/** 因源文缺失 结束标记而手动添加的 <cf> 的个数 */
private int addedEndTagNum = 0;
/**
* Run.
* @param params
* the params
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
// 把转换任务分为 5 个部分:复制文件,解析文件,处理内容列表,写骨架文件。
monitor.beginTask(Messages.getString("ttx.Ttx2Xliff.task1"), 5);
Map<String, String> result = new HashMap<String, String>();
segId = 0;
inputFile = params.get(Converter.ATTR_SOURCE_FILE);
xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
skeletonFile = params.get(Converter.ATTR_SKELETON_FILE);
targetLang = params.get(Converter.ATTR_TARGET_LANGUAGE);
userSourceLang = params.get(Converter.ATTR_SOURCE_LANGUAGE);
srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING);
// 下面三个是整理分段等逻辑时需要的参数。
// String elementSegmentation = params.get(Converter.ATTR_SEG_BY_ELEMENT);
// String initSegmenter = params.get(Converter.ATTR_SRX);
// String catalogue = params.get(Converter.ATTR_CATALOGUE);
isSuite = false;
if (Converter.TRUE.equalsIgnoreCase(params.get(Converter.ATTR_IS_SUITE))) {
isSuite = true;
}
qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID)
: Converter.QT_TOOLID_DEFAULT_VALUE;
// 默认锁定 xu 句段
lockXtrans = true;
// if (Converter.TRUE.equals(params.get(Converter.ATTR_LOCK_XTRANS))) {
// lockXtrans = true;
// }
lock100 = false;
if (Converter.TRUE.equals(params.get(Converter.ATTR_LOCK_100))) {
lock100 = true;
}
try {
// 将源文件复制进骨架文件,之后就从骨架文件中提取翻译信息。
if (!"utf-8".equalsIgnoreCase(srcEncoding)) {
// vtd在处理 UTF-16LE 时会出现 token 定位异常,故转换成 UTF-8 的格式
copyFile(inputFile, skeletonFile, srcEncoding, "UTF-8");
} else {
copyFile(inputFile, skeletonFile);
}
// copyFile(skeletonFile, "/home/robert/Desktop/testFile1.txt");
parseSkeletonFile();
boolean isAlert = false;
// 检测是否含有未翻译的文本段,如果含有则拒绝转换,原因是 R8中无法转换未预翻译的文本段
check(result);
monitor.worked(1);
getSrcAndTgtLang();
// copyFile(skeletonFile, "/home/robert/Desktop/a.txt");
output = new FileOutputStream(xliffFile);
parseSkeletonFile();
deleteDF();
writeHeader();
analyzeNodes();
writeString("</body>\n");
writeString("</file>\n");
writeString("</xliff>");
sklXM.output(skeletonFile);
addPHIdToXliff();
result.put(Converter.ATTR_XLIFF_FILE, xliffFile);
if (isAlert) {
throw new MissTranslationException();
}
} catch (OperationCanceledException e) {
e.printStackTrace();
throw e;
} catch (MissTranslationException e) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, MessageFormat.format(
Messages.getString("ttx.Ttx2Xliff.warn"), new Object[] { new File(inputFile).getName() }));
} catch (Exception e) {
e.printStackTrace();
ConverterUtils
.throwConverterException(Activator.PLUGIN_ID, Messages.getString("ttx.Ttx2Xliff.msg1"), e);
} finally {
monitor.done();
try {
if (output != null) {
output.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 删除 df 标记,因为 df 是保存 ttx 可见即可得的标记信息,可以删除。此功能主要是针对 df 标记太多从而影响很多 bug.
*/
private void deleteDF() throws Exception{
AutoPilot ap = new AutoPilot(sklVN);
VTDUtils vu = new VTDUtils(sklVN);
ap.declareXPathNameSpace("xml", VTDUtils.XML_NAMESPACE_URL);
int dfSize = 0;
ap.selectXPath("count(/TRADOStag/Body/Raw/descendant::df[not(descendant::df)])");
dfSize = (int)ap.evalXPathToNumber();
String dfContent = null;
while(dfSize > 0){
ap.selectXPath("/TRADOStag/Body/Raw/descendant::df[not(descendant::df)]");
while(ap.evalXPath() != -1){
dfContent = vu.getElementContent();
sklXM.remove();
if (dfContent != null) {
sklXM.insertAfterElement(dfContent.getBytes("UTF-8"));
}
}
sklXM.output(skeletonFile);
parseSkeletonFile();
ap.bind(sklVN);
vu.bind(sklVN);
ap.selectXPath("count(/TRADOStag/Body/Raw/descendant::df[not(descendant::df)])");
dfSize = (int)ap.evalXPathToNumber();
}
// copyFile(skeletonFile, "C:\\Users\\Ilen\\Desktop\\testTTX.txt");
}
/**
* 检查当前 ttx 是否是预翻译 --李庆东
* @param result
* @throws Exception
*/
private void check(Map<String, String> result) throws Exception {
sklVN.push();
AutoPilot ap = new AutoPilot(sklVN);
// 先查找是否有 tuv 节点的存在
ap.selectXPath("/TRADOStag/Body/Raw//Tu/Tuv");
if (ap.evalXPath() == -1) {
throw new MissTranslationException();
}
// 目前已知的两处可能含有未翻译的文本
ap.selectXPath("/TRADOStag/Body/Raw/text()|/TRADOStag/Body/Raw/df/text()");
while (ap.evalXPath() != -1) {
String text = sklVN.toString(sklVN.getCurrentIndex()).replaceAll("\\s", "").trim();
if (text.length() == 0) {
return;
}
//忽略字符请添加在此处
if (!(text.matches("[0-9\\.:\\-,–%#$\\s/]*") || text.matches("[a-zA-Z]*://.*") || text.matches(".*@.*"))) {
result.put("ttx2xlfAlert39238409230481092830", MessageFormat.format(
Messages.getString("ttx.Ttx2Xliff.warn"), new Object[] { new File(inputFile).getName() }));
}
}
}
/**
* Load files.
* @throws Exception
* the exception
*/
private void parseSkeletonFile() throws Exception {
String errorInfo = "";
VTDGen vg = new VTDGen();
if (vg.parseFile(skeletonFile, true)) {
sklVN = vg.getNav();
sklXM = new XMLModifier(sklVN);
} else {
errorInfo = MessageFormat.format("无法解析源文件 {0} 。", new Object[] { new File(inputFile).getName() });
throw new Exception(errorInfo);
}
}
/**
* 获取源文件的源语言和目标语言
*/
private void getSrcAndTgtLang() throws Exception {
String srcLang = "";
String tgtLang = "";
AutoPilot ap = new AutoPilot(sklVN);
String xpath = "/TRADOStag/FrontMatter/UserSettings";
ap.selectXPath(xpath);
int attrIdx = -1;
if (ap.evalXPath() != -1) {
if ((attrIdx = sklVN.getAttrVal("SourceLanguage")) != -1) {
srcLang = sklVN.toRawString(attrIdx);
}
if ((attrIdx = sklVN.getAttrVal("TargetLanguage")) != -1) {
tgtLang = sklVN.toRawString(attrIdx);
}
}
detectedSourceLang = srcLang;
// 如果 ttx 的目标文件的目标语言为空,那设成转换的目标语言
detectedTargetLang = "".equals(tgtLang) ? targetLang : tgtLang;
// 如果当前转换的目标语言也为空,那设成标识 noLang,之后转换完了再在骨架文件中进行替换
detectedTargetLang = "".equals(detectedTargetLang) ? "noLang" : detectedTargetLang;
}
/**
* 写下 R8 hsxliff 文件的头信息
*/
private void writeHeader() throws IOException {
writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writeString("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\""
+ Converter.HSNAMESPACE + "\" "
+ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd "
+ Converter.HSSCHEMALOCATION + "\">\n");
writeString("<file original=\"" + TextUtil.cleanString(inputFile) + "\" source-language=\""
+ userSourceLang);
if (!"".equals(detectedTargetLang)) {
writeString("\" target-language=\"" + detectedTargetLang);
}
writeString("\" datatype=\"" + TYPE_VALUE + "\">\n");
writeString("<header>\n");
writeString(" <skl>\n");
String crc = "";
if (isSuite) {
crc = "crc=\"" + CRC16.crc16(TextUtil.cleanString(skeletonFile).getBytes("UTF-8")) + "\"";
}
writeString(" <external-file href=\"" + TextUtil.cleanString(skeletonFile) + "\" " + crc + "/>\n");
writeString(" </skl>\n");
writeString(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n");
writeString(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" + srcEncoding
+ "</hs:prop></hs:prop-group>\n");
writeString("</header>\n");
writeString("<body>\n");
}
/**
* 分析骨架文件的每一个节点,主要是针对tu节点
* @throws Exception
*/
private void analyzeNodes() throws Exception {
tagId = 0;
int attrIdx = -1;
// 保存的是要翻译的源文文本与标记
Map<Integer, TextBean> srcTextMap = new TreeMap<Integer, TextBean>();
// 保存的是要翻译的译文文本与标记
Map<Integer, TextBean> tgtTextMap = new TreeMap<Integer, TextBean>();
AutoPilot ap = new AutoPilot(sklVN);
AutoPilot childAP = new AutoPilot(sklVN);
VTDUtils vu = new VTDUtils(sklVN);
String xpath = "/TRADOStag/Body/Raw/descendant::Tu";
String srcXpath = "./Tuv[@Lang=\"" + detectedSourceLang + "\"]";
String tgtXapth = "./Tuv[@Lang=\"" + detectedTargetLang + "\" and (text()!='' or *)]";
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
// 第一步,处理源节点
sklVN.push();
childAP.selectXPath(srcXpath);
if (childAP.evalXPath() != -1) {
srcTextMap.clear();
if (vu.getChildElementsCount() > 0) {
analysisChildOfSrcTuv(srcTextMap, sklVN, vu);
} else if ((attrIdx = sklVN.getText()) != -1) {
if (!"".equals(sklVN.toRawString(attrIdx))) {
sklXM.updateToken(attrIdx, "%%%" + tagId + "%%%");
srcTextMap.put(attrIdx, new TextBean(tagId, sklVN.toRawString(attrIdx), true));
tagId++;
}
}
}
sklVN.pop();
// <Tuv Lang="EN-US">See the enclosure <ut DisplayText="xr"><:xr "“Specifications” on
// page<:hs>20" 2></ut>.</Tuv>
// 第二步,验证是否需要进行转换成trans-unit节点
boolean neenConvert = false;
if (srcTextMap.size() > 0) {
if (srcTextMap.size() == 1) {
for (Entry<Integer, TextBean> entry : srcTextMap.entrySet()) {
if (entry.getValue().getTagId() != -1) {
// tag若等于 -1 ,则是标记,标记没有必须生成trans-unit节点
neenConvert = true;
}
}
} else {
for (Entry<Integer, TextBean> entry : srcTextMap.entrySet()) {
if (entry.getValue().getTagId() != -1) {
// tag为1,则全是标记,没有必要进行生成tu节点
neenConvert = true;
}
}
}
// 如果不用转换,直接跳到下一循环处
if (!neenConvert) {
continue;
}
}
// 第三步,处理目标节点
sklVN.push();
childAP.selectXPath(tgtXapth);
tgtTextMap.clear();
if (childAP.evalXPath() != -1) {
if (vu.getChildElementsCount() > 0) {
analysisChildOfTgtTuv(tgtTextMap, sklVN, vu);
} else if ((attrIdx = sklVN.getText()) != -1) {
if (!"".equals(sklVN.toRawString(attrIdx))) {
tgtTextMap.put(attrIdx, new TextBean(-1, sklVN.toRawString(attrIdx), true));
}
}
// 删除译文节点的内容
String tuvHeader = vu.getElementHead();
sklXM.remove();
sklXM.insertAfterElement(tuvHeader + "</Tuv>");
}
sklVN.pop();
// 第四步,处理目标文本集合的内容。
addedEndTagNum = 0;
Map<Integer, String> tagMap = new LinkedHashMap<Integer, String>(); // 保存标记与标记的占位符
String srcText = analysisSrcTextMap(srcTextMap, tagMap);
String tgtText = analysisTgtTextMap(tgtTextMap, tagMap);
// 第五步,开始生成trans-unit节点
sklXM.insertAttribute(" id=\"" + segId + "\"");
// 转存一些关于tu节点的属性,
int match = 0;
if ((attrIdx = sklVN.getAttrVal("MatchPercent")) != -1) {
String matchPercent = sklVN.toRawString(attrIdx);
if (!matchPercent.equals("")) {
match = Integer.parseInt(matchPercent);
}
}
String origin = "";
if ((attrIdx = sklVN.getAttrVal("Origin")) != -1) {
origin = sklVN.toRawString(attrIdx);
}
boolean isLock = false;
boolean isXtranslate = false;
if ("xtranslate".equalsIgnoreCase(origin) && lockXtrans) {
isLock = true;
isXtranslate = true;
}
if (match >= 100 && lock100) {
isLock = true;
}
writeSegment(srcText, tgtText, match, isLock, isXtranslate);
}
}
/**
* 分析tuv节点下面的所有节点,获取出要翻译的文本段
*/
private void analysisChildOfSrcTuv(Map<Integer, TextBean> textMap, VTDNav vn, VTDUtils vu) throws Exception {
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "./node()|text()";
ap.selectXPath(xpath);
int index = -1;
while (ap.evalXPath() != -1) {
int curIdx = vn.getCurrentIndex();
int tokenType = vn.getTokenType(curIdx);
// 等于0表示为节点
if (tokenType == 0) {
// 如果这个节点还有子节点。那么遍历其子节点
if (vu.getChildElementsCount() > 0) {
analysisChildOfSrcTuv(textMap, vn, vu);
} else {
String nodeName = vu.getCurrentElementName();
if ("df".equals(nodeName)) {
// df节点下的数据,直接加载。
if ((index = vn.getText()) != -1) {
sklXM.updateToken(index, "%%%" + tagId + "%%%");
textMap.put(index, new TextBean(tagId, vn.toRawString(index), true));
tagId++;
}
} else if ("ut".equals(nodeName)) {
// ut节点下保存的是cf标记信息,要将它进行转义
if ((index = vn.getText()) != -1) {
// 这种情况,为cf标记
if (vn.getAttrVal("DisplayText") != -1
&& "cf".equals(sklVN.toString(vn.getAttrVal("DisplayText")))) {
textMap.put(index, new TextBean(-1, vn.toString(index), false));
} else {
// 处理除cf之外的其他标记,如symbol,这时一般当文本处理
sklXM.remove();
sklXM.insertBeforeElement("%%%" + tagId + "%%%");
textMap.put(index, new TextBean(tagId, vn.toString(index), false));
tagId++;
}
}
}
}
} else if (tokenType == 5) { // 等于5表示为文本子节点
index = vn.getCurrentIndex();
sklXM.updateToken(index, "%%%" + tagId + "%%%");
textMap.put(index, new TextBean(tagId, vn.toRawString(index), true));
tagId++;
}
}
vn.pop();
}
/**
* 分析译文tuv节点下面的所有节点,获取出要翻译的文本段,但不占位,只获取文本
*/
private void analysisChildOfTgtTuv(Map<Integer, TextBean> tgtTextMap, VTDNav vn, VTDUtils vu) throws Exception {
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "./*|text()";
ap.selectXPath(xpath);
int index = -1;
while (ap.evalXPath() != -1) {
int curIdx = vn.getCurrentIndex();
int tokenType = vn.getTokenType(curIdx);
// 等于0表示为节点
if (tokenType == 0) {
// 如果这个节点还有子节点。那么遍历其子节点
if (vu.getChildElementsCount() > 0) {
analysisChildOfTgtTuv(tgtTextMap, vn, vu);
} else {
String nodeName = vu.getCurrentElementName();
if ("df".equals(nodeName)) {
// df节点下的数据,直接加载。
if ((index = vn.getText()) != -1) {
tgtTextMap.put(index, new TextBean(-1, vn.toRawString(index), true));
}
} else if ("ut".equals(nodeName)) {
// ut节点下保存的是cf标记信息,要将它进行转义
if ((index = vn.getText()) != -1) {
if (vn.getAttrVal("Type") != -1) {
tgtTextMap.put(index, new TextBean(-1, vn.toString(index), false));
} else {
// 若 ut 节点没有 Type 属性,一般为除cf之外的其他标记,如symbol,这时一般当文本处理
tgtTextMap.put(index, new TextBean(-1, vn.toString(index), false));
}
}
}
}
} else if (tokenType == 5) { // 等于5表示为文本子节点
index = vn.getCurrentIndex();
tgtTextMap.put(index, new TextBean(-1, vn.toRawString(index), true));
}
}
vn.pop();
}
/**
* 分析处理源或目标文本,主要是处理cf标记,若第一行的标记为一个</cf>,那么删除, 若缺少<cf>的结束标记,自动补全,还有种情况就是<cf>标记在tu节点之外的情况。
*/
private String analysisSrcTextMap(Map<Integer, TextBean> srcMap, Map<Integer, String> tagMap) {
StringBuffer testSB = new StringBuffer();
for (Entry<Integer, TextBean> entry : srcMap.entrySet()) {
testSB.append(entry.getValue().getText());
}
// if (testSB.toString().indexOf("See the enclosure") >= 0) {
// System.out.println("处理开始了。。。。");
//
// }
TextBean[] beans = srcMap.values().toArray(new TextBean[] {});
StringBuffer sb = new StringBuffer();
int i = 0;
int start = 0; // 是否遇到起始标记
int end = 0;
for (Entry<Integer, TextBean> entry : srcMap.entrySet()) {
TextBean bean = entry.getValue();
String text = resetText(entry.getValue().getText());
if (bean.getTagId() == -1) {
// 标记的起始符号
if (text.indexOf("<cf ") != -1) {
if (i + 1 < beans.length) {
// 处于标记对的,添加到结果集中,否则以ph的形式出现。这是针对开始或结束时,有多余的cf标记的情况
tagMap.put(beans[i + 1].getTagId(), text);
start++;
sb.append(text);
} else {
sb.append("<ph type='cf'>" + cleanString(text) + "</ph>");
}
}
// 标记的结束符号
if (bean.getText().indexOf("</") != -1) {
// 处于标记对的,添加到结果集中,否则以ph的形式出现。这是针对开始或结束时,有多余的cf标记的情况
if (start > 0 && start > end) {
sb.append(entry.getValue().getText());
end++;
} else {
sb.append("<ph type='cf'>" + cleanString(entry.getValue().getText()) + "</ph>");
}
}
} else {
// 添加纯文本,纯文本里面也有标记,比如<symbol font="Symbol" character="F0E2"/>
if (!bean.isText()) { // 如果是<symbol font="Symbol" character="F0E2"/>类似的。就变成 ph 标记
text = "<ph>" + cleanString(text) + "</ph>";
}
sb.append(text);
}
i++;
}
// 最后时,如果缺少一个标签,自动补全。
for (int j = 0; j < start - end; j++) {
addedEndTagNum++;
sb.append("</cf>");
}
String srcText = sb.toString();
return replaceR8Tag(srcText, tagMap);
}
/**
* 分析处理目标文本,主要是处理cf标记,若第一行的标记为一个</cf>,那么以ph的形式出现, 若缺少<cf>的结束标记,自动补全,还有种情况就是<cf>标记在tu节点之外的情况。
* 备注:目标文本与源文不一样的是,目标文本里所有的文本都是没有占位符编号的。这个占位符编号要从译文的srcTextMap中获取,当然此时这些编号都存放在了tagMap中了。
*/
private String analysisTgtTextMap(Map<Integer, TextBean> tgtMap, Map<Integer, String> tagMap) {
StringBuffer testSB = new StringBuffer();
for (Entry<Integer, TextBean> entry : tgtMap.entrySet()) {
testSB.append(entry.getValue().getText());
}
StringBuffer sb = new StringBuffer();
int i = 0;
int start = 0; // 是否遇到起始标记
int end = 0;
for (Entry<Integer, TextBean> entry : tgtMap.entrySet()) {
String text = resetText(entry.getValue().getText());
if (!entry.getValue().isText()) {
// 标记的起始符号
if (text.indexOf("<cf ") != -1) {
if (i + 1 < tgtMap.size()) { // 这是开始标记,如果是最后一个值,那么,它以ph的形式出现
start++;
sb.append(text);
} else {
sb.append("<ph type='cf'>" + cleanString(text) + "</ph>");
}
} else if (text.indexOf("</cf>") != -1) { // 标记的结束符号
// 处于标记对的,添加到结果集中,否则以ph的形式出现。这是针对开始或结束时,有多余的cf标记的情况
if (start > 0 && start > end) {
sb.append(text);
end++;
} else {
sb.append("<ph type='cf'>" + cleanString(text) + "</ph>");
}
} else {
// 添加纯文本,纯文本里面也有标记,比如<symbol font="Symbol" character="F0E2"/>
text = "<ph>" + cleanString(text) + "</ph>";
sb.append(text);
}
} else {
sb.append(text);
}
i++;
}
// 最后时,如果缺少一个标签,自动补全。
for (int j = 0; j < start - end; j++) {
sb.append("</cf>");
}
String srcText = sb.toString();
return replaceR8Tag(srcText, tagMap);
}
/**
* 将ttx的cf标记替换成R8的 g 标记
*/
private String replaceR8Tag(String text, Map<Integer, String> tagMap) {
String replacedText = text;
String tagStr = ""; // 标签字符串
String replaceStr = ""; // 要把标记头替换的内容
int index = replacedText.indexOf("<cf ");
int endIndex = -1;
int tagSegId = -1; // 标签所对应的占位符
while (index != -1) {
endIndex = replacedText.indexOf(">", index);
tagStr = replacedText.substring(index, endIndex + 1);
tagSegId = getTagSegmentId(tagStr, tagMap);
if (tagSegId == -1) {
replaceStr = "<g";
} else {
replaceStr = "<g id='" + tagSegId + "'";
}
replacedText = replacedText.replaceFirst("<cf", replaceStr);
index = replacedText.indexOf("<cf ");
}
replacedText = replacedText.replaceAll("</cf>", "</g>");
return replacedText;
}
/**
* 根据标记的头节点获取标记所对应的占位符
* @param tagStr
* @param tagMap
* @return
*/
private int getTagSegmentId(String tagStr, Map<Integer, String> tagMap) {
int tagSegId = -1;
for (Entry<Integer, String> entry : tagMap.entrySet()) {
if (tagStr.equals(entry.getValue())) {
tagSegId = entry.getKey();
break;
}
}
return tagSegId;
}
/**
* 将ut节点下的标记信息进行转义
* @param value
* @return
*/
private String resetText(String value) {
value = value.replaceAll(""", "\"");
return value;
}
/**
* 向 r8 hslixff 文件写入数据
*/
private void writeString(String string) throws IOException {
output.write(string.getBytes("UTF-8"));
}
/**
* 开始填充文本
* @param source
* @param target
* @param match
* @param isLock
* @param isXtranslate
* @throws IOException
*/
private void writeSegment(String source, String target, int match, boolean isLock, boolean isXtranslate)
throws IOException {
String approved = match > 100 ? "yes" : "no";
String matchStr = match > 0 ? " hs:matchType=\"TM\" hs:quality=\"" + match + "\"" : "";
if (!isLock) {
writeString(" <trans-unit id=\"" + segId + "\" xml:space=\"preserve\" approved=\"" + approved
+ "\" addedEndTagNum='" + addedEndTagNum + "'>\n" + " <source xml:lang=\"" + userSourceLang
+ "\">");
} else {
writeString(" <trans-unit id=\"" + segId + "\" xml:space=\"preserve\" translate=\"no\" approved=\""
+ approved + "\" addedEndTagNum='" + addedEndTagNum + "'>\n" + " <source xml:lang=\""
+ userSourceLang + "\">");
}
writeString(source + "</source>\n ");
if (!target.equals("")) {
if (!targetLang.equals("")) {
writeString(" <target xml:lang=\"" + targetLang + "\" state=\"new\"" + matchStr + ">" + target
+ "</target>\n");
} else {
writeString(" <target state=\"new\"" + matchStr + ">" + target + "</target>\n");
}
}
if (match >= 100 && !targetLang.equals("")) {
if (!isXtranslate) {
writeString(" <alt-trans xml:space=\"preserve\" match-quality=\"100\" tool=\"Trados or Similar\">"
+ " <source xml:lang=\"" + userSourceLang + "\">");
} else {
writeString(" <alt-trans xml:space=\"preserve\" match-quality=\"100\" tool=\"Trados or Similar\" origin=\"Xtranslate\">"
+ " <source xml:lang=\"" + userSourceLang + "\">");
}
writeString(source + "</source>");
writeString(" <target xml:lang=\"" + targetLang + "\"\n>");
writeString(target + "</target>\n");
writeString(" </alt-trans>\n");
}
writeString(" </trans-unit>\n");
segId++;
}
/**
* 向 xliff 文件中的 ph 标记添加 id 属性。
*/
private void addPHIdToXliff() throws Exception {
int phId = 1;
VTDGen vg = new VTDGen();
boolean parseResult = vg.parseFile(xliffFile, true);
if (!parseResult) {
throw new Exception();
}
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
AutoPilot childAP = new AutoPilot(vn);
XMLModifier xm = new XMLModifier(vn);
VTDUtils vu = new VTDUtils(vn);
String xpath = "/xliff/file/body//trans-unit";
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
Map<Integer, String> phMap = new HashMap<Integer, String>();
// 先循环 src 中的 ph 标记
vn.push();
childAP.selectXPath("./source/descendant::ph");
while (childAP.evalXPath() != -1) {
phMap.put(phId, vu.getElementFragment());
xm.insertAttribute(" id='" + (phId++) + "'");
}
vn.pop();
// 再循环 target 中的 ph 标记
vn.push();
childAP.selectXPath("./target//ph");
while (childAP.evalXPath() != -1) {
boolean findExsit = false;
String tgtPhFrag = vu.getElementFragment();
for (Entry<Integer, String> entry : phMap.entrySet()) {
String srcPhFrag = entry.getValue();
if (tgtPhFrag.equals(srcPhFrag)) {
findExsit = true;
int srcPhId = entry.getKey();
phMap.remove(srcPhId);
xm.insertAttribute(" id='" + srcPhId + "'");
break;
}
}
if (!findExsit) {
xm.insertAttribute(" id='" + (phId++) + "'");
}
}
vn.pop();
}
xm.output(xliffFile);
}
}
/**
* Copy file.
* @param in
* the in
* @param out
* the out
* @throws Exception
* the exception
*/
private static void copyFile(String in, String out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
private static void copyFile(String oldFile, String newFilePath, String strOldEncoding, String strNewEncoding)
throws Exception {
FileInputStream fileInputStream = null;
InputStreamReader inputStreamRead = null;
BufferedReader bufferRead = null;
BufferedWriter newFileBW = null;
OutputStreamWriter outputStreamWriter = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(oldFile);
inputStreamRead = new InputStreamReader(fileInputStream, strOldEncoding);
bufferRead = new BufferedReader(inputStreamRead);
fileOutputStream = new FileOutputStream(newFilePath, false);
outputStreamWriter = new OutputStreamWriter(fileOutputStream, strNewEncoding);
newFileBW = new BufferedWriter(outputStreamWriter);
String strTSVLine = "";
while ((strTSVLine = bufferRead.readLine()) != null) {
if (strTSVLine.equals("")) {
continue;
}
newFileBW.write(strTSVLine.replaceAll("Shift_JIS", "UTF-8"));
newFileBW.write("\n");
}
} finally {
if (bufferRead != null)
bufferRead.close();
if (newFileBW != null) {
newFileBW.flush();
newFileBW.close();
}
}
}
/**
* 将ut节点下的标记信息进行转义
* @param value
* @return
*/
private static String cleanString(String value) {
value = value.replaceAll("&", "&");
value = value.replaceAll("<", "<");
value = value.replaceAll("\"", """);
value = value.replaceAll(">", ">");
return value;
}
public static void main(String[] args) {
// String filePath = "ttx/testXml.xml";
// VTDGen vg = new VTDGen();
// vg.parseFile(filePath, true);
// VTDNav vn = vg.getNav();
// try {
// AutoPilot ap = new AutoPilot(vn);
// AutoPilot childAP = new AutoPilot(vn);
// ap.selectXPath("/books/book[@id='4']");
// XMLModifier xm = new XMLModifier(vn);
// while (ap.evalXPath() != -1) {
// vn.push();
// childAP.selectXPath("preceding::book");
// while (childAP.evalXPath() != -1) {
// System.out.println(vn.toString(vn.getAttrVal("id")));
// }
// vn.pop();
// }
// xm.output(filePath);
//
// } catch (Exception e) {
// e.printStackTrace();
// }
try {
copyFile("/Users/Mac/Desktop/a.txt", "/Users/Mac/Desktop/b.txt", "UTF-8", "UTF-16LE");
} catch (Exception e) {
e.printStackTrace();
}
}
} | 34,152 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TextBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/TextBean.java | package net.heartsome.cat.converter.ttx;
public class TextBean {
private int tagId;
private String text;
/** 这个属性是用于逆转换的,也就是文本段所处在节点的内容,这个节点一般是df */
private String parentFrag;
/** 这个属性是用于逆转换的,是否有标记 */
private boolean hasTag;
/** 标识此文本段是否是纯文本还是标记 */
private boolean isText;
public TextBean(){}
public TextBean(int tagId, String text, boolean isText){
this.tagId = tagId;
this.text = text;
this.isText = isText;
}
public int getTagId() {
return tagId;
}
public void setTagId(int tagId) {
this.tagId = tagId;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getParentFrag() {
return parentFrag;
}
public void setParentFrag(String parentFrag) {
this.parentFrag = parentFrag;
}
public boolean isHasTag() {
return hasTag;
}
public void setHasTag(boolean hasTag) {
this.hasTag = hasTag;
}
public boolean isText() {
return isText;
}
public void setText(boolean isText) {
this.isText = isText;
}
}
| 1,151 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MissTranslationException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/MissTranslationException.java | package net.heartsome.cat.converter.ttx;
public class MissTranslationException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
}
| 179 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.ttx/src/net/heartsome/cat/converter/ttx/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.ttx.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* The Class Messages.
* @author John Zhu
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.ttx.resource.ttx"; //$NON-NLS-1$
/** The Constant RESOURCE_BUNDLE. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
/**
* Instantiates a new messages.
*/
private Messages() {
// Do nothing
}
/**
* Gets the string.
* @param key
* the key
* @return the string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| 1,013 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
MsExcel2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/MsExcel2Xliff.java | /**
* MsExcel2Xliff.java
*
* Version information :
*
* Date:2012-8-9
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.StringSegmenter;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.preference.Constants;
import net.heartsome.cat.converter.msexcel2007.reader.SpreadsheetReader;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.util.TextUtil;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class MsExcel2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "Microsoft Office Excel 2007";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("msexcel.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "MS Excel 2007 to XLIFF Conveter";
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
MsExcel2XliffImpl impl = new MsExcel2XliffImpl();
return impl.run(args, monitor);
}
public String getName() {
return NAME_VALUE;
}
public String getType() {
return TYPE_VALUE;
}
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class MsExcel2XliffImpl {
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask(Messages.getString("msexcel.mse2xliff.task1"), 4);
Map<String, String> result = new HashMap<String, String>();
String inputFile = params.get(Converter.ATTR_SOURCE_FILE);
String xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
String skeletonFile = params.get(Converter.ATTR_SKELETON_FILE);
String sourceLanguage = params.get(Converter.ATTR_SOURCE_LANGUAGE);
String encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
// load segment
monitor.worked(1);
String catalogue = params.get(Converter.ATTR_CATALOGUE);
String initSegmenter = params.get(Converter.ATTR_SRX);
StringSegmenter segmenter = null;
try {
segmenter = new StringSegmenter(initSegmenter, sourceLanguage, catalogue);
} catch (Exception e) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("msexcel.mse2xliff.msg1") + e.getMessage(), e);
}
BufferedWriter xlfWriter = null;
SpreadsheetReader reader = new SpreadsheetReader(sourceLanguage, segmenter);
try {
xlfWriter = new BufferedWriter(new FileWriter(xliffFile));
// generation the header of xliff file
writeXliffHeader(xlfWriter, inputFile, sourceLanguage, skeletonFile, encoding);
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
reader.read2XliffFile(inputFile, xlfWriter, skeletonFile, store.getBoolean(Constants.EXCEL_FILTER),
new SubProgressMonitor(monitor, 3));
// generation the end of xliff file
writeXliffTail(xlfWriter);
} catch (IOException e) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID,
Messages.getString("msexcel.converter.exception.msg2") + e.getMessage(), e);
} catch (InternalFileException e) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, e.getMessage(), e);
} catch (Exception e) {
String msg = e.getMessage() == null ? "" : e.getMessage();
ConverterUtils
.throwConverterException(
Activator.PLUGIN_ID,
MessageFormat.format(Messages.getString("msexcel.converter.exception.msg2"),
msg), e);
} finally {
if (xlfWriter != null) {
try {
xlfWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
monitor.done();
result.put(Converter.ATTR_XLIFF_FILE, xliffFile);
return result;
}
private void writeXliffHeader(BufferedWriter xlfWriter, String inputFile, String srcLang, String sklFile,
String encoding) throws IOException {
xlfWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xlfWriter.write("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:hs=\""
+ Converter.HSNAMESPACE + "\" "
+ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd "
+ Converter.HSSCHEMALOCATION + "\">\n");
xlfWriter.write("<file original=\"" + TextUtil.cleanString(inputFile) + "\" source-language=\"" + srcLang
+ "\" datatype=\"" + TYPE_VALUE + "\">\n");
xlfWriter.write("<header>\n");
xlfWriter.write(" <skl>\n");
xlfWriter.write(" <external-file href=\"" + TextUtil.cleanString(sklFile) + "\"/>\n"); //$NON-NLS-2$ //$NON-NLS-3$
xlfWriter.write(" </skl>\n");
xlfWriter
.write(" <tool tool-id=\"" + Converter.QT_TOOLID_DEFAULT_VALUE + "\" tool-name=\"HSStudio\"/>\n"); //$NON-NLS-2$
xlfWriter.write(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">" + encoding
+ "</hs:prop></hs:prop-group>\n");
xlfWriter.write("</header>\n");
xlfWriter.write("<body>\n");
}
private void writeXliffTail(BufferedWriter xlfWriter) throws IOException {
xlfWriter.write("</body>\n");
xlfWriter.write("</file>\n");
xlfWriter.write("</xliff>");
}
}
}
| 5,945 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/Activator.java | package net.heartsome.cat.converter.msexcel2007;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.ConverterRegister;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class Activator extends AbstractUIPlugin implements BundleActivator {
public static final String PLUGIN_ID = "net.heartsome.cat.converter.msexcel2007";
private ServiceRegistration<?> excel2XLIFFSR;
private ServiceRegistration<?> xliff2excelSR;
private static BundleContext context;
private static Activator plugin;
static BundleContext getContext() {
return context;
}
/*
* (non-Javadoc)
*
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext bundleContext) throws Exception {
super.start(bundleContext);
Activator.context = bundleContext;
Converter excel2xliff = new MsExcel2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, MsExcel2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, MsExcel2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, MsExcel2Xliff.TYPE_NAME_VALUE);
excel2XLIFFSR = ConverterRegister.registerPositiveConverter(context, excel2xliff, properties);
Converter xliff2excel = new Xliff2MsExcel();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2MsExcel.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2MsExcel.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2MsExcel.TYPE_NAME_VALUE);
xliff2excelSR = ConverterRegister.registerReverseConverter(context, xliff2excel, properties);
plugin = this;
}
/*
* (non-Javadoc)
*
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext bundleContext) throws Exception {
plugin = null;
if (excel2XLIFFSR != null) {
excel2XLIFFSR.unregister();
excel2XLIFFSR = null;
}
if (xliff2excelSR != null) {
xliff2excelSR.unregister();
xliff2excelSR = null;
}
Activator.context = null;
super.stop(bundleContext);
}
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
public static Activator getDefault() {
return plugin;
}
}
| 2,486 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2MsExcel.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/Xliff2MsExcel.java | /**
* MsExcel2Xliff.java
*
* Version information :
*
* Date:2012-8-9
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.reader.XliffReader;
import net.heartsome.cat.converter.util.ConverterUtils;
import org.eclipse.core.runtime.IProgressMonitor;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class Xliff2MsExcel implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "Microsoft Office Excel 2007";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = "Microsoft Office Excel 2007";
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to MS Excel 2007 Conveter";
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
Xliff2MsExcelImpl impl = new Xliff2MsExcelImpl();
return impl.run(args, monitor);
}
public String getName() {
return NAME_VALUE;
}
public String getType() {
return TYPE_VALUE;
}
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class Xliff2MsExcelImpl {
// skeleton 文件编码
// private String encoding;
// private FileOutputStream output;
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
Map<String, String> result = new HashMap<String, String>();
String sklFile = params.get(Converter.ATTR_SKELETON_FILE);
String xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
String outputFile = params.get(Converter.ATTR_TARGET_FILE);
// encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
XliffReader reader = new XliffReader();
try {
reader.read2SpreadsheetDoc(outputFile, xliffFile, sklFile, monitor);
result.put(Converter.ATTR_TARGET_FILE, outputFile);
} catch (InternalFileException e) {
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, e.getMessage(), e);
}
return result;
}
}
}
| 2,250 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SpreadsheetReader.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/reader/SpreadsheetReader.java | /**
* XliffReader.java
*
* Version information :
*
* Date:2012-8-2
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.reader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.converter.StringSegmenter;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.ZipUtil;
import net.heartsome.cat.converter.msexcel2007.document.Cell;
import net.heartsome.cat.converter.msexcel2007.document.DrawingsPart;
import net.heartsome.cat.converter.msexcel2007.document.HeaderFooter;
import net.heartsome.cat.converter.msexcel2007.document.SheetPart;
import net.heartsome.cat.converter.msexcel2007.document.SpreadsheetDocument;
import net.heartsome.cat.converter.msexcel2007.document.WorkBookPart;
import net.heartsome.cat.converter.msexcel2007.document.drawing.CellAnchor;
import net.heartsome.cat.converter.msexcel2007.document.drawing.ShapeParagraph;
import net.heartsome.cat.converter.msexcel2007.document.drawing.ShapeTxBody;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class SpreadsheetReader {
private BufferedWriter xlfOs;
/** The source file language */
private String srcLang;
/** The XLiff TransUnit index counter */
private int xliffIdex;
/** The text segmentter */
private StringSegmenter segmenter;
private List<Integer> filterStyleIndex;
public SpreadsheetReader(String sourceLanguage, StringSegmenter segmenter) {
this.srcLang = sourceLanguage;
this.xliffIdex = 1;
this.segmenter = segmenter;
this.filterStyleIndex = new ArrayList<Integer>();
}
/**
* 将内容读入到XLIFF文件
* @param xlfOs
* XLIFF文件BufferWriter
* @param filterRedCell
* 是否需要过滤标记为红色的单元格
* @param monitor
* @throws InternalFileException
* @throws IOException
* ;
*/
public void read2XliffFile(String inputFile, BufferedWriter xlfOs, String sklFilePath, boolean filterRedCell,
IProgressMonitor monitor) throws InternalFileException, IOException {
this.xlfOs = xlfOs;
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", 5);
try {
monitor.setTaskName(Messages.getString("msexcel.mse2xliff.task2"));
// open source file
SpreadsheetDocument.open(inputFile);
monitor.worked(1);
monitor.setTaskName(Messages.getString("msexcel.mse2xliff.task3"));
// load current workbook
WorkBookPart wb = SpreadsheetDocument.workBookPart;
if (filterRedCell) {
this.filterStyleIndex = wb.getStylesPart().getFilterCellStyle();
}
// read worksheet
List<SheetPart> sheetList = wb.getSheetParts();
readSheets(sheetList, new SubProgressMonitor(monitor, 2));
// save current document
wb.save();
monitor.worked(1);
monitor.setTaskName(Messages.getString("msexcel.mse2xliff.task4"));
// generate skl file
saveSklFile(sklFilePath);
monitor.worked(1);
} finally {
SpreadsheetDocument.close();
}
monitor.done();
}
private void saveSklFile(String sklPath) {
try {
ZipUtil.zipFolder(sklPath, SpreadsheetDocument.spreadsheetPackage.getPackageSuperRoot());
} catch (IOException e) {
e.printStackTrace();
}
}
private void readSheets(List<SheetPart> sheetList, IProgressMonitor monitor)
throws InternalFileException, IOException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask("", sheetList.size() * 5);
for (SheetPart sp : sheetList) {
// process sheet name
String name = sp.getName();
writeXliffFile(xliffIdex, name);
sp.setSheetName("%%%" + xliffIdex + "%%%");
xliffIdex++;
monitor.worked(1);
// read headers
List<HeaderFooter> headers = sp.getHeader();
readHeaderFooters(headers);
sp.setHeaderFooter(headers); // update the file
monitor.worked(1);
// read drawing part
DrawingsPart drawingp = sp.getDrawingsPart();
if (drawingp != null) {
readDrawings(drawingp);
drawingp.updateDrawingObject();
}
monitor.worked(1);
List<Cell> cellList = sp.getCells("s");
for (Cell c : cellList) {
if (filterStyleIndex.contains(c.getStyleIndex())) {
// skip this cell
continue;
}
String cellText = c.getValue();
if(cellText == null || cellText.trim().length() == 0){
// ignore the cell
continue;
}
List<Object[]> cellStyle = c.getCellCharacterStyles();
String[] segs = segmenter.segment(cellText);
StringBuffer bf = new StringBuffer();
for (String seg : segs) {
List<Object[]> s = ReaderUtil.getSegStyle(cellStyle, seg, cellText);
if (s.size() != 0) {
seg = ReaderUtil.appendSegStyle(seg, s);
}
bf.append("%%%").append(xliffIdex++).append("%%%");
// System.out.println(xliffIdex + ":" + seg);
writeXliffFile(xliffIdex - 1, seg);
}
c.setValue(bf.toString());
}
monitor.worked(1);
// read headers
List<HeaderFooter> footers = sp.getFoolter();
readHeaderFooters(footers);
sp.setHeaderFooter(footers); // update the file
monitor.worked(1);
}
monitor.done();
}
private void readDrawings(DrawingsPart drawingp) throws IOException {
List<CellAnchor> aList = drawingp.getCellAnchorList();
for (CellAnchor a : aList) {
List<ShapeTxBody> sList = a.getShapeList();
if (sList.size() == 0) {
continue;
}
for (ShapeTxBody s : sList) {
List<ShapeParagraph> pList = s.getTxBodyParagraghList();
for (ShapeParagraph p : pList) {
String txt = p.getParagraghText();
if (txt.length() == 0) {
continue;
}
List<Object[]> txtStyle = p.getParagraghCharacterStyle();
String[] segs = segmenter.segment(txt);
StringBuffer bf = new StringBuffer();
for (String seg : segs) {
if (txtStyle.size() > 1) {
List<Object[]> style = ReaderUtil.getSegStyle(txtStyle, seg, txt);
if (style.size() != 0) {
seg = ReaderUtil.appendSegStyle(seg, style);
}
}
bf.append("%%%").append(xliffIdex).append("%%%");
writeXliffFile(xliffIdex, seg);
xliffIdex++;
}
// System.out.println(bf.toString());
p.setParagraghText(bf.toString());
}
}
}
}
private void readHeaderFooters(List<HeaderFooter> headerFooters) throws IOException {
for (HeaderFooter hf : headerFooters) {
String content = ReaderUtil.reCleanTag(hf.getContent());
String[] lcr = splitHeaderFooter(content);
StringBuffer skl = new StringBuffer();
for (String s : lcr) {
if (s.length() == 0) {
continue;
}
StringBuffer text = new StringBuffer();
readSplitedContent(s, skl, text);
if (text.length() == 0) {
continue;
}
writeXliffFile(xliffIdex - 1, text.toString());
}
hf.setContent(ReaderUtil.cleanTag(skl.toString()));
}
}
private void readSplitedContent(String s, StringBuffer skl, StringBuffer text) {
char[] array = s.toCharArray();
int p = 0;
for (int i = 0; i < array.length; i++) {
char ch = array[i];
if (ch == '&') {
i++;
if (array[i] == '"') {
i++;
while (array[i] != '"') {
i++;
}
}
} else {
p = i;
break;
}
}
if (p == 0) {
skl.append(s);
return;
}
skl.append(s.substring(0, p)).append("%%%").append(xliffIdex++).append("%%%");
String temp = s.substring(p);
int ep = 0;
int tp = temp.indexOf('&');
if (tp != -1) {
do {
text.append(temp.substring(ep, tp));
if (temp.charAt(tp + 1) == '"') {
int tpp = temp.indexOf('"', tp + 2);
String t1 = temp.substring(tp, tpp + 1);
text.append("<ph>").append(ReaderUtil.cleanTag(t1)).append("</ph>");
ep = tpp + 1;
} else {
String t1 = temp.substring(tp, tp + 2);
if ((tp + 2) == temp.length()) {
skl.append(t1);
break;
} else {
text.append("<ph>").append(ReaderUtil.cleanTag(t1)).append("</ph>");
ep = tp + 2;
}
}
int tpp = temp.indexOf('&', tp + 2);
if (tpp == -1 && (tp + 2) != temp.length()) {
text.append(temp.substring(ep));
break;
}
tp = tpp;
} while (tp != -1);
} else {
text.append(temp);
}
}
private String[] splitHeaderFooter(String c) {
String left = "";
String center = "";
String right = "";
int lp = c.indexOf("&L");
int cp = c.indexOf("&C");
int rp = c.indexOf("&R");
if (lp != -1) {
if (cp != -1) {
left = c.substring(lp, cp);
} else if (rp != -1) {
left = c.substring(lp, rp);
} else {
left = c;
}
}
if (cp != -1) {
if (rp != -1) {
center = c.substring(cp, rp);
} else {
center = c.substring(cp);
}
}
if (rp != -1) {
right = c.substring(rp);
}
String[] result = new String[3];
result[0] = left;
result[1] = center;
result[2] = right;
return result;
}
private void writeXliffFile(int tuId, String sourceSeg) throws IOException {
xlfOs.write(" <trans-unit id=\"" + tuId++ + "\" xml:space=\"preserve\">\n" + " <source xml:lang=\""
+ srcLang + "\">" + sourceSeg + "</source>\n" + " </trans-unit>\n");
// System.out.println(tuId + ":" + sourceSeg);
}
}
| 9,412 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
XliffReader.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/reader/XliffReader.java | /**
* XliffReader.java
*
* Version information :
*
* Date:2012-8-10
*
* Copyright notice :
* 本文件及其附带的相关文件包含机密信息,仅限瀚特盛科技有限公司指定的,与本项目有关的内部人员和客户联络人员查阅和使用。
* 如果您不是本保密声明中指定的收件者,请立即销毁本文件,禁止对本文件或根据本文件中的内容采取任何其他行动,
* 包括但不限于:泄露本文件中的信息、以任何方式制作本文件全部或部分内容之副本、将本文件或其相关副本提供给任何其他人。
*/
package net.heartsome.cat.converter.msexcel2007.reader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.ZipUtil;
import net.heartsome.cat.converter.msexcel2007.document.Cell;
import net.heartsome.cat.converter.msexcel2007.document.DrawingsPart;
import net.heartsome.cat.converter.msexcel2007.document.HeaderFooter;
import net.heartsome.cat.converter.msexcel2007.document.SheetPart;
import net.heartsome.cat.converter.msexcel2007.document.SpreadsheetDocument;
import net.heartsome.cat.converter.msexcel2007.document.WorkBookPart;
import net.heartsome.cat.converter.msexcel2007.document.drawing.CellAnchor;
import net.heartsome.cat.converter.msexcel2007.document.drawing.ShapeParagraph;
import net.heartsome.cat.converter.msexcel2007.document.drawing.ShapeTxBody;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class XliffReader {
public static final Logger logger = LoggerFactory.getLogger(XliffReader.class);
private VTDUtils vu;
public XliffReader() {
}
public void read2SpreadsheetDoc(String spreadsheetDocFile, String xliffFile, String sklFile,
IProgressMonitor monitor) throws InternalFileException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask(Messages.getString("msexcel.xliff2mse.task1"), 5);
loadFile(xliffFile);
monitor.worked(1);
monitor.setTaskName(Messages.getString("msexcel.xliff2mse.task2"));
try {
SpreadsheetDocument.open(sklFile);
monitor.worked(1);
WorkBookPart wb = SpreadsheetDocument.workBookPart;
List<SheetPart> sheetList = wb.getSheetParts();
readSheet(sheetList, new SubProgressMonitor(monitor, 1));
monitor.setTaskName(Messages.getString("msexcel.xliff2mse.task3"));
wb.save();
monitor.worked(1);
try {
ZipUtil.zipFolder(spreadsheetDocFile, SpreadsheetDocument.spreadsheetPackage.getPackageSuperRoot());
} catch (IOException e) {
logger.error("", e);
}
monitor.worked(1);
} finally {
SpreadsheetDocument.close();
monitor.done();
}
}
private void readSheet(List<SheetPart> sheetList, IProgressMonitor monitor) throws InternalFileException {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
monitor.beginTask(Messages.getString("msexcel.xliff2mse.task4"), sheetList.size() * 5);
List<String> sheetNames = new ArrayList<String>();
for (SheetPart sp : sheetList) {
monitor.worked(1);
String name = sp.getName();
name = processContent(name);
// 处理重复名称
int i = 1;
while (sheetNames.contains(name)) {
name += i;
i++;
}
sheetNames.add(name);
sp.setSheetName(name);
// read headers
monitor.worked(1);
List<HeaderFooter> headers = sp.getHeader();
for (HeaderFooter hf : headers) {
String content = hf.getContent();
content = processContent(content);
hf.setContent(content);
}
sp.setHeaderFooter(headers); // update the file
monitor.worked(1);
DrawingsPart drawingp = sp.getDrawingsPart();
if (drawingp != null) {
List<CellAnchor> aList = drawingp.getCellAnchorList();
for (CellAnchor a : aList) {
List<ShapeTxBody> sList = a.getShapeList();
if (sList.size() == 0) {
continue;
}
for (ShapeTxBody s : sList) {
List<ShapeParagraph> pList = s.getTxBodyParagraghList();
for (ShapeParagraph p : pList) {
String content = p.getXmlContent();
content = processContent(content);
p.setXmlContent(content);
}
}
}
drawingp.updateDrawingObject();
}
monitor.worked(1);
List<Cell> cellList = sp.getCells("s");
for (Cell c : cellList) {
String content = c.getFullContent();
content = processContent(content);
c.setShareStringItemFullContent(content);
}
monitor.worked(1);
// read footer
List<HeaderFooter> footers = sp.getFoolter();
for (HeaderFooter hf : footers) {
String content = hf.getContent();
content = processContent(content);
hf.setContent(content);
}
sp.setHeaderFooter(footers); // update the file
}
monitor.done();
}
private String processContent(String content) throws InternalFileException {
String result = content;
int sos = content.indexOf("%%%");
while (sos != -1) {
sos += 3;
int eos = content.indexOf("%%%", sos);
String code = content.substring(sos, eos);
eos += 3;
String t = getTargetById(code);
result = result.replace("%%%" + code + "%%%", t);
sos = content.indexOf("%%%", eos);
}
return result;
}
public static void main(String[] args) throws InternalFileException {
XliffReader r = new XliffReader();
r.read2SpreadsheetDoc("d:\\ot1\\test1.xlsx", "d:\\ot1\\test1_zh-CN.xlsx.hsxliff", "d:\\ot1\\test1.xlsx.skl",
null);
}
private String getTargetById(String id) throws InternalFileException {
String result = null;
String xpath = "/xliff/file/body/trans-unit[@id='" + id + "']";
AutoPilot ap = new AutoPilot(vu.getVTDNav());
try {
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
String text = vu.getChildContent("./target");
if (text == null) {
text = vu.getChildContent("./target");
vu.pilot("./source");
} else {
vu.pilot("./target");
}
Map<Integer, String[]> anaysisRs = anaysisTarget();
result = converterAnaysisResult(anaysisRs);
}
} catch (VTDException e) {
logger.error("", e);
}
if (result == null) {
throw new InternalFileException(MessageFormat.format(Messages.getString("msexcel.xliff2mse.msg1"), id));
}
return result;
}
private String converterAnaysisResult(Map<Integer, String[]> targetMap) {
List<String[]> list = new ArrayList<String[]>();
Set<Entry<Integer, String[]>> entrys = targetMap.entrySet();
for (Entry<Integer, String[]> entry : entrys) {
list.add(entry.getValue());
}
StringBuffer bf = new StringBuffer();
String tAttr = " xml:space=\"preserve\"";
for (int i = 0; i < list.size(); i++) {
String[] val = list.get(i);
// System.out.print(val[0]);
String text = val[0] == null ? "" : val[0];
String style = val[1];
if (style == null) {
bf.append(text);
continue;
}
style = ReaderUtil.reCleanAttribute(style);
String ns = val[2];
String tagr = "r";
String tagt = "t";
if (ns != null && ns.length() != 0) {
tagr = ns + ":" + tagr;
tagt = ns + ":" + tagt;
}
bf.append('<').append(tagr).append('>').append(style); // <r> <rpr></rpr>
bf.append('<').append(tagt);
if(!tagt.equals("a:t")){
bf.append(tAttr);
}
bf.append('>').append(text); // <t>text
while (i + 1 < list.size() && list.get(i + 1)[2] != null && list.get(i + 1)[2].equals(style)) {
val = list.get(i + 1);
text = val[0] == null ? "" : val[0];
bf.append(text);
i++;
}
bf.append('<').append('/').append(tagt).append('>');
bf.append('<').append('/').append(tagr).append('>');
}
// System.out.println(bf);
return bf.toString();
}
private Map<Integer, String[]> anaysisTarget() throws VTDException {
Map<Integer, String[]> targetMap = new TreeMap<Integer, String[]>();
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("./node() | text()");
while (ap.evalXPath() != -1) {
int index = vu.getVTDNav().getCurrentIndex();
int tokenType = vu.getVTDNav().getTokenType(index);
if (tokenType == 0) {
ananysisTag(targetMap);
} else if (tokenType == 5) {
targetMap.put(index, new String[] { vu.getVTDNav().toRawString(index), null, null });
}
}
return targetMap;
}
private void ananysisTag(Map<Integer, String[]> targetMap) throws VTDException {
VTDNav vn = vu.getVTDNav();
vn.push();
int idex = vn.getCurrentIndex();
String tagName = vn.toString(idex);
if ("g".equals(tagName)) {
String ctype = vu.getCurrentElementAttribut("ctype", null);
String rpr = vu.getCurrentElementAttribut("rPr", "");
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("./node() | text()");
while (ap.evalXPath() != -1) {
idex = vn.getCurrentIndex();
int tokenType = vn.getTokenType(idex);
if (tokenType == 0) {
String name = vu.getCurrentElementName();
if ("ph".equals(name)) {
targetMap.put(idex, new String[] { vu.getElementContent(), rpr, ctype });
} else if ("g".equals(name)) {
ananysisTag(targetMap);
}
} else if (tokenType == 5) {
targetMap.put(idex, new String[] { vn.toRawString(idex), rpr, ctype });
}
}
} else if ("ph".equals(tagName)) {
targetMap.put(idex, new String[] { vu.getElementContent(), null, null });
} else { // 其他节点,一律当做字符串处理
targetMap.put(idex, new String[] { vu.getElementFragment(), null, null });
}
vn.pop();
}
private void loadFile(String file) throws InternalFileException {
File f = new File(file);
VTDGen vg = new VTDGen();
FileInputStream fis = null;
byte[] b = new byte[(int) f.length()];
try {
fis = new FileInputStream(f);
fis.read(b);
} catch (IOException e) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
logger.error("", e);
}
}
}
vg.setDoc(b);
try {
vg.parse(true);
vu = new VTDUtils(vg.getNav());
} catch (VTDException e) {
String message = Messages.getString("msexcel.converter.exception.msg1");
message += "\nFile:" + f.getName() + "\n" + e.getMessage();
throw new InternalFileException(message);
}
}
}
| 10,865 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ReaderUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/reader/ReaderUtil.java | package net.heartsome.cat.converter.msexcel2007.reader;
import java.util.ArrayList;
import java.util.List;
public class ReaderUtil {
public static String appendSegStyle(String seg, List<Object[]> styleList) {
StringBuffer bf = new StringBuffer(seg);
StringBuffer result = new StringBuffer();
int styledId = 1;
for (Object[] obj : styleList) {
int start = (Integer) obj[0];
int end = (Integer) obj[1];
String style = (String) obj[2];
result.append("<g id=\""+ styledId++ +"\" ").append(style).append(">");
result.append(bf.substring(start, end)).append("</g>");
}
return result.toString();
}
public static List<Object[]> getSegStyle(List<Object[]> styles, String seg, String content) {
List<Object[]> result = new ArrayList<Object[]>();
int segSos = content.indexOf(seg);
int segEos = segSos + seg.length();
int baseSos = segSos;
for (Object[] obj : styles) {
Object[] temp = obj.clone();
int styleSos = (Integer) temp[0];
int styleEos = (Integer) temp[1];
if (segSos == styleSos && segEos == styleEos) {
temp[0] = styleSos - baseSos;
temp[1] = styleEos - baseSos;
result.add(temp);
break;
}
if (segSos <= styleSos) {
temp[0] = styleSos - baseSos;
if (segEos < styleEos) {
temp[1] = segEos - baseSos;
result.add(temp);
break;
} else if (segEos > styleEos) {
temp[1] = styleEos - baseSos;
result.add(temp);
segSos = styleEos;
}
}
if (segSos > styleSos && segSos < styleEos) {
temp[0] = segSos - baseSos;
if (segEos <= styleEos) {
temp[1] = segEos - baseSos;
result.add(temp);
break;
} else if (styleEos < segEos) {
temp[1] = styleEos - baseSos;
result.add(temp);
segSos = styleEos;
}
}
}
return result;
}
/**
* This method cleans the text that will be stored inside <ph>elements in the XLIFF file *.
* @param line
* the line
* @return the string
*/
public static String cleanTag(String line) {
String s = line;
int control = s.indexOf("&");
while (control != -1) {
s = s.substring(0, control) + "&" + s.substring(control + 1);
if (control < s.length()) {
control++;
}
control = s.indexOf("&", control);
}
control = s.indexOf("<");
while (control != -1) {
s = s.substring(0, control) + "<" + s.substring(control + 1);
if (control < s.length()) {
control++;
}
control = s.indexOf("<", control);
}
control = s.indexOf(">");
while (control != -1) {
s = s.substring(0, control) + ">" + s.substring(control + 1);
if (control < s.length()) {
control++;
}
control = s.indexOf(">", control);
}
return s;
}
public static String cleanAttribute(String line){
String s = cleanTag(line);
int control = s.indexOf('"');
while (control != -1) {
s = s.substring(0, control) + """ + s.substring(control + 1);
if (control < s.length()) {
control++;
}
control = s.indexOf('"', control);
}
return s;
}
public static String reCleanAttribute(String line){
String s = line;
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll(""", "\"");
s = s.replaceAll("&", "&");
return s;
}
public static String reCleanTag(String line) {
String s = line;
s = s.replaceAll("<", "<");
s = s.replaceAll(">", ">");
s = s.replaceAll("&", "&");
return s;
}
}
| 3,425 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
InternalFileException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/common/InternalFileException.java | package net.heartsome.cat.converter.msexcel2007.common;
public class InternalFileException extends Exception {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
public InternalFileException(){
super();
}
public InternalFileException(String message){
super(message);
}
}
| 311 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SpreadsheetUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/common/SpreadsheetUtil.java | /**
* SpreadsheetUtil.java
*
* Version information :
*
* Date:2012-8-1
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.common;
import java.io.File;
import java.io.FileNotFoundException;
import net.heartsome.cat.converter.msexcel2007.document.AbstractPart;
import net.heartsome.cat.converter.msexcel2007.document.SpreadsheetDocument;
import net.heartsome.cat.converter.msexcel2007.document.SpreadsheetPackage;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class SpreadsheetUtil {
public static String getPartXml(String target, boolean isBack2TopLeve) throws FileNotFoundException {
SpreadsheetPackage spkg = SpreadsheetDocument.spreadsheetPackage;
if (spkg == null || target == null || target.length() == 0) {
throw new NullPointerException();
}
String r = spkg.getPackageFilePath(target);
if (isBack2TopLeve) {
spkg.back2TopLeve();
}
return r;
}
public static String getPartRelsTarget(AbstractPart part) throws FileNotFoundException {
String containerPartXml = part.getPartXmlPath();
File f = new File(containerPartXml);
String partXmlName = f.getName();
partXmlName = "_rels/" + partXmlName + ".rels";
return getPartXml(partXmlName, true);
}
public static void assertNull(Object obj) throws InternalFileException {
if (obj == null) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
}
}
| 1,496 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ReadXliffException.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/common/ReadXliffException.java | package net.heartsome.cat.converter.msexcel2007.common;
public class ReadXliffException extends Exception {
/** serialVersionUID. */
private static final long serialVersionUID = 1L;
public ReadXliffException(){
super();
}
public ReadXliffException(String message){
super(message);
}
}
| 302 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Constants.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/common/Constants.java | package net.heartsome.cat.converter.msexcel2007.common;
public interface Constants {
String WORKBOOK_PATH = "xl/workbook.xml";
String PART_TYPE_SST = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings";
String PART_TYPE_STYLE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles";
String NAMESPACE_DRAWING_PREFIX_XDR = "xdr";
String NAMESPACE_DRAWING_URL_XDR = "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing";
String NAMESPACE_DRAWING_PREFIX_A = "a";
String NAMESPACE_DRAWING_URL_A = "http://schemas.openxmlformats.org/drawingml/2006/main";
}
| 641 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ZipUtil.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/common/ZipUtil.java | package net.heartsome.cat.converter.msexcel2007.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
/**
* 压缩文件夹
* @param zipPath
* 生成的zip文件路径
* @param filePath
* 需要压缩的文件夹路径
* @throws Exception
*/
public static void zipFolder(String zipPath, String filePath) throws IOException {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipPath));
File f = new File(filePath);
zipFiles(out, f, "");
out.close();
}
/**
* 将压缩文件中的内容解压到指定目录中<br>
* 如果<code>baseDir</code>的值为空,则将文件解压到相同的目录中,目录名称为"zipFile_files"
* @param zipFile
* 压缩文件路径
* @param baseDir
* 解压的目标路径,可以为null
* @throws IOException
*/
public static String upZipFile(String zipFile, String baseDir) throws IOException {
File f = new File(zipFile);
if (baseDir == null) {
baseDir = f.getPath() + "_files";
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(f));
ZipEntry ze;
byte[] buf = new byte[1024];
while ((ze = zis.getNextEntry()) != null) {
File outFile = getRealFileName(baseDir, ze.getName());
FileOutputStream os = new FileOutputStream(outFile);
int readLen = 0;
while ((readLen = zis.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
os.close();
}
zis.close();
return baseDir;
}
/**
* 递归调用,压缩文件夹和子文件夹的所有文件
* @param out
* @param f
* @param base
* @throws Exception
*/
private static void zipFiles(ZipOutputStream out, File f, String base) throws IOException {
if (f.isDirectory()) {
File[] fl = f.listFiles();
// out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zipFiles(out, fl[i], base + fl[i].getName());// 递归压缩子文件夹
}
} else {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
// System.out.println(base);
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
}
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
private static File getRealFileName(String baseDir, String absFileName) {
String[] dirs = absFileName.split("/");
File ret = new File(baseDir);
if (!ret.exists()) {
ret.mkdirs();
}
if (dirs.length >= 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
if (!ret.exists()) {
ret.mkdirs();
}
ret = new File(ret, dirs[dirs.length - 1]);
if(!ret.exists()){
File p = ret.getParentFile();
if(!p.exists()){
p.mkdirs();
}
}
}
return ret;
}
}
| 3,189 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ConverterPreferenceInitializer.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/preference/ConverterPreferenceInitializer.java | package net.heartsome.cat.converter.msexcel2007.preference;
import net.heartsome.cat.converter.msexcel2007.Activator;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* 设置首选项文件类型下的默认值类
* @author peason
* @version
* @since JDK1.6
*/
public class ConverterPreferenceInitializer extends AbstractPreferenceInitializer {
@Override
public void initializeDefaultPreferences() {
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
store.setDefault(Constants.EXCEL_FILTER, false);
}
}
| 629 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Constants.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/preference/Constants.java | package net.heartsome.cat.converter.msexcel2007.preference;
/**
* 常量类
* @author peason
* @version
* @since JDK1.6
*/
public final class Constants {
/** 首选项-->Microsoft Excel 2007 页面的提示信息图片 */
public static final String PREFERENCE_EXCEL_32 = "images/preference/excel_32.png";
public static final String EXCEL_FILTER = "net.heartsome.cat.converter.msexcel2007.preference.Excel";
}
| 428 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ExcelPreferencePage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/preference/ExcelPreferencePage.java | package net.heartsome.cat.converter.msexcel2007.preference;
import net.heartsome.cat.common.ui.HsImageLabel;
import net.heartsome.cat.converter.msexcel2007.Activator;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* 首选项-->Microsoft Excel 2007 页面
* @author peason
* @version
* @since JDK1.6
*/
public class ExcelPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private IPreferenceStore preferenceStore;
private Button btnRedFont;
public ExcelPreferencePage() {
setTitle(Messages.getString("preference.ExcelPreferencePage.title"));
setPreferenceStore(Activator.getDefault().getPreferenceStore());
preferenceStore = getPreferenceStore();
}
@Override
protected Control createContents(Composite parent) {
Composite tparent = new Composite(parent, SWT.NONE);
tparent.setLayout(new GridLayout());
tparent.setLayoutData(new GridData(GridData.FILL_BOTH));
Group groupCommon = new Group(tparent, SWT.NONE);
groupCommon.setLayout(new GridLayout());
groupCommon.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
groupCommon.setText(Messages.getString("preference.ExcelPreferencePage.groupCommon"));
HsImageLabel imageLabel = new HsImageLabel(
Messages.getString("preference.ExcelPreferencePage.imageLabel"),
Activator.getImageDescriptor(Constants.PREFERENCE_EXCEL_32));
Composite cmpCommon = imageLabel.createControl(groupCommon);
cmpCommon.setLayout(new GridLayout());
cmpCommon.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
btnRedFont = new Button(cmpCommon, SWT.CHECK);
btnRedFont.setText(Messages.getString("preference.ExcelPreferencePage.btnRedFont"));
GridDataFactory.fillDefaults().applyTo(btnRedFont);
imageLabel.computeSize();
btnRedFont.setSelection(preferenceStore.getBoolean(Constants.EXCEL_FILTER));
return parent;
}
public void init(IWorkbench workbench) {
}
@Override
protected void performDefaults() {
btnRedFont.setSelection(preferenceStore.getDefaultBoolean(Constants.EXCEL_FILTER));
}
@Override
public boolean performOk() {
preferenceStore.setValue(Constants.EXCEL_FILTER, btnRedFont.getSelection());
return true;
}
}
| 2,705 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SheetPart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/SheetPart.java | package net.heartsome.cat.converter.msexcel2007.document;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.SpreadsheetUtil;
import net.heartsome.cat.converter.msexcel2007.document.rels.Relationship;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
public class SheetPart extends AbstractPart {
private String name;
private String sheetId;
private RelsPart relsPart;
private DrawingsPart drawingsPart;
private List<Cell> cellList;
private List<HeaderFooter> headers;
private List<HeaderFooter> footers;
public SheetPart(String name, String sheetId, String target) throws InternalFileException, FileNotFoundException {
super(SpreadsheetUtil.getPartXml(target, false));
this.name = name;
this.sheetId = sheetId;
try {
this.relsPart = new RelsPart(this); // load relationship
} catch (FileNotFoundException e) {
// no rels resource
this.relsPart = null;
}
SpreadsheetDocument.spreadsheetPackage.back2TopLeve();
if (this.relsPart != null) {
loadDrawingsPart();
}
loadHeaderFooter();
}
public List<Cell> getCells(String dataType) throws InternalFileException {
cellList = new ArrayList<Cell>();
String xpath = "/worksheet/sheetData/row/c[@t='" + dataType + "']";
AutoPilot ap = new AutoPilot(vu.getVTDNav());
try {
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
Hashtable<String, String> attrs = vu.getCurrentElementAttributs();
SpreadsheetUtil.assertNull(attrs);
String styleIndex = attrs.get("s");
styleIndex = styleIndex == null ? "-1" : styleIndex;
String val = vu.getChildContent("v");
val = val == null ? "" : val;
Cell cell = new Cell(val, Integer.parseInt(styleIndex), dataType);
cellList.add(cell);
}
} catch (VTDException e) {
logger.error("", e);
}
return cellList;
}
/***
* 将Share String Tbale中的数据填充满,即每一个引用都对应独立的String item
* @param sst
* ;
* @throws InternalFileException
*/
public int fillShareStringTable(ShareStringTablePart sst, int index,StringBuffer siBf) throws InternalFileException {
String xpath = "/worksheet/sheetData/row/c[@t='s']/v";
try {
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
String c = vu.getElementContent();
int cInt = 0;
try {
cInt = Integer.parseInt(c);
} catch (NumberFormatException e) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
siBf.append(sst.getStringItemFragment(cInt));
xm.updateToken(vu.getVTDNav().getCurrentIndex() + 1, index+"");
index++;
}
saveAndReload();
} catch (VTDException e) {
logger.error("", e);
} catch (UnsupportedEncodingException e) {
logger.error("", e);
}
return index;
}
public String getName() {
return this.name;
}
public DrawingsPart getDrawingsPart() {
return drawingsPart;
}
public void setSheetName(String name) {
this.name = name;
SpreadsheetDocument.workBookPart.updateSheetName(sheetId, name);
}
public List<HeaderFooter> getHeader() {
return this.headers;
}
public void setHeaderFooter(List<HeaderFooter> headerFooters) {
this.headers = headerFooters;
for (HeaderFooter h : headerFooters) {
String xpath = "/worksheet/headerFooter/" + h.getType() + "/text()";
vu.update(null, xm, xpath, h.getContent());
}
}
public List<HeaderFooter> getFoolter() {
return this.footers;
}
private void loadDrawingsPart() throws InternalFileException {
String xpath = "/worksheet/drawing";
AutoPilot ap = new AutoPilot(vu.getVTDNav());
try {
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
Hashtable<String, String> attrs = vu.getCurrentElementAttributs();
SpreadsheetUtil.assertNull(attrs);
String rId = attrs.get("r:id");
Relationship r = relsPart.getRelationshipById(rId);
SpreadsheetUtil.assertNull(r);
SpreadsheetDocument.spreadsheetPackage.markRoot();
try {
this.drawingsPart = new DrawingsPart(r.getTarget());
} catch (FileNotFoundException e) {
// no drawingsPart
}
SpreadsheetDocument.spreadsheetPackage.resetRoot();
}
} catch (VTDException e) {
logger.error("", e);
}
}
private void loadHeaderFooter() {
this.headers = new ArrayList<HeaderFooter>();
this.footers = new ArrayList<HeaderFooter>();
String xpath = "/worksheet/headerFooter/*";
AutoPilot ap = new AutoPilot(vu.getVTDNav());
try {
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
String type = vu.getCurrentElementName();
String c = vu.getElementContent();
HeaderFooter e = new HeaderFooter(type, c);
if (type.equals("oddHeader") || type.equals("evenHeader") || type.equals("firstHeader")) {
headers.add(e);
} else if (type.equals("oddFooter") || type.equals("evenFooter") || type.equals("firstFooter")) {
footers.add(e);
}
}
} catch (VTDException e) {
logger.error("", e);
}
}
}
| 5,297 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
WorkBookPart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/WorkBookPart.java | package net.heartsome.cat.converter.msexcel2007.document;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.converter.msexcel2007.common.Constants;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.SpreadsheetUtil;
import net.heartsome.cat.converter.msexcel2007.document.rels.Relationship;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class WorkBookPart extends AbstractPart {
private RelsPart relsPart;
private List<SheetPart> sheetPartList;
private ShareStringTablePart sst;
private StylesPart stylePart;
public WorkBookPart() throws InternalFileException, FileNotFoundException {
super(SpreadsheetUtil.getPartXml(Constants.WORKBOOK_PATH, false));
this.relsPart = new RelsPart(this);
loadShareStringTable();
loadSytlesPart();
loadWorkSheets();
}
public List<SheetPart> getSheetParts() {
return sheetPartList;
}
public ShareStringTablePart getShareStringTablePart() {
return sst;
}
public StylesPart getStylesPart() {
return stylePart;
}
private void loadWorkSheets() throws InternalFileException, FileNotFoundException {
sheetPartList = new ArrayList<SheetPart>();
int ssiIndex = 0;
StringBuffer siBf = new StringBuffer();
try {
String xpath = "/workbook/sheets/sheet";
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
int index = vu.getVTDNav().getAttrVal("name");
if (index == -1) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
String name = vu.getVTDNav().toRawString(index);
index = vu.getVTDNav().getAttrVal("sheetId");
if (index == -1) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
String id = vu.getVTDNav().toRawString(index);
index = vu.getVTDNav().getAttrVal("r:id");
if (index == -1) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
String rid = vu.getVTDNav().toRawString(index);
Relationship r = relsPart.getRelationshipById(rid);
SpreadsheetUtil.assertNull(r);
String target = r.getTarget();
SheetPart sp = new SheetPart(name, id, target);
ssiIndex = sp.fillShareStringTable(sst, ssiIndex, siBf);
sheetPartList.add(sp);
}
// fix bug Bug #2925 转换excel文件--空指针异常,转换失败 by jason
if (sst != null && siBf.length() != 0) {
sst.updateShareStringTable(siBf.toString());
}
} catch (VTDException e) {
logger.error("", e);
} catch (IOException e) {
}
}
private void loadShareStringTable() throws InternalFileException {
List<Relationship> rList = relsPart.getRelationshipByType(Constants.PART_TYPE_SST);
if (rList.size() != 1) {
return;
}
Relationship r = rList.get(0);
try {
sst = new ShareStringTablePart(r.getTarget());
} catch (FileNotFoundException e) {
// 可能没有sharedStrings.xml
}
}
private void loadSytlesPart() throws InternalFileException, FileNotFoundException {
List<Relationship> rList = relsPart.getRelationshipByType(Constants.PART_TYPE_STYLE);
if (rList.size() != 1) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
Relationship r = rList.get(0);
stylePart = new StylesPart(r.getTarget());
}
void updateSheetName(String sheetId, String sheetName) {
String xpath = "/workbook/sheets/sheet[@sheetId = '" + sheetId + "']/@name";
vu.update(null, xm, xpath, sheetName);
}
@Override
public void save() throws InternalFileException {
for (SheetPart s : sheetPartList) {
s.save();
}
if (this.sst != null) {
this.sst.save();
}
super.save();
}
}
| 3,991 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SpreadsheetDocument.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/SpreadsheetDocument.java | package net.heartsome.cat.converter.msexcel2007.document;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.ZipUtil;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
public class SpreadsheetDocument {
public static WorkBookPart workBookPart;
public static SpreadsheetPackage spreadsheetPackage;
public static void open(String file) throws InternalFileException {
String root = "";
try {
root = ZipUtil.upZipFile(file, null);
} catch (IOException e1) {
file = file.substring(file.lastIndexOf(File.separator));
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
try {
spreadsheetPackage = new SpreadsheetPackage(root);
} catch (FileNotFoundException e) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
try {
workBookPart = new WorkBookPart();
} catch (FileNotFoundException e) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
}
}
public static void close() {
spreadsheetPackage.close();
spreadsheetPackage = null;
workBookPart = null;
}
}
| 1,315 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
DrawingsPart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/DrawingsPart.java | /**
* DrawingsPart.java
*
* Version information :
*
* Date:2012-8-2
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import net.heartsome.cat.converter.msexcel2007.common.Constants;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.SpreadsheetUtil;
import net.heartsome.cat.converter.msexcel2007.document.drawing.CellAnchor;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class DrawingsPart extends AbstractPart {
// private RelsPart rels;
private List<CellAnchor> cellAnchorList;
public DrawingsPart(String target) throws InternalFileException, FileNotFoundException {
super(SpreadsheetUtil.getPartXml(target, false));
// spreadsheet package root is "drawings"
// rels = new RelsPart(this); // load the relationship of this part
loadShapeAnchor();
}
public List<CellAnchor> getCellAnchorList() {
return this.cellAnchorList;
}
public void updateDrawingObject() throws InternalFileException {
StringBuffer bf = new StringBuffer();
for (CellAnchor c : cellAnchorList) {
c.updateCellAnchor();
bf.append(c.getXmlContent());
}
vu.update(getAutoPilot(), xm, "/xdr:wsDr/text()", bf.toString());
save();
}
private void loadShapeAnchor() {
cellAnchorList = new ArrayList<CellAnchor>();
AutoPilot ap = getAutoPilot();
try {
ap.selectXPath("/xdr:wsDr/xdr:twoCellAnchor | xdr:oneCellAnchor");
while (ap.evalXPath() != -1) {
String anchorXML = vu.getElementFragment();
String fromCol = vu.getElementContent("./xdr:from/xdr:col");
String fromRow = vu.getElementContent("./xdr:from/xdr:row");
CellAnchor a = new CellAnchor(anchorXML, fromRow, fromCol);
cellAnchorList.add(a);
}
} catch (VTDException e) {
}
// sort by row&col ASC
if (cellAnchorList.size() > 0) {
Collections.sort(cellAnchorList, new Comparator<CellAnchor>() {
public int compare(CellAnchor o1, CellAnchor o2) {
int o1r = Integer.parseInt(o1.getFromRow());
int o2r = Integer.parseInt(o2.getFromRow());
int o1c = Integer.parseInt(o1.getFromCol());
int o2c = Integer.parseInt(o2.getFromCol());
if (o1r != o2r) {
return o1r - o2r;
} else {
return o1c - o2c;
}
}
});
}
}
private AutoPilot getAutoPilot() {
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.declareXPathNameSpace(Constants.NAMESPACE_DRAWING_PREFIX_XDR, Constants.NAMESPACE_DRAWING_URL_XDR);
ap.declareXPathNameSpace(Constants.NAMESPACE_DRAWING_PREFIX_A, Constants.NAMESPACE_DRAWING_URL_A);
return ap;
}
}
| 2,840 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ShareStringTablePart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/ShareStringTablePart.java | /**
* ShareStringPart.java
*
* Version information :
*
* Date:2012-8-1
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document;
import java.io.FileNotFoundException;
import java.io.IOException;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.SpreadsheetUtil;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ShareStringTablePart extends AbstractPart {
public ShareStringTablePart(String target) throws InternalFileException, FileNotFoundException {
super(SpreadsheetUtil.getPartXml(target, false));
}
public String getAllStringItem() {
vu.pilot("/sst");
try {
return vu.getElementContent();
} catch (VTDException e) {
logger.error("", e);
}
return null;
}
public int getAllStringItemCount() {
vu.pilot("/sst");
try {
return vu.getChildElementsCount();
} catch (VTDException e) {
logger.error("", e);
}
return 0;
}
public String getStringItemFragment(int index) {
index = index + 1;
String xpath = "/sst/si[" + index + "]";
try {
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath(xpath);
if (ap.evalXPath() != -1) {
String content = vu.getElementFragment();
return content;
} else {
// TODO error
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void updateShareStringTable(String newVal) throws IOException, InternalFileException {
// System.out.println(newVal);
vu.update(null, xm, "/sst/text()", newVal);
saveAndReload();
}
public void updateStringItem(int index, String value) {
index += 1;
vu.update(null, xm, "/sst/si[" + index + "]/text()", value);
}
}
| 1,805 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractPart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/AbstractPart.java | /**
* AbstractPart.java
*
* Version information :
*
* Date:2012-8-1
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.resource.Messages;
import net.heartsome.xml.vtdimpl.VTDUtils;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.XMLModifier;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class AbstractPart {
public static final Logger logger = LoggerFactory.getLogger(AbstractPart.class);
protected String partXmlPath;
protected VTDUtils vu;
protected XMLModifier xm;
protected AbstractPart(String partXmlPath) throws InternalFileException {
this.partXmlPath = partXmlPath;
loadFile();
}
protected void loadFile() throws InternalFileException {
File f = new File(this.partXmlPath);
VTDGen vg = new VTDGen();
FileInputStream fis = null;
byte[] b = new byte[(int) f.length()];
try {
fis = new FileInputStream(f);
fis.read(b);
} catch (IOException e) {
throw new InternalFileException(Messages.getString("msexcel.converter.exception.msg1"));
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
logger.error("",e);
}
}
}
vg.setDoc(b);
try {
vg.parse(true);
vu = new VTDUtils(vg.getNav());
xm = new XMLModifier(vu.getVTDNav());
} catch (VTDException e) {
String message = Messages.getString("msexcel.converter.exception.msg1");
message += "\nFile:"+f.getName()+"\n"+e.getMessage();
throw new InternalFileException(message);
}
}
public String getPartXmlPath() {
return this.partXmlPath;
}
public void save() throws InternalFileException {
FileOutputStream os;
File f = new File(this.partXmlPath);
try {
os = new FileOutputStream(f);
xm.output(os);
os.close();
} catch (Exception e) {
throw new InternalFileException("保存文件出错\n" + e.getMessage());
}
}
public void saveAndReload() throws InternalFileException {
save();
loadFile();
}
}
| 2,294 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
StylesPart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/StylesPart.java | /**
* StylesPart.java
*
* Version information :
*
* Date:2012-8-2
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.SpreadsheetUtil;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class StylesPart extends AbstractPart {
private List<Integer> redStyleIndexs;
public StylesPart(String target) throws InternalFileException, FileNotFoundException {
super(SpreadsheetUtil.getPartXml(target, false));
loadRedFgStyle();
}
/**
* 加载红前景色样式
*/
private boolean isRedColor(int idx) {
idx += 1;
String xpath = "/styleSheet/fonts/font["+idx+"]";
try {
vu.getVTDNav().push();
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
String rgb = vu.getElementAttribute("./color", "rgb");
if(rgb != null && rgb.equals("FFFF0000")){
return true;
}
}
vu.getVTDNav().pop();
} catch (VTDException e) {
e.printStackTrace();
}
return false;
}
private void loadRedFgStyle(){
redStyleIndexs = new ArrayList<Integer>();
String xpath = "/styleSheet/cellXfs/xf";
try {
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
String fIdx = vu.getCurrentElementAttribut("fontId", "");
if(!fIdx.equals("") && isRedColor(Integer.parseInt(fIdx))){
redStyleIndexs.add(vu.getVTDNav().getCurrentDepth() - 1);
}
}
} catch (VTDException e) {
e.printStackTrace();
}
}
public List<Integer> getFilterCellStyle(){
return this.redStyleIndexs;
}
}
| 1,875 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Cell.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/Cell.java | /**
* Cell.java
*
* Version information :
*
* Date:2012-8-3
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.heartsome.cat.converter.msexcel2007.reader.ReaderUtil;
import net.heartsome.xml.vtdimpl.VTDUtils;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class Cell {
private final static Logger logger = LoggerFactory.getLogger(Cell.class);
private String valIdx;
private String content;
private String val;
private Integer styleIdx;
private String dataType;
private ShareStringTablePart ssi;
private List<Object[]> characterStyles;
private Cell() {
this.val = "";
this.styleIdx = -1;
this.dataType = "";
this.ssi = SpreadsheetDocument.workBookPart.getShareStringTablePart();
}
public Cell(String value, Integer styleIndex, String dataType) {
this();
if (dataType.equals("s")) {
this.valIdx = value;
this.content = ssi.getStringItemFragment(Integer.parseInt(this.valIdx));
this.val = loadCellText(content);
this.characterStyles = loadCellCharacterStyle(content, this.val);
} else {
this.val = value;
}
this.styleIdx = styleIndex;
this.dataType = dataType;
}
public String getValue() {
return val;
}
public String getFullContent(){
return content;
}
public List<Object[]> getCellCharacterStyles() {
return this.characterStyles;
}
/**
* 直接将值更新到Share String table中<br>
* 其实在这儿执行这个操作是不合理的,但是为了简化就在这儿做这个操作了<br>
* (更新的操作应该是在{@link SheetPart}中完成,此Cell类只是一个缓存作用)
* @param val ;
*/
public void setValue(String val) {
if(dataType.equals("s")){
if(characterStyles.size() != 0){
// have character style
ssi.updateStringItem(Integer.parseInt(this.valIdx),val+getNonTextContent());
}else {
// no character style
// System.out.println(content);
ssi.updateStringItem(Integer.parseInt(this.valIdx),"<t xml:space=\"preserve\">"+val+"</t>"+getNonTextContent());
}
}
this.val = val;
}
/**
* 更新si节点中的内容
* @param content ;
*/
public void setShareStringItemFullContent(String content){
content = content.replace("<si>", "").replace("</si>", "");
ssi.updateStringItem(Integer.parseInt(this.valIdx), content);
}
/**
* 获取当前单元格的样式序号
* @return ;
*/
public Integer getStyleIndex() {
return styleIdx;
}
public void setStyleIdx(Integer styleIdx) {
this.styleIdx = styleIdx;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
/**
* Get rPh & phoneticPr Element fragment
* @return ;
*/
private String getNonTextContent(){
StringBuffer result = new StringBuffer();
VTDGen vg = new VTDGen();
vg.setDoc(content.getBytes());
VTDUtils vu = null;
try {
vg.parse(true);
vu = new VTDUtils(vg.getNav());
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("/si/rPh | phoneticPr");
while(ap.evalXPath() != -1){
result.append(vu.getElementFragment());
}
} catch (VTDException e) {
e.printStackTrace();
}
return result.toString();
}
/**
* 加载Cell的文本内容
* @param content
* @return ;
*/
private String loadCellText(String content) {
String result = "";
VTDGen vg = new VTDGen();
vg.setDoc(content.getBytes());
VTDUtils vu = null;
try {
vg.parse(true);
vu = new VTDUtils(vg.getNav());
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("/si/r");
if (ap.evalXPath() != -1) {
StringBuffer bf = new StringBuffer();
do {
String tVal = vu.getChildContent("t");
bf.append(tVal);
} while (ap.evalXPath() != -1);
result = bf.toString();
} else {
vu.pilot("/si/t");
result = vu.getElementContent();
}
} catch (VTDException e) {
e.printStackTrace();
}
return result;
}
private List<Object[]> loadCellCharacterStyle(String content, String cellText) {
List<Object[]> result = new ArrayList<Object[]>();
VTDGen vg = new VTDGen();
vg.setDoc(content.getBytes());
VTDUtils vu = null;
try {
vg.parse(true);
vu = new VTDUtils(vg.getNav());
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.selectXPath("/si/r");
if (ap.evalXPath() != -1) {
StringBuffer bf = new StringBuffer();
int start = 0;
do {
String rPrC = vu.getChildContent("rPr");
if (rPrC != null) {
rPrC = "<rPr>" + rPrC + "</rPr>";
bf.append("rPr=\"").append(ReaderUtil.cleanAttribute(rPrC)).append("\"");
} else {
bf.append(" ");
}
String tVal = vu.getChildContent("t");
if(tVal == null || tVal.length() == 0){
bf.delete(0, bf.length()); // clear
continue;
}
int sos = cellText.indexOf(tVal, start);
int length = tVal.length();
Object[] obj = new Object[3];
obj[0] = sos;
obj[1] = start = sos + length;
obj[2] = bf.toString();
result.add(obj);
bf.delete(0, bf.length()); // clear
} while (ap.evalXPath() != -1);
}
} catch (VTDException e) {
logger.error("",e);
}
return result;
}
}
| 5,415 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
SpreadsheetPackage.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/SpreadsheetPackage.java | package net.heartsome.cat.converter.msexcel2007.document;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Spreadsheet的资源包<br>
* 关闭Spreadsheet文档时,需要调用{@link #close()}方法,清理解压后的文件资源
* @author Jason
* @since jdk 1.5
*/
public class SpreadsheetPackage {
/**Spread解压后的第一级目录 */
private String superRoot;
/** 在包中获取文件时的当前目录 */
private String currentRoot;
/** 临时目录,用于记录标记 */
private String tempRoot;
/**
* 构造SpreadsheetPackage对象
* @param root
* 资源根路径,在此路径下,包含了Spreadsheet解压后的所有文件和正确的目录结构
* @throws FileNotFoundException
*/
public SpreadsheetPackage(String root) throws FileNotFoundException {
superRoot = root;
setCurrentRoot(root);
}
/**
* 设置当前根目录
* @param root
* @throws FileNotFoundException
* ;
*/
public void setCurrentRoot(String root) throws FileNotFoundException {
File f = new File(root);
if (!f.exists()) {
throw new FileNotFoundException();
}
this.currentRoot = root;
}
/**
* 获取包的根目录
* @return
*/
public String getPackageSuperRoot() {
return this.superRoot;
}
/**
* 获取当前根目录的名称
* @return ;
*/
public String getRootName() {
File f = new File(currentRoot);
return f.getName();
}
/**
* 回到上一级目录,类似命令行中的cd ..命令,如果当前根目录已经是包的根目录,则不做任何操作
*/
public void back2TopLeve() {
File f = new File(currentRoot);
if (!f.getParent().equals(superRoot)) {
try {
setCurrentRoot(f.getParent());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
/**
* 获取包中文件的路径<br>
* 如获取workbook.xml,则relativePath的值应该为xl/workbook.xml<br>
* 获取xl/workbook.xml后,{@link #currentRoot}/xl将作为根目录
* @param relativePath
* @return
* @throws FileNotFoundException
*/
public String getPackageFilePath(String relativePath) throws FileNotFoundException {
if (relativePath.startsWith("..")) {
back2TopLeve();
relativePath = relativePath.substring(relativePath.indexOf('/') + 1, relativePath.length());
}
File ret = new File(currentRoot);
String[] dirs = relativePath.split("/");
if (!ret.exists()) {
throw new FileNotFoundException(currentRoot);
}
if (dirs.length >= 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
ret = new File(ret, dirs[dirs.length - 1]);
if (!ret.exists()) {
throw new FileNotFoundException(relativePath);
}
}
setCurrentRoot(ret.getParent());
return ret.getAbsolutePath();
}
/**
* 标记当前根目录位置,参考{@link #resetRoot()}
*/
public void markRoot() {
tempRoot = this.currentRoot;
}
/**
* 重置当前根目录到标记位置,参考{@link #markRoot()}<br>
* 如果未调用{@link #markRoot()} 方法则不做任何操作
*/
public void resetRoot() {
if (tempRoot != null && tempRoot.length() != 0) {
this.currentRoot = tempRoot;
tempRoot = "";
}
}
/**
* 删除目录或者文件
* @param file
* 需要处理的文件或文件夹;
*/
private void deleteFileOrFolder(File file) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
this.deleteFileOrFolder(files[i]);
}
}
file.delete();
}
}
/**
* 关闭当前包,关闭时清理资源,删除当前包路径 ;
*/
public void close() {
File f = new File(superRoot);
this.deleteFileOrFolder(f);
}
}
| 3,789 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
HeaderFooter.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/HeaderFooter.java | /**
* HeaderFooter.java
*
* Version information :
*
* Date:2012-8-9
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class HeaderFooter {
private String type;
private String content;
public HeaderFooter(String type, String content) {
this.type = type;
this.content = content;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| 628 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
RelsPart.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/RelsPart.java | package net.heartsome.cat.converter.msexcel2007.document;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import net.heartsome.cat.converter.msexcel2007.common.InternalFileException;
import net.heartsome.cat.converter.msexcel2007.common.SpreadsheetUtil;
import net.heartsome.cat.converter.msexcel2007.document.rels.Relationship;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class RelsPart extends AbstractPart {
private List<Relationship> relationships;
public RelsPart(AbstractPart part) throws InternalFileException, FileNotFoundException {
super(SpreadsheetUtil.getPartRelsTarget(part));
loadRealtionship();
}
public List<Relationship> getRelationshipByType(String type) {
List<Relationship> rlist = new ArrayList<Relationship>();
for (Relationship r : relationships) {
if (r.getType().equals(type)) {
rlist.add(r);
}
}
return rlist;
}
public Relationship getRelationshipById(String rId) {
for (Relationship r : relationships) {
if (r.getId().equals(rId)) {
return r;
}
}
return null;
}
public void loadRealtionship() {
relationships = new ArrayList<Relationship>();
String xpath = "/Relationships/Relationship";
AutoPilot ap = new AutoPilot(vu.getVTDNav());
try {
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
Hashtable<String, String> attrs = vu.getCurrentElementAttributs();
if (attrs == null) {
// TODO Error
}
String id = attrs.get("Id");
String type = attrs.get("Type");
String target = attrs.get("Target");
Relationship rsp = new Relationship(id, type, target);
relationships.add(rsp);
}
} catch (VTDException e) {
logger.error("", e);
}
}
}
| 1,835 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ShapeParagraph.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/drawing/ShapeParagraph.java | /**
* ShapeParagraph.java
*
* Version information :
*
* Date:2012-8-8
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document.drawing;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.heartsome.cat.converter.msexcel2007.reader.ReaderUtil;
import net.heartsome.xml.vtdimpl.VTDUtils;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ShapeParagraph extends AbstractDrawing {
/** the paragraph pure text */
private String pText;
/** the paragraph text style */
private List<Object[]> characterStyles;
public ShapeParagraph(String pXML) {
super(pXML);
this.pText = getCellValueText();
this.characterStyles = getParagraghCharacterStyle(this.pText);
}
public String getParagraghText() {
return this.pText;
}
public void setParagraghText(String newValue) {
try {
if (this.characterStyles.size() > 1) {
// multi r element
vu.pilot(getDeclareNSAutoPilot(), "/a:p/a:r");
xm.insertAfterElement(newValue);
vu.delete(getDeclareNSAutoPilot(), xm, "/a:p/a:r", VTDUtils.PILOT_TO_END);
} else if (this.characterStyles.size() == 1) {
// single r element
vu.update(getDeclareNSAutoPilot(), xm, "/a:p/a:r/a:t/text()", newValue);
}
save();
// saveAndReload();
} catch (VTDException e) {
logger.error("",e);
} catch (IOException e) {
logger.error("",e);
}
}
public List<Object[]> getParagraghCharacterStyle() {
return this.characterStyles;
}
private String getCellValueText() {
String result = "";
try {
AutoPilot ap = getDeclareNSAutoPilot();
ap.selectXPath("/a:p/a:r");
if (ap.evalXPath() != -1) {
StringBuffer bf = new StringBuffer();
do {
String tVal = vu.getChildContent("a:t");
bf.append(tVal);
} while (ap.evalXPath() != -1);
result = bf.toString();
}
} catch (VTDException e) {
logger.error("",e);
}
return result;
}
private List<Object[]> getParagraghCharacterStyle(String cellText) {
List<Object[]> result = new ArrayList<Object[]>();
try {
AutoPilot ap = getDeclareNSAutoPilot();
ap.selectXPath("/a:p/a:r");
if (ap.evalXPath() != -1) {
StringBuffer bf = new StringBuffer();
do {
String rPrC = getChilderFragment("a:rPr");
if (rPrC != null) {
bf.append("ctype=\"a\" rPr=\"").append(ReaderUtil.cleanAttribute(rPrC)).append("\"");
} else {
bf.append("ctype=\"a\">");
}
String tVal = vu.getChildContent("a:t");
int sos = cellText.indexOf(tVal);
int length = tVal.length();
Object[] obj = new Object[3];
obj[0] = sos;
obj[1] = sos + length;
obj[2] = bf.toString();
result.add(obj);
bf.delete(0, bf.length()); // clear
} while (ap.evalXPath() != -1);
}
} catch (VTDException e) {
logger.error("",e);
}
return result;
}
private String getChilderFragment(String elementName) throws VTDException {
String text = null;
AutoPilot ap = getDeclareNSAutoPilot();
ap.selectXPath("./" + elementName);
vu.getVTDNav().push();
if (ap.evalXPath() != -1) {
text = vu.getElementFragment();
}
vu.getVTDNav().pop();
return text;
}
}
| 3,240 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
CellAnchor.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/drawing/CellAnchor.java | /**
* Anchor.java
*
* Version information :
*
* Date:2012-8-7
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document.drawing;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class CellAnchor extends AbstractDrawing{
private String fromRow;
private String fromCol;
private List<ShapeTxBody> shapeList;
public CellAnchor(String anchorXML, String fromRow, String fromCol) {
super(anchorXML);
this.fromRow = fromRow;
this.fromCol = fromRow;
loadShapeAnchor();
}
public void appendShape(ShapeTxBody shape) {
shapeList.add(shape);
}
public String getFromRow() {
return fromRow;
}
public void setFromRow(String fromRow) {
this.fromRow = fromRow;
}
public String getFromCol() {
return fromCol;
}
public void setFromCol(String fromCol) {
this.fromCol = fromCol;
}
public List<ShapeTxBody> getShapeList() {
return shapeList;
}
public void updateCellAnchor(){
for(ShapeTxBody s : shapeList){
s.updateParagragh();
}
String xpath = "//xdr:sp/xdr:txBody";
AutoPilot ap = getDeclareNSAutoPilot();
try {
ap.selectXPath(xpath);
int i = 0;
while (ap.evalXPath() != -1) {
ShapeTxBody s = shapeList.get(i);
xm.remove();
xm.insertAfterElement(s.getXmlContent());
i++;
}
save();
} catch (VTDException e) {
logger.error("",e);
} catch (UnsupportedEncodingException e) {
logger.error("",e);
}
}
private void loadShapeAnchor() {
this.shapeList = new ArrayList<ShapeTxBody>();
String xpath = "//xdr:sp";
AutoPilot ap = getDeclareNSAutoPilot();
try {
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
AutoPilot _ap = getDeclareNSAutoPilot();
_ap.selectXPath("./xdr:txBody");
vu.getVTDNav().push();
if (_ap.evalXPath() != -1) {
ShapeTxBody s = new ShapeTxBody(vu.getElementFragment());
shapeList.add(s);
}
vu.getVTDNav().pop();
}
} catch (VTDException e) {
logger.error("",e);
}
}
}
| 2,147 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
AbstractDrawing.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/drawing/AbstractDrawing.java | /**
* AbstractDrawing.java
*
* Version information :
*
* Date:2012-8-8
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document.drawing;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.heartsome.cat.converter.msexcel2007.common.Constants;
import net.heartsome.xml.vtdimpl.VTDUtils;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
import com.ximpleware.VTDGen;
import com.ximpleware.XMLByteOutputStream;
import com.ximpleware.XMLModifier;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class AbstractDrawing {
public static final Logger logger = LoggerFactory.getLogger(AbstractDrawing.class);
protected VTDUtils vu;
private String xmlContent;
protected XMLModifier xm;
public AbstractDrawing(String xmlContent) {
this.xmlContent = appendNS(xmlContent);
loadXML();
}
protected void save() {
try {
XMLByteOutputStream xbos = new XMLByteOutputStream(xm.getUpdatedDocumentSize());
xm.output(xbos);
this.xmlContent = new String(xbos.getXML());
xbos.close();
// System.out.println(this.xmlContent);
} catch (VTDException e) {
logger.error("",e);
} catch (IOException e) {
logger.error("",e);
}
}
protected void saveAndReload() {
save();
loadXML();
}
public String getXmlContent(){
return this.xmlContent.replace(getNSDeclare2XML(), "");
}
public void setXmlContent(String newValue){
this.xmlContent = newValue;
}
/**
* 获取带有命名空间申明的AtutoPilot对象
* @return ;
*/
protected AutoPilot getDeclareNSAutoPilot() {
AutoPilot ap = new AutoPilot(vu.getVTDNav());
ap.declareXPathNameSpace(Constants.NAMESPACE_DRAWING_PREFIX_XDR, Constants.NAMESPACE_DRAWING_URL_XDR);
ap.declareXPathNameSpace(Constants.NAMESPACE_DRAWING_PREFIX_A, Constants.NAMESPACE_DRAWING_URL_A);
return ap;
}
private void loadXML() {
VTDGen vg = new VTDGen();
vg.setDoc(this.xmlContent.getBytes());
try {
vg.parse(true);
vu = new VTDUtils(vg.getNav());
xm = new XMLModifier(vu.getVTDNav());
} catch (VTDException e) {
logger.error("",e);
}
}
private String appendNS(String xml) {
String nsDecl = getNSDeclare2XML();
StringBuffer xbf = new StringBuffer(xml);
int p = xbf.indexOf(">");
xbf.insert(p, nsDecl);
return xbf.toString();
}
private String getNSDeclare2XML(){
StringBuffer bf = new StringBuffer();
bf.append(" xmlns:").append(Constants.NAMESPACE_DRAWING_PREFIX_XDR);
bf.append("=\"").append(Constants.NAMESPACE_DRAWING_URL_XDR).append("\"");
bf.append(" xmlns:").append(Constants.NAMESPACE_DRAWING_PREFIX_A);
bf.append("=\"").append(Constants.NAMESPACE_DRAWING_URL_A).append("\"");
return bf.toString();
}
}
| 2,751 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
ShapeTxBody.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/drawing/ShapeTxBody.java | /**
* Shape.java
*
* Version information :
*
* Date:2012-8-7
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document.drawing;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDException;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class ShapeTxBody extends AbstractDrawing {
private List<ShapeParagraph> pList;
public ShapeTxBody(String txBodyXml) {
super(txBodyXml);
loadParagraph();
}
public List<ShapeParagraph> getTxBodyParagraghList() {
return pList;
}
void updateParagragh(){
String xpath = "/xdr:txBody/a:p";
AutoPilot ap = getDeclareNSAutoPilot();
try {
ap.selectXPath(xpath);
int i = 0;
while (ap.evalXPath() != -1) {
ShapeParagraph p = pList.get(i);
xm.remove();
xm.insertAfterElement(p.getXmlContent());
i++;
}
save();
} catch (VTDException e) {
logger.error("",e);
} catch (UnsupportedEncodingException e) {
logger.error("",e);
}
}
private void loadParagraph() {
pList = new ArrayList<ShapeParagraph>();
String xpath = "/xdr:txBody/a:p";
AutoPilot ap = getDeclareNSAutoPilot();
try {
ap.selectXPath(xpath);
while (ap.evalXPath() != -1) {
ShapeParagraph p = new ShapeParagraph(vu.getElementFragment());
pList.add(p);
}
} catch (VTDException e) {
logger.error("",e);
}
}
}
| 1,449 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Relationship.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/document/rels/Relationship.java | /**
* ReferenceRelationship.java
*
* Version information :
*
* Date:2012-8-1
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.document.rels;
/**
* @author Jason
* @version
* @since JDK1.6
*/
public class Relationship {
private String id;
private String type;
private String target;
public Relationship(String id, String type, String target) {
this.id = id;
this.type = type;
this.target = target;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Relationship) {
Relationship tempObj = (Relationship) obj;
if (this.id.equals(tempObj.id) && this.type.equals(tempObj.getType())
&& this.target.equals(tempObj.getTarget())) {
return true;
}
} else {
return super.equals(obj);
}
return false;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
}
| 1,111 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.msexcel2007/src/net/heartsome/cat/converter/msexcel2007/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.msexcel2007.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 国际化工具类
* @author peason
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.msexcel2007.resource.message"; //$NON-NLS-1$
/** The Constant RESOURCE_BUNDLE. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
/**
* Instantiates a new messages.
*/
private Messages() {
// Do nothing
}
/**
* Gets the string.
* @param key
* the key
* @return the string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| 985 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
TuMrkBean.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.DejaVuX2/src/net/heartsome/cat/converter/deja_vu_x2/TuMrkBean.java | package net.heartsome.cat.converter.deja_vu_x2;
import java.util.LinkedList;
import java.util.List;
/**
* 这是sdlXliff文件trans-unit/source或target节点下mrk[mtype='seg']节点的内容 pojo类
* @author robert 2012-06-29
*/
public class TuMrkBean {
private String mid;
private String content;
private boolean isSource;
private String comment;
/**
* <div>deja vu x2 xliff文件的状态,下面是duxlf至r8 xliff文件状态的转换</div>
* <table border='1' cellSpacing='1' cellSpadding='0'>
* <tr><td>duxlf</td><td>R8 xliff</td><td>备注</td></tr>
* <tr><td>needs-translation</td><td colSpan='2'>对应R8的未翻译与草稿</td></tr>
* <tr><td>needs-review-translation</td><td>疑问</td><td></td></tr>
* <tr><td>finish</td><td colSpan='2'>在du中的tu节点设置approved="yes"并在target节点上设置state="translated",对应R8为已经批准</td></tr>
* </table>
*/
private String status;
/** 是否锁定
* <div style="color:red">在R8中的锁定格式为 < trans-unit translate="no"> ... </trans-unit>,
* <br>deja vu x2中与之一样</div>
*/
private boolean isLocked;
public TuMrkBean(){}
public TuMrkBean(String mid, String content, String status, boolean isSource){
this.mid = mid;
this.content = content;
this.isSource = isSource;
this.status = status;
}
/**
* 判断当前mrk节点的文本是否为空
* @return
*/
public boolean isTextNull(){
if (content == null || "".equals(content)) {
return true;
}
return false;
}
public String getMid() {
return mid;
}
public void setMid(String mid) {
this.mid = mid;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public boolean isSource() {
return isSource;
}
public void setSource(boolean isSource) {
this.isSource = isSource;
}
/**
* <div>deja vu x2 xliff文件的状态,下面是duxlf至r8 xliff文件状态的转换</div>
* <table border='1' cellSpacing='1' cellSpadding='0'>
* <tr><td>duxlf</td><td>R8 xliff</td><td>备注</td></tr>
* <tr><td>needs-translation</td><td colSpan='2'>对应R8的未翻译与草稿</td></tr>
* <tr><td>needs-review-translation</td><td>疑问</td><td></td></tr>
* <tr><td>finish</td><td colSpan='2'>在du中的tu节点设置approved="yes"并在target节点上设置state="translated",对应R8为已经批准</td></tr>
* </table>
*/
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
/** 是否锁定
* <div style="color:red">在R8中的锁定格式为 < trans-unit translate="no"> ... </trans-unit>,
* <br>而在sdl中这种表达方式为不需翻译,即不会加载到翻译工具界面中。</div>
*/
public boolean isLocked() {
return isLocked;
}
public void setLocked(boolean isLocked) {
this.isLocked = isLocked;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
| 3,076 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.DejaVuX2/src/net/heartsome/cat/converter/deja_vu_x2/Activator.java | package net.heartsome.cat.converter.deja_vu_x2;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.ConverterRegister;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator implements BundleActivator {
// The plug-in ID
public static final String PLUGIN_ID = "net.heartsome.cat.converter.Deja_Vu_X2"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/** deja vu x2文件转换至xliff文件的服务注册器 */
// @SuppressWarnings("rawtypes")
private ServiceRegistration du2XliffSR;
/** xliff文件转换至deja vu x2文件的服务注册器 */
// @SuppressWarnings("rawtypes")
private ServiceRegistration xliff2DuSR;
/**
* The constructor
*/
public Activator() {
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
plugin = this;
Converter du2Xliff = new Du2Xliff();
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Du2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Du2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Du2Xliff.TYPE_NAME_VALUE);
du2XliffSR = ConverterRegister.registerPositiveConverter(context, du2Xliff, properties);
Converter xliff2Du = new Xliff2Du();
properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2Du.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2Du.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2Du.TYPE_NAME_VALUE);
xliff2DuSR = ConverterRegister.registerReverseConverter(context, xliff2Du, properties);
}
/*
* (non-Javadoc)
* @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
if (du2XliffSR != null) {
du2XliffSR.unregister();
du2XliffSR = null;
}
if (xliff2DuSR != null) {
xliff2DuSR.unregister();
xliff2DuSR = null;
}
plugin = null;
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
| 2,356 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2Du.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.DejaVuX2/src/net/heartsome/cat/converter/deja_vu_x2/Xliff2Du.java | package net.heartsome.cat.converter.deja_vu_x2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.deja_vu_x2.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
public class Xliff2Du implements Converter{
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "xlf";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.DU");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "XLIFF to DUXLIFF Conveter";
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor)
throws ConverterException {
Xliff2DuImpl xliff2DuImpl = new Xliff2DuImpl();
return xliff2DuImpl.run(args, monitor);
}
public String getName() {
return NAME_VALUE;
}
public String getType() {
return TYPE_VALUE;
}
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class Xliff2DuImpl{
/** 逆转换的结果文件 */
private String outputFile;
/** 骨架文件的解析游标 */
private VTDNav outputVN;
/** 骨架文件的修改类实例 */
private XMLModifier outputXM;
/** 骨架文件的查询实例 */
private AutoPilot outputAP;
/** hsxliff文件的解析游标 */
private VTDNav hsxlfVN;
/** The encoding. */
private String encoding;
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
// 把转换过程分为两大部分共 10 个任务,其中加载 xliff 文件占 4,替换过程占 6。
monitor.beginTask("Converting...", 10);
Map<String, String> result = new HashMap<String, String>();
String sklFile = params.get(Converter.ATTR_SKELETON_FILE);
String xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
encoding = params.get(Converter.ATTR_SOURCE_ENCODING);
outputFile = params.get(Converter.ATTR_TARGET_FILE);
try {
//先将骨架文件的内容拷贝到目标文件,再解析目标文件
copyFile(sklFile, outputFile);
parseOutputFile(outputFile, xliffFile);
parseXlfFile(xliffFile);
ananysisXlfTU();
outputXM.output(outputFile);
} catch (Exception e) {
e.printStackTrace();
String errorTip = Messages.getString("xlf2du.msg1") + "\n" + e.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e);
}finally{
monitor.done();
}
return result;
}
/**
* 解析结果文件(解析时这个结果文件还是一个骨架文件)
* @param file
* @throws Exception
*/
private void parseOutputFile(String file, String xliffFile) throws Exception {
VTDGen vg = new VTDGen();
if (vg.parseFile(file, true)) {
outputVN = vg.getNav();
outputXM = new XMLModifier(outputVN);
outputAP = new AutoPilot(outputVN);
outputAP.declareXPathNameSpace("sdl", "http://sdl.com/FileTypes/SdlXliff/1.0");
}else {
String errorInfo = MessageFormat.format(Messages.getString("du.parse.msg2"),
new Object[]{new File(xliffFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 解析要被逆转换的xliff文件
* @param xliffFile
* @throws Exception
*/
private void parseXlfFile(String xliffFile) throws Exception {
VTDGen vg = new VTDGen();
if (vg.parseFile(xliffFile, true)) {
hsxlfVN = vg.getNav();
}else {
String errorInfo = MessageFormat.format(Messages.getString("du.parse.msg1"),
new Object[]{new File(xliffFile).getName()});
throw new Exception(errorInfo);
}
}
/**
* 分析xliff文件的每一个 trans-unit 节点
* @throws Exception
*/
private void ananysisXlfTU() throws Exception {
AutoPilot ap = new AutoPilot(hsxlfVN);
AutoPilot childAP = new AutoPilot(hsxlfVN);
VTDUtils vu = new VTDUtils(hsxlfVN);
String xpath = "/xliff/file/body//trans-unit";
String srcXpath = "./source";
String tgtXpath = "./target";
ap.selectXPath(xpath);
int attrIdx = -1;
//trans-unit的id,对应sdl文件的占位符如%%%1%%% 。
String segId = "";
TuMrkBean srcBean = null;
TuMrkBean tgtBean = null;
while (ap.evalXPath() != -1) {
if ((attrIdx = hsxlfVN.getAttrVal("id")) == -1) {
continue;
}
srcBean = new TuMrkBean();
tgtBean = new TuMrkBean();
segId = hsxlfVN.toString(attrIdx);
//处理source节点
hsxlfVN.push();
childAP.selectXPath(srcXpath);
if (childAP.evalXPath() != -1) {
String srcContent = vu.getElementContent();
srcContent = srcContent == null ? "" : srcContent;
srcBean.setContent(srcContent);
srcBean.setSource(true);
}
hsxlfVN.pop();
//处理target节点
String status = ""; //状态,针对target节点,空字符串为未翻译
hsxlfVN.push();
tgtBean.setSource(false);
String tgtContent = null;
childAP.selectXPath(tgtXpath);
if (childAP.evalXPath() != -1) {
tgtContent = vu.getElementContent();
if ((attrIdx = hsxlfVN.getAttrVal("state")) != -1) {
status = hsxlfVN.toString(attrIdx);
}
}
tgtContent = tgtContent == null ? "" : tgtContent;
tgtBean.setContent(tgtContent);
hsxlfVN.pop(); //回到trans-unit节点下
//判断是否处于锁定状态
if ((attrIdx = hsxlfVN.getAttrVal("translate")) != -1) {
if ("no".equalsIgnoreCase(hsxlfVN.toString(attrIdx))) {
tgtBean.setLocked(true);
}
}
//判断是否处于批准状态,若是签发,就没有必要判断了,因为签发了的一定就批准了的
if (!"signed-off".equalsIgnoreCase(status)) {
if ((attrIdx = hsxlfVN.getAttrVal("approved")) != -1) {
if ("yes".equalsIgnoreCase(hsxlfVN.toString(attrIdx))) {
status = "approved"; //批准
}
}
}
//如果是锁定了的。在deja vu里面的完成翻译状态变成未完成翻译。
if (tgtBean.isLocked()) {
status = "needs-translation";
}else {
//将状态切换成du xliff的格式
if ("approved".equals(status) || "signed-off".equals(status)) {
status = "finish";
}else {
status = "needs-translation";
}
//判断是否有疑问这个属性
if (!"finish".equals(status)) {
if ((attrIdx = hsxlfVN.getAttrVal("hs:needs-review")) != -1) {
if ("yes".equals(hsxlfVN.toString(attrIdx))) {
status = "needs-review-translation";
}
}
}
}
tgtBean.setStatus(status);
//获取批注
getNotes(hsxlfVN, tgtBean);
replaceSegment(segId, srcBean, tgtBean);
}
}
/**
* 替换掉骨架文件中的占位符
* @param segId
* @param srcBean
* @param tgtbeBean
*/
private void replaceSegment(String segId, TuMrkBean srcBean, TuMrkBean tgtbeBean) throws Exception {
int attrIdx = -1;
String segStr = "%%%" + segId + "%%%";
String srcXpath = "/xliff/file/body//trans-unit/seg-source//mrk[text()='" + segStr + "']";
//先处理源文
outputAP.selectXPath(srcXpath);
if (outputAP.evalXPath() != -1) {
int textIdx = outputVN.getText();
outputXM.updateToken(textIdx, srcBean.getContent().getBytes("utf-8"));
}
//处理译文
String tgtXpath = "/xliff/file/body//trans-unit/target//mrk[text()='" + segStr + "']";
outputAP.selectXPath(tgtXpath);
if (outputAP.evalXPath() != -1) {
String content = tgtbeBean.getContent();
if (tgtbeBean.getComment().length() > 0) {
if ((attrIdx = hsxlfVN.getAttrVal("comment")) != -1) {
outputXM.updateToken(attrIdx, tgtbeBean.getComment().getBytes("utf-8"));
}else {
String comment = " comment='" + tgtbeBean.getComment() + "'";
outputXM.insertAttribute(comment.getBytes("utf-8"));
}
}
int textIdx = outputVN.getText();
outputXM.updateToken(textIdx, content.getBytes("utf-8"));
//开始处理状态
if ((attrIdx = outputVN.getAttrVal("mid"))!= -1) {
//下面进入target父节点,这个节点里面存放的有文本段的状态
String xpath = "ancestor::target";
outputAP.selectXPath(xpath);
if (outputAP.evalXPath() != -1) {
//下面根据R8的状态。修改sdl的状态。
String status = tgtbeBean.getStatus();
String needInsertAttrStr = "";
if ("".equals(status) || "needs-translation".equals(status)) {
if ((attrIdx = outputVN.getAttrVal("state")) != -1) {
if (!"needs-translation".equals(outputVN.toString(attrIdx))) {
outputXM.updateToken(attrIdx, "needs-translation");
}
}else {
needInsertAttrStr = " state=\"needs-translation\"";
}
}else if ("needs-review-translation".equals(status)) {
if ((attrIdx = outputVN.getAttrVal("state")) != -1) {
if (!"needs-review-translation".equals(outputVN.toString(attrIdx))) {
outputXM.updateToken(attrIdx, "needs-review-translation");
}
}else {
needInsertAttrStr = " state=\"needs-review-translation\"";
}
}else if ("finish".equals(status)) {
if ((attrIdx = outputVN.getAttrVal("state")) != -1) {
if (!"translated".equals(outputVN.toString(attrIdx))) {
outputXM.updateToken(attrIdx, "translated");
}
}else {
needInsertAttrStr = " state=\"translated\"";
}
}
if (needInsertAttrStr.length() > 0) {
outputXM.insertAttribute(needInsertAttrStr.getBytes("utf-8"));
}
//如果是完成翻译或需要锁定,那么就要进行trans-unit节点中进行修改。
if ("finish".equals(status) || tgtbeBean.isLocked()) {
needInsertAttrStr = "";
xpath = "ancestor::trans-unit";
outputAP.selectXPath(xpath);
if (outputAP.evalXPath() != -1) {
//先判断是否锁定,这里的判断优先处理锁定
if (tgtbeBean.isLocked()) {
if ((attrIdx = outputVN.getAttrVal("translate")) != -1) {
if (!"no".equals(outputVN.toString(attrIdx))) {
outputXM.updateToken(attrIdx, "no");
}
}else {
needInsertAttrStr = " translate=\"no\"";
}
}else {
if ((attrIdx = outputVN.getAttrVal("translate")) != -1) {
if ("no".equals(outputVN.toString(attrIdx))) {
outputXM.updateToken(attrIdx, "");
}
}
}
//判断是否完成翻译,完成翻译与锁定状态是对立的,两者只能存在一个
if ("finish".equals(status)) {
if ((attrIdx = outputVN.getAttrVal("approved")) != -1) {
if (!"yes".equals(outputVN.toString(attrIdx))) {
outputXM.updateToken(attrIdx, "yes");
}
}else {
needInsertAttrStr = " approved=\"yes\"";
}
}else {
if ((attrIdx = outputVN.getAttrVal("approved")) != -1) {
if ("yes".equals(outputVN.toString(attrIdx))) {
outputXM.updateToken(attrIdx, "");
}
}
}
if (needInsertAttrStr.length() > 0) {
outputXM.insertAttribute(needInsertAttrStr.getBytes("utf-8"));
}
}
}
}
}
}
}
private void getNotes(VTDNav vn, TuMrkBean tgtBean) throws Exception {
vn.push();
AutoPilot ap = new AutoPilot(vn);
String xpath = "./note";
ap.selectXPath(xpath);
String commentText = "";
int i = 0;
while(ap.evalXPath() != -1){
if (vn.getText() != -1) {
i ++;
String r8NoteText = vn.toString(vn.getText());
if (r8NoteText.indexOf(":") != -1) {
commentText += i + ": " + r8NoteText.substring(r8NoteText.indexOf(":") + 1, r8NoteText.length());
}else {
commentText += i + ": " + r8NoteText;
}
}
}
if (commentText.length() > 0) {
commentText = commentText.substring(0, commentText.length() - 1);
}
tgtBean.setComment(commentText);
vn.pop();
}
}
//----------------------------------------------------Xliff2DuImpl 结束标志--------------------------------------------//
/**
* 将一个文件的数据复制到另一个文件
* @param in
* @param out
* @throws Exception
*/
private static void copyFile(String in, String out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
public static void main(String[] args) {
String comment = "this is a comment;\n";
System.out.println(comment.substring(0, comment.length() - 1));
}
}
| 13,553 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Du2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.DejaVuX2/src/net/heartsome/cat/converter/deja_vu_x2/Du2Xliff.java | package net.heartsome.cat.converter.deja_vu_x2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.deja_vu_x2.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.util.CRC16;
import net.heartsome.util.TextUtil;
import net.heartsome.xml.vtdimpl.VTDUtils;
import org.eclipse.core.runtime.IProgressMonitor;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;
/**
* Deja Vu X2 的双语文件的正向转换器。
* @author robert 2012-007-09
*/
public class Du2Xliff implements Converter{
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "xlf";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("utils.FileFormatUtils.DU");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "DUXLIFF to XLIFF Conveter";
public Map<String, String> convert(Map<String, String> args,
IProgressMonitor monitor) throws ConverterException {
Du2XliffImpl converter = new Du2XliffImpl();
return converter.run(args, monitor);
}
public String getName() {
return NAME_VALUE;
}
public String getType() {
return TYPE_VALUE;
}
public String getTypeName() {
return TYPE_NAME_VALUE;
}
class Du2XliffImpl{
/** 源文件 */
private String inputFile;
/** 转换成的XLIFF文件(临时文件) */
private String xliffFile;
/** 骨架文件(临时文件) */
private String skeletonFile;
/** 源语言 */
private String userSourceLang;
/** 目标语言 */
private String targetLang;
/** 转换的编码格式 */
private String srcEncoding;
/** 将数据输出到XLIFF文件的输出流 */
private FileOutputStream output;
private boolean lockXtrans;
private boolean lock100;
private boolean isSuite;
/** 转换工具的ID */
private String qtToolID;
/** 解析骨架文件的VTDNav实例 */
private VTDNav sklVN;
private XMLModifier sklXM;
public Map<String, String> run(Map<String, String> params, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
monitor.beginTask("Converting...", 5);
Map<String, String> result = new HashMap<String, String>();
inputFile = params.get(Converter.ATTR_SOURCE_FILE);
xliffFile = params.get(Converter.ATTR_XLIFF_FILE);
skeletonFile = params.get(Converter.ATTR_SKELETON_FILE);
targetLang = params.get(Converter.ATTR_TARGET_LANGUAGE);
userSourceLang = params.get(Converter.ATTR_SOURCE_LANGUAGE);
srcEncoding = params.get(Converter.ATTR_SOURCE_ENCODING);
isSuite = false;
if (Converter.TRUE.equalsIgnoreCase(params.get(Converter.ATTR_IS_SUITE))) {
isSuite = true;
}
qtToolID = params.get(Converter.ATTR_QT_TOOLID) != null ? params.get(Converter.ATTR_QT_TOOLID)
: Converter.QT_TOOLID_DEFAULT_VALUE;
lockXtrans = false;
if (Converter.TRUE.equals(params.get(Converter.ATTR_LOCK_XTRANS))) {
lockXtrans = true;
}
lock100 = false;
if (Converter.TRUE.equals(params.get(Converter.ATTR_LOCK_100))) {
lock100 = true;
}
try {
output = new FileOutputStream(xliffFile);
copyFile(inputFile, skeletonFile);
parseSkeletonFile();
writeHeader();
analyzeNodes();
writeString("</body>\n");
writeString("</file>\n");
writeString("</xliff>");
sklXM.output(skeletonFile);
}catch (Exception e) {
e.printStackTrace();
String errorTip = Messages.getString("du2Xlf.msg1") + "\n" + e.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e);
}finally{
try {
output.close();
} catch (Exception e2) {
e2.printStackTrace();
String errorTip = Messages.getString("du2Xlf.msg1") + "\n" + e2.getMessage();
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, errorTip, e2);
}
monitor.done();
}
return result;
}
/**
* 解析骨架文件,此时的骨架文件的内容就是源文件的内容
* @throws Exception
*/
private void parseSkeletonFile() throws Exception{
String errorInfo = "";
VTDGen vg = new VTDGen();
if (vg.parseFile(skeletonFile, true)) {
sklVN = vg.getNav();
sklXM = new XMLModifier(sklVN);
}else {
errorInfo = MessageFormat.format(Messages.getString("du.parse.msg1"),
new Object[]{new File(inputFile).getName()});
throw new Exception(errorInfo);
}
}
private void writeString(String string) throws IOException {
output.write(string.getBytes("utf-8")); //$NON-NLS-1$
}
/**
* 写下XLIFF文件的头节点
*/
private void writeHeader() throws IOException {
writeString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writeString("<xliff version=\"1.2\" xmlns=\"urn:oasis:names:tc:xliff:document:1.2\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xmlns:hs=\""
+ Converter.HSNAMESPACE + "\" "
+ "xsi:schemaLocation=\"urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd "
+ Converter.HSSCHEMALOCATION + "\">\n");
writeString("<file original=\"" + TextUtil.cleanString(inputFile) + "\" source-language=\"" + userSourceLang);
writeString("\" target-language=\"" + ((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang));
writeString("\" datatype=\"" + TYPE_VALUE + "\">\n");
writeString("<header>\n");
writeString(" <skl>\n");
String crc = "";
if (isSuite) {
crc = "crc=\"" + CRC16.crc16(TextUtil.cleanString(skeletonFile).getBytes("utf-8")) + "\"";
}
writeString(" <external-file href=\"" + TextUtil.cleanString(skeletonFile) + "\" " + crc + "/>\n");
writeString(" </skl>\n");
writeString(" <tool tool-id=\"" + qtToolID + "\" tool-name=\"HSStudio\"/>\n");
writeString(" <hs:prop-group name=\"encoding\"><hs:prop prop-type=\"encoding\">"
+ srcEncoding + "</hs:prop></hs:prop-group>\n");
writeString("</header>\n");
writeString("<body>\n");
}
/**
* 分析每一个节点
* @throws Exception
*/
private void analyzeNodes() throws Exception{
AutoPilot ap = new AutoPilot(sklVN);
AutoPilot mrkAP = new AutoPilot(sklVN);
VTDUtils vu = new VTDUtils(sklVN);
String xpath = "/xliff/file/body//trans-unit";
String srxMrkXpath = "./seg-source//mrk[@mtype=\"seg\"]";
String tgtMrkXpath = "./target//mrk[@mtype=\"seg\"]";
//存储源文的集合,key为mrk节点的mid。
Map<String, TuMrkBean> srcMap = new LinkedHashMap<String, TuMrkBean>();
//存储译文的集合,key为mrk节点的mid。
Map<String, TuMrkBean> tgtMap = new LinkedHashMap<String, TuMrkBean>();
//针对骨架文件的每一个源文节点的mrk保存占位符ID
Map<String, Integer> segMap = new HashMap<String, Integer>();
ap.selectXPath(xpath);
int attrIdx = -1;
//xliff 文件的 trans-unit 节点的 id 值
int segId = 0;
while (ap.evalXPath() != -1) {
// 清除所有数据
srcMap.clear();
tgtMap.clear();
sklVN.push();
mrkAP.resetXPath();
mrkAP.selectXPath(srxMrkXpath);
while (mrkAP.evalXPath() != -1) {
// 先获取出节点mrk的属性mid的值
attrIdx = sklVN.getAttrVal("mid");
String mid;
if (attrIdx == -1 || "".equals(mid = sklVN.toString(attrIdx))) {
continue;
}
String srcContent = vu.getElementContent();
if (srcContent != null && !"".equals(srcContent)) {
srcMap.put(mid, new TuMrkBean(mid, srcContent, null, true));
//开始填充占位符
insertPlaceHolder(vu, segId);
segMap.put(mid, segId);
segId ++;
}
}
sklVN.pop();
// 开始处理骨架文件的译文信息
//这是判断状态是否为finish
boolean isApproved = false;
if ((attrIdx = sklVN.getAttrVal("approved")) != -1) {
if ("yes".equals(sklVN.toString(attrIdx))) {
isApproved = true;
}
}
//是否锁定
boolean isLocked = false;
if ((attrIdx = sklVN.getAttrVal("translate")) != -1) {
if ("no".equals(sklVN.toString(attrIdx))) {
isLocked = true;
}
}
sklVN.push();
mrkAP.resetXPath();
mrkAP.selectXPath(tgtMrkXpath);
while (mrkAP.evalXPath() != -1) {
attrIdx = sklVN.getAttrVal("mid");
String mid;
if (attrIdx == -1 || "".equals(mid = sklVN.toString(attrIdx))) {
continue;
}
//注意两个填充占位符方法的位置不同。
if (segMap.get(mid) != null) {
insertPlaceHolder(vu, segMap.get(mid));
TuMrkBean tgtBean = new TuMrkBean();
tgtBean.setSource(false);
tgtBean.setLocked(isLocked);
String content = vu.getElementContent();
if (content != null && !"".equals(content)) {
tgtBean.setContent(content);
}
analysisTuMrkStatus(sklVN, vu, tgtBean, mid, isApproved);
tgtMap.put(mid, tgtBean);
}
}
//开始填充数据到XLIFF文件
for(Entry<String, TuMrkBean> srcEntry : srcMap.entrySet()){
String key = srcEntry.getKey(); //这个key是mid
TuMrkBean srcBean = srcEntry.getValue();
TuMrkBean tgtBean = tgtMap.get(key) == null ? new TuMrkBean() : tgtMap.get(key);
int curSegId = segMap.get(key);
writeSegment(srcBean, tgtBean, curSegId);
}
sklVN.pop();
}
}
/**
* 分析每一个文本段的状态
* @param vn
* @param vu
* @param tgtBean
* @param mid target节点下子节点mrk的mid属性,即唯一id值
*/
private void analysisTuMrkStatus(VTDNav vn, VTDUtils vu, TuMrkBean tgtBean, String mid, boolean isApproved) throws Exception {
vn.push();
String status = ""; //一个空字符串代表未翻译
if (isApproved) {
status = "finish";
}else {
String xpath = "ancestor::target";
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath(xpath);
if(ap.evalXPath() != -1){
int attrIdx = -1;
if ((attrIdx = vn.getAttrVal("state")) != -1) {
status = vn.toString(attrIdx);
}
}
}
tgtBean.setStatus(status);
vn.pop();
}
/**
* 给剔去翻译内容后的骨架文件填充占位符
* @throws Exception
*/
private void insertPlaceHolder(VTDUtils vu, int seg) throws Exception{
String mrkHeader = vu.getElementHead();
String newMrkStr = mrkHeader + "%%%"+ seg +"%%%" + "</mrk>";
sklXM.remove();
sklXM.insertAfterElement(newMrkStr.getBytes(srcEncoding));
}
/**
* 向XLIFF文件输入新生成的trans-unit节点
* @param srcContent
* @param tgtContent
* @param segId
* @throws Exception
*/
private void writeSegment(TuMrkBean srcBean, TuMrkBean tgtBean, int segId) throws Exception{
String srcContent = srcBean.getContent();
StringBuffer tuSB = new StringBuffer();
String status = tgtBean.getStatus() == null ? "" : tgtBean.getStatus();
String tgtStatusStr = "";
String tuAttrStr = "";
boolean isApproved = false;
//具体的意思及与R8的转换请查看tgtBean.getStatus()的注释。
if ("needs-translation".equals(status) || "".equals(status)) {
if (tgtBean.getContent() != null && tgtBean.getContent().length() >= 1) {
tgtStatusStr += " state=\"new\"";
}
}else if ("finish".equals(status)) {
isApproved = true;
tgtStatusStr += " state=\"translated\"";
}else if ("needs-review-translation".equals(status)) {
//疑问
tuAttrStr += " hs:needs-review=\"yes\"";
}
tuAttrStr += isApproved ? " approved=\"yes\"" : "";
tuAttrStr += tgtBean.isLocked() ? " translate=\"no\"" : "";
tuSB.append(" <trans-unit" + tuAttrStr + " id=\"" + segId + "\" xml:space=\"preserve\" >\n");
tuSB.append(" <source xml:lang=\"" + userSourceLang + "\">" + srcContent + "</source>\n");
if (!tgtBean.isTextNull()) {
String tgtContent = tgtBean.getContent();
tuSB.append(" <target" + tgtStatusStr + " xml:lang=\"" +
((targetLang == null || "".equals(targetLang)) ? userSourceLang : targetLang) + "\">"
+ tgtContent + "</target>\n");
}
tuSB.append(" </trans-unit>\n");
writeString(tuSB.toString());
}
}
//----------------------------------------------------Du2XliffImpl 结束标志--------------------------------------------//
private static void copyFile(String in, String out) throws Exception {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
}
}
| 13,388 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Messages.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.DejaVuX2/src/net/heartsome/cat/converter/deja_vu_x2/resource/Messages.java | /**
* Messages.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.deja_vu_x2.resource;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* The Class Messages.
* @author John Zhu
* @version
* @since JDK1.6
*/
public final class Messages {
/** The Constant BUNDLE_NAME. */
private static final String BUNDLE_NAME = "net.heartsome.cat.converter.deja_vu_x2.resource.du"; //$NON-NLS-1$
/** The Constant RESOURCE_BUNDLE. */
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
/**
* Instantiates a new messages.
*/
private Messages() {
// Do nothing
}
/**
* Gets the string.
* @param key
* the key
* @return the string
*/
public static String getString(String key) {
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
}
| 1,026 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Xliff2OpenOfficeTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.openoffice/testSrc/net/heartsome/cat/converter/openoffice/test/Xliff2OpenOfficeTest.java | package net.heartsome.cat.converter.openoffice.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.openoffice.Xliff2OpenOffice;
import org.junit.BeforeClass;
import org.junit.Test;
public class Xliff2OpenOfficeTest {
public static Xliff2OpenOffice converter = new Xliff2OpenOffice();
private String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
private static String xlfODTFile = "rc/Test.odt.xlf";
private static String sklODTFile = "rc/Test.odt.skl";
private static String tgtODTFile = "rc/Test_en-US.odt";
private static String xlfODSFile = "rc/Test.ods.xlf";
private static String sklODSFile = "rc/Test.ods.skl";
private static String tgtODSFile = "rc/Test_en-US.ods";
private static String xlfODGFile = "rc/Test.odg.xlf";
private static String sklODGFile = "rc/Test.odg.skl";
private static String tgtODGFile = "rc/Test_en-US.odg";
@BeforeClass
public static void setUp() {
File tgt = new File(tgtODSFile);
if (tgt.exists()) {
tgt.delete();
}
tgt = new File(tgtODTFile);
if (tgt.exists()) {
tgt.delete();
}
tgt = new File(tgtODGFile);
if (tgt.exists()) {
tgt.delete();
}
}
@Test
public void testConvertODS() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtODSFile);
args.put(Converter.ATTR_XLIFF_FILE, xlfODSFile);
args.put(Converter.ATTR_SKELETON_FILE, sklODSFile);
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8");
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
// args.put(Converter.ATTR_PROGRAM_FOLDER,rootFolder);
Map<String, String> result = converter.convert(args, null);
String target = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(target);
File tgtFile = new File(target);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
@Test
public void testConvertODT() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtODTFile);
args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile);
args.put(Converter.ATTR_SKELETON_FILE, sklODTFile);
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8");
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
// args.put(Converter.ATTR_PROGRAM_FOLDER,rootFolder);
Map<String, String> result = converter.convert(args, null);
String target = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(target);
File tgtFile = new File(target);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
@Test
public void testConvertODG() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_TARGET_FILE, tgtODGFile);
args.put(Converter.ATTR_XLIFF_FILE, xlfODGFile);
args.put(Converter.ATTR_SKELETON_FILE, sklODGFile);
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8");
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
// args.put(Converter.ATTR_PROGRAM_FOLDER,rootFolder);
Map<String, String> result = converter.convert(args, null);
String target = result.get(Converter.ATTR_TARGET_FILE);
assertNotNull(target);
File tgtFile = new File(target);
assertNotNull(tgtFile);
assertTrue(tgtFile.exists());
}
}
| 3,537 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenOffice2XliffTest.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.openoffice/testSrc/net/heartsome/cat/converter/openoffice/test/OpenOffice2XliffTest.java | package net.heartsome.cat.converter.openoffice.test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.openoffice.OpenOffice2Xliff;
import org.junit.BeforeClass;
import org.junit.Test;
public class OpenOffice2XliffTest {
public static OpenOffice2Xliff converter = new OpenOffice2Xliff();
private static String rootFolder = "/data/john/Workspaces/CAT/HSTS7/";
private static String srcODTFile = "rc/Test.odt";
private static String xlfODTFile = "rc/Test.odt.xlf";
private static String sklODTFile = "rc/Test.odt.skl";
private static String srcODSFile = "rc/Test.ods";
private static String xlfODSFile = "rc/Test.ods.xlf";
private static String sklODSFile = "rc/Test.ods.skl";
private static String srcODGFile = "rc/Test.odg";
private static String xlfODGFile = "rc/Test.odg.xlf";
private static String sklODGFile = "rc/Test.odg.skl";
@BeforeClass
public static void setUp() {
File xlf = new File(xlfODTFile);
if (xlf.exists()) {
xlf.delete();
}
File skl = new File(sklODTFile);
if (skl.exists()) {
skl.delete();
}
xlf = new File(xlfODSFile);
if (xlf.exists()) {
xlf.delete();
}
skl = new File(sklODSFile);
if (skl.exists()) {
skl.delete();
}
xlf = new File(xlfODGFile);
if (xlf.exists()) {
xlf.delete();
}
skl = new File(sklODGFile);
if (skl.exists()) {
skl.delete();
}
}
//
// @Test(expected = ConverterException.class)
// public void testConvertMissingCatalog() throws ConverterException {
// Map<String, String> args = new HashMap<String, String>();
// args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
// args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
// // args.put(Converter.ATTR_CATALOGUE, rootFolder +
// // "catalogue/catalogue.xml");
// args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
// args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
//
// Map<String, String> result = converter.convert(args, null);
// String xliff = result.get(Converter.ATTR_XLIFF_FILE);
// assertNotNull(xliff);
//
// File xlfFile = new File(xliff);
// assertNotNull(xlfFile);
// assertTrue(xlfFile.exists());
// }
//
// @Test(expected = ConverterException.class)
// public void testConvertMissingSRX() throws ConverterException {
// Map<String, String> args = new HashMap<String, String>();
// args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
// args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
// args.put(Converter.ATTR_CATALOGUE, rootFolder
// + "catalogue/catalogue.xml");
// // args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
// args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
//
// Map<String, String> result = converter.convert(args, null);
// String xliff = result.get(Converter.ATTR_XLIFF_FILE);
// assertNotNull(xliff);
//
// File xlfFile = new File(xliff);
// assertNotNull(xlfFile);
// assertTrue(xlfFile.exists());
// }
//
// @Test(expected = ConverterException.class)
// public void testConvertMissingINI() throws ConverterException {
// Map<String, String> args = new HashMap<String, String>();
// args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$
// args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
// args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
// args.put(Converter.ATTR_CATALOGUE, rootFolder
// + "catalogue/catalogue.xml");
// args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
// // args.put(Converter.ATTR_PROGRAM_FOLDER,rootFolder);
//
// Map<String, String> result = converter.convert(args, null);
// String xliff = result.get(Converter.ATTR_XLIFF_FILE);
// assertNotNull(xliff);
//
// File xlfFile = new File(xliff);
// assertNotNull(xlfFile);
// assertTrue(xlfFile.exists());
// }
@Test
public void testConvertODS() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcODSFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfODSFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklODSFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
@Test
public void testConvertODT() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcODTFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfODTFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklODTFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
@Test
public void testConvertODG() throws ConverterException {
Map<String, String> args = new HashMap<String, String>();
args.put(Converter.ATTR_SOURCE_FILE, srcODGFile); //$NON-NLS-1$
args.put(Converter.ATTR_XLIFF_FILE, xlfODGFile); //$NON-NLS-1$
args.put(Converter.ATTR_SKELETON_FILE, sklODGFile); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_LANGUAGE, "zh-CN"); //$NON-NLS-1$
args.put(Converter.ATTR_SOURCE_ENCODING, "UTF-8"); //$NON-NLS-1$
args.put(Converter.ATTR_CATALOGUE, rootFolder
+ "catalogue/catalogue.xml");
args.put(Converter.ATTR_SRX, rootFolder + "srx/default_rules.srx");
args.put(Converter.ATTR_PROGRAM_FOLDER, rootFolder);
Map<String, String> result = converter.convert(args, null);
String xliff = result.get(Converter.ATTR_XLIFF_FILE);
assertNotNull(xliff);
File xlfFile = new File(xliff);
assertNotNull(xlfFile);
assertTrue(xlfFile.exists());
}
}
| 7,334 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
OpenOffice2Xliff.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.openoffice/src/net/heartsome/cat/converter/openoffice/OpenOffice2Xliff.java | /**
* OpenOffice2Xliff.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.openoffice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.ConverterException;
import net.heartsome.cat.converter.openoffice.resource.Messages;
import net.heartsome.cat.converter.util.ConverterUtils;
import net.heartsome.cat.converter.util.Progress;
import net.heartsome.util.CRC16;
import net.heartsome.util.TextUtil;
import net.heartsome.xml.Document;
import net.heartsome.xml.Element;
import net.heartsome.xml.SAXBuilder;
import net.heartsome.xml.XMLOutputter;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.xml.sax.SAXException;
/**
* The Class OpenOffice2Xliff.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class OpenOffice2Xliff implements Converter {
/** The Constant TYPE_VALUE. */
public static final String TYPE_VALUE = "x-openoffice";
/** The Constant TYPE_NAME_VALUE. */
public static final String TYPE_NAME_VALUE = Messages.getString("openoffice.TYPE_NAME_VALUE");
/** The Constant NAME_VALUE. */
public static final String NAME_VALUE = "OpenOffice to XLIFF Conveter";
// 内部实现所依赖的转换器
/** The dependant converter. */
private Converter dependantConverter;
/**
* for test to initialize depend on converter.
*/
public OpenOffice2Xliff() {
dependantConverter = Activator.getXMLConverter(Converter.DIRECTION_POSITIVE);
}
/**
* 运行时把所依赖的转换器,在初始化的时候通过构造函数注入。.
* @param converter
* the converter
*/
public OpenOffice2Xliff(Converter converter) {
dependantConverter = converter;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getName()
* @return
*/
public String getName() {
return NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getType()
* @return
*/
public String getType() {
return TYPE_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#getTypeName()
* @return
*/
public String getTypeName() {
return TYPE_NAME_VALUE;
}
/**
* (non-Javadoc)
* @see net.heartsome.cat.converter.Converter#convert(java.util.Map, org.eclipse.core.runtime.IProgressMonitor)
* @param args
* @param monitor
* @return
* @throws ConverterException
*/
public Map<String, String> convert(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
OpenOffice2XliffImpl converter = new OpenOffice2XliffImpl();
return converter.run(args, monitor);
}
/**
* The Class OpenOffice2XliffImpl.
* @author John Zhu
* @version
* @since JDK1.6
*/
class OpenOffice2XliffImpl {
/** The merged. */
private Document merged;
/** The merged root. */
private Element mergedRoot;
/** The zip in. */
private ZipInputStream zipIn;
/** The zip out. */
private ZipOutputStream zipOut;
/** The src file. */
private String srcFile;
/** The skeleton. */
private String skeleton;
/** The is suite. */
private boolean isSuite;
private String type ;
/**
* Count segments.
* @param string
* the string
* @return the int
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private int countSegments(String string) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(string);
Element root = doc.getRootElement();
return root.getChild("file").getChild("body").getChildren("trans-unit").size(); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
/**
* Save entry.
* @param entry
* the entry
* @param name
* the name
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void saveEntry(ZipEntry entry, String name) throws IOException {
ZipEntry content = new ZipEntry(entry.getName());
content.setMethod(ZipEntry.DEFLATED);
zipOut.putNextEntry(content);
FileInputStream input = new FileInputStream(name);
byte[] array = new byte[1024];
int len;
while ((len = input.read(array)) > 0) {
zipOut.write(array, 0, len);
}
zipOut.closeEntry();
input.close();
}
/**
* Adds the file.
* @param xliff
* the xliff
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void addFile(String xliff) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xliff);
Element root = doc.getRootElement();
Element file = root.getChild("file"); //$NON-NLS-1$
Element newFile = new Element("file", merged); //$NON-NLS-1$
newFile.clone(file, merged);
mergedRoot.addContent(newFile);
File f = new File(xliff);
f.delete();
}
/**
* Update xliff.
* @param xliff
* the xliff
* @param original
* the original
* @throws SAXException
* the SAX exception
* @throws IOException
* Signals that an I/O exception has occurred.
*/
private void updateXliff(String xliff, String original) throws SAXException, IOException {
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(xliff);
Element root = doc.getRootElement();
Element file = root.getChild("file"); //$NON-NLS-1$
file.setAttribute("datatype", type); //$NON-NLS-1$
// file.setAttribute("original", TextUtil.cleanString(srcFile)); //$NON-NLS-1$
Element header = file.getChild("header"); //$NON-NLS-1$
Element elePropGroup = new Element("hs:prop-group", doc); //$NON-NLS-1$
elePropGroup.setAttribute("name", "document"); //$NON-NLS-1$ //$NON-NLS-2$
Element originalProp = new Element("hs:prop", doc); //$NON-NLS-1$
originalProp.setAttribute("prop-type", "original"); //$NON-NLS-1$ //$NON-NLS-2$
originalProp.setText(original);
header.addContent("\n"); //$NON-NLS-1$
elePropGroup.addContent(originalProp);
Element srcFileProp = new Element("hs:prop", doc); //$NON-NLS-1$
srcFileProp.setAttribute("prop-type", "sourcefile"); //$NON-NLS-1$ //$NON-NLS-2$
srcFileProp.setText(srcFile);
header.addContent("\n"); //$NON-NLS-1$
elePropGroup.addContent(srcFileProp);
header.addContent(elePropGroup);
Element ext = header.getChild("skl").getChild("external-file"); //$NON-NLS-1$ //$NON-NLS-2$
ext.setAttribute("href", TextUtil.cleanString(skeleton)); //$NON-NLS-1$
if (isSuite) {
ext.setAttribute("crc", "" + CRC16.crc16(TextUtil.cleanString(skeleton).getBytes("UTF-8"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
XMLOutputter outputter = new XMLOutputter();
FileOutputStream output = new FileOutputStream(xliff);
outputter.output(doc, output);
output.close();
}
private void setType(String args ){
if("true".equals(args)){
type="x-msoffice2003";
}else{
type=TYPE_VALUE;
}
}
/**
* Run.
* @param args
* the args
* @param monitor
* the monitor
* @return the map< string, string>
* @throws ConverterException
* the converter exception
*/
public Map<String, String> run(Map<String, String> args, IProgressMonitor monitor) throws ConverterException {
monitor = Progress.getMonitor(monitor);
Map<String, String> result = new HashMap<String, String>();
srcFile = args.get(Converter.ATTR_SOURCE_FILE);
setType(args.get("isofficefile"));
String xliff = args.get(Converter.ATTR_XLIFF_FILE);
skeleton = args.get(Converter.ATTR_SKELETON_FILE);
isSuite = false;
if (Converter.TRUE.equals(args.get(Converter.ATTR_IS_SUITE))) {
isSuite = true;
}
try {
// 把总任务分为压缩文件中的条目个数+1;其中最后一个任务为 library3 写合并后的 xliff 文件。
ZipFile zipFile = new ZipFile(srcFile);
int size = zipFile.size();
int totalTask = size + 1;
monitor.beginTask("", totalTask);
merged = new Document(null, "xliff", null, null); //$NON-NLS-1$
mergedRoot = merged.getRootElement();
mergedRoot.setAttribute("version", "1.2"); //$NON-NLS-1$ //$NON-NLS-2$
mergedRoot.setAttribute("xmlns", "urn:oasis:names:tc:xliff:document:1.2"); //$NON-NLS-1$ //$NON-NLS-2$
mergedRoot.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); //$NON-NLS-1$ //$NON-NLS-2$
mergedRoot.setAttribute("xmlns:hs", Converter.HSNAMESPACE); //$NON-NLS-1$
mergedRoot
.setAttribute(
"xsi:schemaLocation", "urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd " + Converter.HSSCHEMALOCATION); //$NON-NLS-1$ //$NON-NLS-2$
zipOut = new ZipOutputStream(new FileOutputStream(skeleton));
zipIn = new ZipInputStream(new FileInputStream(srcFile));
ZipEntry entry = null;
while ((entry = zipIn.getNextEntry()) != null) {
// 标识当前的条目是否委托其他转换器进行转换
boolean isDelegation = false;
// 检查是否取消操作
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("openoffice.cancel"));
}
String messagePattern = Messages.getString("openoffice.OpenOffice2Xliff.msg1");
String message = MessageFormat.format(messagePattern, new Object[] { entry.getName() });
monitor.subTask(message);
if (entry.getName().matches(".*\\.[xX][mM][lL]")) { //$NON-NLS-1$
File f = new File(entry.getName());
String name = f.getName();
String tmpFileName = name.substring(0, name.lastIndexOf(".")); //$NON-NLS-1$
if (tmpFileName.length() < 3) {
tmpFileName += "_tmp"; //$NON-NLS-1$
}
File tmp = File.createTempFile(tmpFileName, ".xml");
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = zipIn.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
try {
Map<String, String> table = new HashMap<String, String>();
table.put(Converter.ATTR_SOURCE_FILE, tmp.getAbsolutePath());
table.put(Converter.ATTR_XLIFF_FILE, tmp.getAbsolutePath() + ".xlf"); //$NON-NLS-1$
table.put(Converter.ATTR_SKELETON_FILE, tmp.getAbsolutePath() + ".skl"); //$NON-NLS-1$
table.put(Converter.ATTR_CATALOGUE, args.get(Converter.ATTR_CATALOGUE));
table.put(Converter.ATTR_SOURCE_LANGUAGE, args.get(Converter.ATTR_SOURCE_LANGUAGE));
table.put(Converter.ATTR_TARGET_LANGUAGE, args.get(Converter.ATTR_TARGET_LANGUAGE));
table.put(Converter.ATTR_SOURCE_ENCODING, args.get(Converter.ATTR_SOURCE_ENCODING));
table.put(Converter.ATTR_PROGRAM_FOLDER, args.get(Converter.ATTR_PROGRAM_FOLDER));
table.put(Converter.ATTR_SEG_BY_ELEMENT, args.get(Converter.ATTR_SEG_BY_ELEMENT));
table.put(Converter.ATTR_SRX, args.get(Converter.ATTR_SRX));
table.put(Converter.ATTR_FORMAT, TYPE_VALUE);
Converter converter = dependantConverter;
boolean hasError = false;
Map<String, String> res = null;
try {
// 委托其它转换器进行操作
res = converter.convert(table, Progress.getSubMonitor(monitor, 1));
isDelegation = true;
} catch (ConverterException ce) {
hasError = true;
}
if (res == null || res.get(Converter.ATTR_XLIFF_FILE) == null) {
hasError = true;
}
if (!hasError) {
if (countSegments(tmp.getAbsolutePath() + ".xlf") > 0) { //$NON-NLS-1$
updateXliff(tmp.getAbsolutePath() + ".xlf", entry.getName()); //$NON-NLS-1$
addFile(tmp.getAbsolutePath() + ".xlf"); //$NON-NLS-1$
ZipEntry content = new ZipEntry(entry.getName() + ".skl"); //$NON-NLS-1$
content.setMethod(ZipEntry.DEFLATED);
zipOut.putNextEntry(content);
FileInputStream input = new FileInputStream(tmp.getAbsolutePath() + ".skl"); //$NON-NLS-1$
byte[] array = new byte[1024];
while ((len = input.read(array)) > 0) {
zipOut.write(array, 0, len);
}
zipOut.closeEntry();
input.close();
} else {
saveEntry(entry, tmp.getAbsolutePath());
}
File skl = new File(tmp.getAbsolutePath() + ".skl"); //$NON-NLS-1$
skl.delete();
File xlf = new File(tmp.getAbsolutePath() + ".xlf"); //$NON-NLS-1$
xlf.delete();
} else {
saveEntry(entry, tmp.getAbsolutePath());
}
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
// do nothing
saveEntry(entry, tmp.getAbsolutePath());
}
tmp.delete();
} else {
// not an XML file
File tmp = File.createTempFile("zip", ".tmp"); //$NON-NLS-1$ //$NON-NLS-2$
FileOutputStream output = new FileOutputStream(tmp.getAbsolutePath());
byte[] buf = new byte[1024];
int len;
while ((len = zipIn.read(buf)) > 0) {
output.write(buf, 0, len);
}
output.close();
saveEntry(entry, tmp.getAbsolutePath());
tmp.delete();
}
// 如果当前条目没有委托其它转换器进行操作,则需要把任务的处理进度加 1
if (!isDelegation) {
monitor.worked(1);
}
}
zipOut.close();
// output final XLIFF
// fixed a bug 572 by john. keep a well-format of xliff. add a empty
// file into xliff if root have not file element.
List<Element> files = mergedRoot.getChildren("file"); //$NON-NLS-1$
if (files.size() == 0) {
Element file = new Element("file", merged); //$NON-NLS-1$
file.setAttribute("original", srcFile); //$NON-NLS-1$
file.setAttribute("source-language", args.get("srcLang")); //$NON-NLS-1$ //$NON-NLS-2$
file.setAttribute("datatype", type); //$NON-NLS-1$
Element header = new Element("header", merged); //$NON-NLS-1$
Element body = new Element("body", merged); //$NON-NLS-1$
file.addContent(header);
file.addContent("\n"); //$NON-NLS-1$
file.addContent(body);
mergedRoot.addContent(file);
header = null;
body = null;
file = null;
}
files = null;
// 生成 xliff 文件
if (monitor.isCanceled()) {
throw new OperationCanceledException(Messages.getString("openoffice.cancel"));
}
monitor.subTask(Messages.getString("openoffice.OpenOffice2Xliff.task2"));
XMLOutputter outputter = new XMLOutputter();
outputter.preserveSpace(true);
FileOutputStream output = new FileOutputStream(xliff);
outputter.output(merged, output);
output.close();
result.put(Converter.ATTR_XLIFF_FILE, xliff);
monitor.worked(1);
} catch(OperationCanceledException e){
throw e;
} catch (Exception e) {
if (Converter.DEBUG_MODE) {
e.printStackTrace();
}
ConverterUtils.throwConverterException(Activator.PLUGIN_ID, Messages.getString("openoffice.OpenOffice2Xliff.msg2"), e);
} finally {
monitor.done();
}
return result;
}
}
}
| 16,042 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Activator.java | /FileExtraction/Java_unseen/heartsome_translationstudio8/hsconverter/net.heartsome.cat.converter.openoffice/src/net/heartsome/cat/converter/openoffice/Activator.java | /**
* Activator.java
*
* Version information :
*
* Date:Jan 14, 2010
*
* Copyright notice :
*/
package net.heartsome.cat.converter.openoffice;
import java.util.Properties;
import net.heartsome.cat.converter.Converter;
import net.heartsome.cat.converter.util.AndFilter;
import net.heartsome.cat.converter.util.ConverterRegister;
import net.heartsome.cat.converter.util.EqFilter;
import net.heartsome.cat.converter.xml.Xliff2Xml;
import net.heartsome.cat.converter.xml.Xml2Xliff;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
/**
* The Class Activator.The activator class controls the plug-in life cycle.
* @author John Zhu
* @version
* @since JDK1.6
*/
public class Activator implements BundleActivator {
// The plug-in ID
/** The Constant PLUGIN_ID. */
public static final String PLUGIN_ID = "net.heartsome.cat.converter.openoffice";
// The shared instance
/** The plugin. */
private static Activator plugin;
/** The bundle context. */
private static BundleContext bundleContext;
/** The positive tracker. */
private static ServiceTracker positiveTracker;
/** The reverse tracker. */
private static ServiceTracker reverseTracker;
/**
* The constructor.
*/
public Activator() {
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void start(BundleContext context) throws Exception {
plugin = this;
bundleContext = context;
// tracker the xml converter service
String positiveFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xml2Xliff.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_POSITIVE)).toString();
positiveTracker = new ServiceTracker(context, context.createFilter(positiveFilter), new XmlPositiveCustomizer());
positiveTracker.open();
String reverseFilter = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()),
new EqFilter(Converter.ATTR_TYPE, Xliff2Xml.TYPE_VALUE), new EqFilter(Converter.ATTR_DIRECTION,
Converter.DIRECTION_REVERSE)).toString();
reverseTracker = new ServiceTracker(context, context.createFilter(reverseFilter), new XmlReverseCustomize());
reverseTracker.open();
}
/**
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
* @param context
* @throws Exception
*/
public void stop(BundleContext context) throws Exception {
positiveTracker.close();
reverseTracker.close();
plugin = null;
bundleContext = null;
}
/**
* Returns the shared instance.
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
// just for test
/**
* Gets the xML converter.
* @param direction
* the direction
* @return the xML converter
*/
public static Converter getXMLConverter(String direction) {
if (Converter.DIRECTION_POSITIVE.equals(direction)) {
return new Xml2Xliff();
} else {
return new Xliff2Xml();
}
}
/**
* The Class XmlPositiveCustomizer.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlPositiveCustomizer implements ServiceTrackerCustomizer {
/**
* (non-Javadoc).
* @param reference
* the reference
* @return the object
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference)
*/
public Object addingService(ServiceReference reference) {
Converter converter = (Converter) bundleContext.getService(reference);
Converter inx2Xliff = new OpenOffice2Xliff(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, OpenOffice2Xliff.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, OpenOffice2Xliff.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, OpenOffice2Xliff.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerPositiveConverter(bundleContext, inx2Xliff,
properties);
return registration;
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void modifiedService(ServiceReference reference, Object service) {
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void removedService(ServiceReference reference, Object service) {
ServiceRegistration registration = (ServiceRegistration) service;
registration.unregister();
bundleContext.ungetService(reference);
}
}
/**
* The Class XmlReverseCustomize.
* @author John Zhu
* @version
* @since JDK1.6
*/
private class XmlReverseCustomize implements ServiceTrackerCustomizer {
/**
* (non-Javadoc).
* @param reference
* the reference
* @return the object
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#addingService(org.osgi.framework.ServiceReference)
*/
public Object addingService(ServiceReference reference) {
Converter converter = (Converter) bundleContext.getService(reference);
Converter xliff2Inx = new Xliff2OpenOffice(converter);
Properties properties = new Properties();
properties.put(Converter.ATTR_NAME, Xliff2OpenOffice.NAME_VALUE);
properties.put(Converter.ATTR_TYPE, Xliff2OpenOffice.TYPE_VALUE);
properties.put(Converter.ATTR_TYPE_NAME, Xliff2OpenOffice.TYPE_NAME_VALUE);
ServiceRegistration registration = ConverterRegister.registerReverseConverter(bundleContext, xliff2Inx,
properties);
return registration;
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#modifiedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void modifiedService(ServiceReference reference, Object service) {
}
/**
* (non-Javadoc).
* @param reference
* the reference
* @param service
* the service
* @see org.osgi.util.tracker.ServiceTrackerCustomizer#removedService(org.osgi.framework.ServiceReference,
* java.lang.Object)
*/
public void removedService(ServiceReference reference, Object service) {
ServiceRegistration registration = (ServiceRegistration) service;
registration.unregister();
bundleContext.ungetService(reference);
}
}
}
| 7,034 | Java | .java | heartsome/translationstudio8 | 83 | 45 | 18 | 2014-06-03T17:56:15Z | 2020-10-13T06:46:15Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.